Skip to content

Commit 703b425

Browse files
committed
fix(safe eval): support optional chaining
jsep parses `?.`, `?.[]` and `?.()` and marks the node `optional`, but the safe evaluator ignored the flag. So under the default eval: "safe" a filter such as $.books[?(@.meta?.tag === "x")] threw "Cannot read properties of undefined (reading 'tag')" as soon as one item had no `meta`, while eval: "native" returned the match. A member or call link now returns a short-circuit marker when it is optional and its object or callee is null or undefined; the outer links pass it up and the whole chain evaluates to undefined, like in JS. The object is now evaluated before the property and the callee before the arguments (JS order), so a skipped `?.[expr]` or `?.(args)` does not run `expr` or `args`.
1 parent 970bdb2 commit 703b425

2 files changed

Lines changed: 114 additions & 11 deletions

File tree

‎src/Safe-Script.js‎

Lines changed: 59 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,21 @@ const UNOPS = Object.assign(Object.create(null), /** @type {UnaryOperatorTable}
150150
void: () => undefined
151151
}));
152152

153+
/**
154+
* Returned by a member or call link when an optional link (`?.`) met
155+
* `null` or `undefined`: the rest of the chain is skipped and the chain
156+
* evaluates to `undefined`.
157+
*/
158+
const SHORT_CIRCUIT = Symbol('optional chain short-circuit');
159+
160+
/**
161+
* @param {UnknownResult} value
162+
* @returns {boolean}
163+
*/
164+
const isNullish = (value) => {
165+
return value === null || value === undefined;
166+
};
167+
153168
const SafeEval = {
154169
/**
155170
* @param {jsep.Expression} ast
@@ -182,10 +197,8 @@ const SafeEval = {
182197
case 'Literal':
183198
return SafeEval.evalLiteral(/** @type {jsep.Literal} */ (ast));
184199
case 'MemberExpression':
185-
return SafeEval.evalMemberExpression(
186-
/** @type {jsep.MemberExpression} */ (ast),
187-
subs
188-
);
200+
case 'CallExpression':
201+
return SafeEval.evalChain(ast, subs);
189202
case 'UnaryExpression':
190203
return SafeEval.evalUnaryExpression(
191204
/** @type {jsep.UnaryExpression} */ (ast),
@@ -196,11 +209,6 @@ const SafeEval = {
196209
/** @type {jsep.ArrayExpression} */ (ast),
197210
subs
198211
);
199-
case 'CallExpression':
200-
return SafeEval.evalCallExpression(
201-
/** @type {jsep.CallExpression} */ (ast),
202-
subs
203-
);
204212
case 'AssignmentExpression':
205213
return SafeEval.evalAssignmentExpression(
206214
/** @type {AssignmentExpression} */ (ast),
@@ -288,12 +296,50 @@ const SafeEval = {
288296
return ast.value;
289297
},
290298

299+
/**
300+
* Evaluates a whole member/call chain such as `@.a?.b.c()`.
301+
* @param {jsep.Expression} ast
302+
* @param {Substitutions} subs
303+
* @returns {UnknownResult}
304+
*/
305+
evalChain (ast, subs) {
306+
const result = SafeEval.evalChainLink(ast, subs);
307+
return result === SHORT_CIRCUIT ? undefined : result;
308+
},
309+
310+
/**
311+
* Evaluates one link of a member/call chain. Unlike `evalAst`, this
312+
* passes `SHORT_CIRCUIT` up so an earlier `?.` skips the later links.
313+
* @param {jsep.Expression} ast
314+
* @param {Substitutions} subs
315+
* @returns {UnknownResult}
316+
*/
317+
evalChainLink (ast, subs) {
318+
if (ast.type === 'MemberExpression') {
319+
return SafeEval.evalMemberExpression(
320+
/** @type {jsep.MemberExpression} */ (ast),
321+
subs
322+
);
323+
}
324+
if (ast.type === 'CallExpression') {
325+
return SafeEval.evalCallExpression(
326+
/** @type {jsep.CallExpression} */ (ast),
327+
subs
328+
);
329+
}
330+
return SafeEval.evalAst(ast, subs);
331+
},
332+
291333
/**
292334
* @param {jsep.MemberExpression} ast
293335
* @param {Substitutions} subs
294336
* @returns {UnknownResult}
295337
*/
296338
evalMemberExpression (ast, subs) {
339+
const obj = SafeEval.evalChainLink(ast.object, subs);
340+
if (obj === SHORT_CIRCUIT || (ast.optional && isNullish(obj))) {
341+
return SHORT_CIRCUIT;
342+
}
297343
const prop = String(
298344
// NOTE: `String(value)` throws error when
299345
// value has overwritten the toString method to return non-string
@@ -302,7 +348,6 @@ const SafeEval = {
302348
? SafeEval.evalAst(ast.property, subs) // `object[property]`
303349
: ast.property.name // `object.property` property is Identifier
304350
);
305-
const obj = SafeEval.evalAst(ast.object, subs);
306351
const result = getSafeProperty(obj, prop);
307352
if (typeof result === 'function') {
308353
return result.bind(obj); // arrow functions aren't affected by bind.
@@ -343,8 +388,11 @@ const SafeEval = {
343388
* @returns {UnknownResult}
344389
*/
345390
evalCallExpression (ast, subs) {
391+
const func = SafeEval.evalChainLink(ast.callee, subs);
392+
if (func === SHORT_CIRCUIT || (ast.optional && isNullish(func))) {
393+
return SHORT_CIRCUIT;
394+
}
346395
const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
347-
const func = SafeEval.evalAst(ast.callee, subs);
348396
if (
349397
isBlockedFunction(func) ||
350398
args.some((arg) => isBlockedFunction(arg))

‎test/test.safe-eval.js‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,61 @@ checkBuiltInVMAndNodeVM(function (vmType, setBuiltInState) {
196196
});
197197
assert.deepEqual(result, expected);
198198
});
199+
describe('optional chaining in safe mode script', () => {
200+
const shelf = {
201+
books: [
202+
{title: 'A', meta: {tags: ['x']}},
203+
{title: 'B', meta: null},
204+
{title: 'C'}
205+
]
206+
};
207+
/**
208+
* @param {string} path
209+
* @returns {unknown}
210+
*/
211+
const titles = (path) => jsonpath({
212+
json: shelf,
213+
path,
214+
eval: 'safe'
215+
});
216+
it('member access (`?.`)', () => {
217+
assert.deepEqual(
218+
titles('$.books[?(@.meta?.tags[0] === "x")].title'),
219+
['A']
220+
);
221+
assert.deepEqual(
222+
titles('$.books[?(@.meta?.tags === undefined)].title'),
223+
['B', 'C']
224+
);
225+
});
226+
it('computed member access (`?.[]`)', () => {
227+
assert.deepEqual(
228+
titles('$.books[?(@.meta?.["tags"]?.length)].title'),
229+
['A']
230+
);
231+
});
232+
it('call (`?.()`)', () => {
233+
assert.deepEqual(
234+
titles('$.books[?(@.meta?.tags.join("") === "x")].title'),
235+
['A']
236+
);
237+
assert.deepEqual(
238+
titles('$.books[?(@.meta?.nope?.() === undefined)].title'),
239+
['A', 'B', 'C']
240+
);
241+
});
242+
it('skips the rest of the chain', () => {
243+
assert.deepEqual(
244+
titles('$.books[?(n = 0, @.meta?.[n = 1], n === 0)].title'),
245+
['B', 'C']
246+
);
247+
});
248+
it('still throws without `?.`', () => {
249+
assert.throws(() => {
250+
titles('$.books[?(@.meta.tags)].title');
251+
}, /Cannot read properties of null \(reading 'tags'\)/v);
252+
});
253+
});
199254
describe('binary operators in safe mode script', () => {
200255
// eslint-disable-next-line no-shadow -- Convenient
201256
const json = {

0 commit comments

Comments
 (0)