Skip to content

fix(safe eval): support optional chaining - #296

Open
bardrop wants to merge 1 commit into
JSONPath-Plus:mainfrom
bardrop-oss:fix-safe-eval-optional-chaining
Open

bardrop wants to merge 1 commit into
JSONPath-Plus:mainfrom
bardrop-oss:fix-safe-eval-optional-chaining

Conversation

@bardrop

@bardrop bardrop commented Nov 16, 2026

Copy link
Copy Markdown

PR description

Fixes #295.

jsep already parses ?., ?.[...] and ?.() and sets optional: true on the node, but the safe evaluator ignored it. So with the default eval: "safe", $.books[?(@.meta?.tag === "x")] threw Cannot read properties of undefined (reading 'tag') on the first item without meta, while eval: "native" worked.

What changed in src/Safe-Script.js:

  • A member or call link that is optional and whose object / callee is null or undefined returns a short-circuit marker. Outer links pass it up, and evalAst turns it into undefined at the end of the chain. So @.a?.b.c() gives undefined when @.a is missing, like in JS.
  • The object is now evaluated before the property, and the callee before the arguments. That is the JS order, and it means a skipped ?.[expr] or ?.(args) does not run expr / args.
  • jsep has no chain node, so (a?.b).c parses the same as a?.b.c and is also short-circuited. I think that is the better side to fall on, since the unparenthesized form is the common one.

The security checks (getSafeProperty, blocked functions) run on the same values as before.

I also compared the safe evaluator against plain JS on 41 member/call chain expressions (nullish and non-nullish links, computed keys, optional calls, side effects in skipped parts). Main differs on 23 of them, this branch on none.

Checklist

  • - Added tests
  • - Ran npm test, ensuring linting passes
  • - Adjust README documentation if relevant (not needed: README does not list the supported syntax)

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`.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optional chaining (?.) throws with the default safe eval

1 participant