@zvenigora/ng-eval-core 0.12.1 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +160 -3
- package/README.md +270 -7
- package/fesm2022/zvenigora-ng-eval-core.mjs +816 -61
- package/fesm2022/zvenigora-ng-eval-core.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -14,13 +14,170 @@ Versions 0.1.104–0.1.107 are on npm without entries here.
|
|
|
14
14
|
|
|
15
15
|
---
|
|
16
16
|
|
|
17
|
+
## [0.13.1] - 2026-10-22
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
- **The package README is the package's whole documentation**, and every `javascript` block in it
|
|
21
|
+
is executed by a case. It gains the sections the repository README held — evaluation,
|
|
22
|
+
compilation, async evaluation and compilation, the supported syntax, case-insensitive evaluation
|
|
23
|
+
and evaluation with state — and opens with Install, Sibling packages and Security, quoting each
|
|
24
|
+
peer range verbatim. The repository README no longer has to be read for the API. No code
|
|
25
|
+
change.
|
|
26
|
+
- **The evaluation section brought in from the repository README states the built-ins
|
|
27
|
+
precisely**: over the default, empty context the global built-ins are out of an expression's
|
|
28
|
+
reach, but the methods of the values it holds stay callable, as `'abc'.toUpperCase()` does. No
|
|
29
|
+
code change and no behaviour change ([F23](../../docs/backlog-retired.md#f23)).
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## [0.13.0] - 2026-10-20
|
|
34
|
+
|
|
35
|
+
**The route through `this` is closed, in both halves — the value and the receiver — and the
|
|
36
|
+
evaluation context is no longer writable by an expression, nor obtainable as a value the walk
|
|
37
|
+
produces.** A minor carrying breaking changes
|
|
38
|
+
([A39](../../docs/backlog-retired.md#a39), [A42](../../docs/backlog-retired.md#a42); the
|
|
39
|
+
[A35 plan](../../docs/a35/plan.md)). Every change is internal: the `.d.ts` is byte-identical to
|
|
40
|
+
0.12.1's.
|
|
41
|
+
|
|
42
|
+
**It does not close every route.** A container the host itself provides, a context the host nests
|
|
43
|
+
in the evaluation data or hands back behind a promise, the context `EvalResult.trace` holds after
|
|
44
|
+
an expression evaluated `this.k`, and a host-built AST that uses one `this` node in two places all
|
|
45
|
+
remain documented limits in every version, 0.13.0 included —
|
|
46
|
+
`SECURITY.md`'s [documented limits](../../SECURITY.md#documented-limits) state each one. So
|
|
47
|
+
0.12.1's [mitigations](../../SECURITY.md#mitigations) still apply unchanged: place no listed
|
|
48
|
+
function in the context, and in a browser serve a Content Security Policy without `'unsafe-eval'`.
|
|
49
|
+
|
|
50
|
+
**`eval-signals` 0.6.0 and `eval-forms` 0.6.0 are the releases that admit it.** Every earlier one
|
|
51
|
+
excludes it by its own peer range — `eval-signals` 0.5.1 declares `>=0.11.0 <0.13.0` and
|
|
52
|
+
`eval-forms` 0.5.0 `>=0.12.0 <0.13.0` — so all three move together, and bumping `eval-core` alone
|
|
53
|
+
leaves a peer graph nothing can satisfy.
|
|
54
|
+
|
|
55
|
+
### Breaking
|
|
56
|
+
- **`this` evaluates only as the object of a member access** — `this.k`, `this["k"]`, `this.fn()`,
|
|
57
|
+
and any spelling of `this` in that place under `caseInsensitive` — which resolves against the
|
|
58
|
+
context as before. Anywhere else it now throws
|
|
59
|
+
`Access to "this" outside a member access is blocked for security reasons`: as a value, an
|
|
60
|
+
argument or an operand, `typeof this` included. Up to 0.12.1 it evaluated to the `EvalContext`
|
|
61
|
+
the walk ran against. Together with the receiver entry below, this **closes the route through
|
|
62
|
+
`this`** that 0.12.1's Security entry states as open ([A39](../../docs/backlog-retired.md#a39)).
|
|
63
|
+
Keep 0.12.1's mitigations in place regardless — place no listed function in the context, and
|
|
64
|
+
serve a Content Security Policy without `'unsafe-eval'` — since a container the host itself
|
|
65
|
+
provides remains a documented limit, which this release does not close.
|
|
66
|
+
- **The assertions it changes**: three, all in `eval-forms`' suite, none in `eval-core`'s or
|
|
67
|
+
`eval-signals`'. Each evaluated `this` outside a member access to reach a rule's context and read
|
|
68
|
+
its lookups ([D5](../../docs/backlog-retired.md#d5)). They now take the context where it is built.
|
|
69
|
+
- **A function the context holds is called with a guarded view of the `EvalContext`**, not the
|
|
70
|
+
context and not the object behind it. **The rule**: every receiver the evaluator resolved out of
|
|
71
|
+
the context's own chain is now that view. In practice that is a bare call, `fn()`; a bare tagged
|
|
72
|
+
template, `` fn`x` ``; and `this.fn()` for any key the context resolves — one held directly on
|
|
73
|
+
it, one a lookup answers, one a prior scope answers without declaring a `thisArg`, and one bound
|
|
74
|
+
by a scope the expression or a source function pushed.
|
|
75
|
+
**What is unchanged**: `obj.fn()` and `ns.fn()`, a prior scope's **declared** `thisArg`, and a
|
|
76
|
+
call on an object the context merely holds — including one that refers back to the context
|
|
77
|
+
itself. Those receivers are the host's own, not the evaluator's choice.
|
|
78
|
+
On the view, `push` and `pop` still act on the real context, so a function that pushes or pops a
|
|
79
|
+
scope is unaffected. **Every other read throws**
|
|
80
|
+
`Access to "<key>" on the evaluation context is blocked for security reasons`, and **a write
|
|
81
|
+
throws** a `TypeError` in strict mode, which compiled module code is, or is silently dropped in
|
|
82
|
+
sloppy mode; up to 0.12.1 a read answered from the context and a write landed on it.
|
|
83
|
+
- **What this breaks**: a method held directly on the context and called as `this.fn()` can no
|
|
84
|
+
longer reach its sibling keys through its own `this`.
|
|
85
|
+
- **The migration**: give that object its own named scope with an explicit `thisArg`, which this
|
|
86
|
+
release does not change. `ns.fn()` and `obj.fn()` are unchanged too — only a receiver the
|
|
87
|
+
evaluator resolved out of the context's own chain is narrowed.
|
|
88
|
+
- **The view's identity is not stable**: every call receives a new one, even two calls in one
|
|
89
|
+
evaluation on one context. Do not key anything on a function's `this` — not a `WeakMap`, not a
|
|
90
|
+
`Set`, not an identity comparison. Nothing retains a view, which is what keeps the guard's cost
|
|
91
|
+
off the ordinary one-shot evaluation.
|
|
92
|
+
- **`push` and `pop` are the ones the context's class defines**, found on its prototype chain, so
|
|
93
|
+
a subclass override is used and a property set on the instance is not. A context whose class
|
|
94
|
+
defines neither has them refused like any other key.
|
|
95
|
+
- Together with the entry above this closes [A39](../../docs/backlog-retired.md#a39), the
|
|
96
|
+
receiver half of it. The member-write policy still receives the real context as its write
|
|
97
|
+
target, so a context implementing `checkMemberWrite` sees what it always did.
|
|
98
|
+
- **The assertions it changes**: six — two in `eval-core`'s suite pinning a receiver's identity,
|
|
99
|
+
two pinning a context method's reach into its siblings, and two in `eval-signals`'. Each is
|
|
100
|
+
rewritten to assert the new contract, none is dropped. Together with the three in `eval-forms`
|
|
101
|
+
named above, nine in all across the three suites.
|
|
102
|
+
- **A write whose target is the evaluation context now throws**
|
|
103
|
+
`Write to the evaluation context is blocked for security reasons`, where up to 0.12.1 it
|
|
104
|
+
succeeded ([A42](../../docs/backlog-retired.md#a42)).
|
|
105
|
+
- **What this is.** `this.k = v` is a member write, and for a key the context does **not**
|
|
106
|
+
resolve the target is the `EvalContext` itself — so the write added an own property to the
|
|
107
|
+
evaluator's own object. It applies to every form the evaluator offers: dotted and computed
|
|
108
|
+
member writes, compound writes and the update expressions. It is matched **by class**, so it
|
|
109
|
+
also covers a signal context and a context reached under some other name.
|
|
110
|
+
- **What is unchanged**: a write to a key the context **does** resolve. `this.n = 7`, `n = 7`
|
|
111
|
+
and `this.n++`, for a key the caller's object holds, land on that object exactly as before,
|
|
112
|
+
through `EvalContext.set` and the write policy a subclass may override. That is the write path
|
|
113
|
+
consumers use, and it is untouched.
|
|
114
|
+
- **What this breaks**: an expression that wrote to the context under a key nothing resolves now
|
|
115
|
+
throws where it used to succeed. Nothing could read the result back — `EvalContext.get`
|
|
116
|
+
resolves through the scopes, the original, the prior scopes and the lookups, and never off the
|
|
117
|
+
instance — so an expression that depended on reading it back cannot exist; one that made the
|
|
118
|
+
write and ignored it will now fail.
|
|
119
|
+
- **Native writers are refused the same way**: `Object.assign`, `Object.defineProperty`,
|
|
120
|
+
`Object.defineProperties`, `Object.setPrototypeOf`, `Object.freeze`, `Object.seal`,
|
|
121
|
+
`Object.preventExtensions`, `Reflect.set`, `Reflect.defineProperty`, `Reflect.deleteProperty`,
|
|
122
|
+
`Reflect.setPrototypeOf` and `Reflect.preventExtensions`, including when reached through
|
|
123
|
+
`call`, `apply` or `bind`. A context that implements `checkMemberWrite` is still asked first,
|
|
124
|
+
so its own refusal is still the error a consumer sees.
|
|
125
|
+
- **The context is also not a value an expression can hold.** Every value the walk pushes is
|
|
126
|
+
refused if it is an `EvalContext`, so a bare identifier naming one, a member read of one, an
|
|
127
|
+
object spread or destructuring of one, and `Object.values` or `JSON.stringify` of one all throw
|
|
128
|
+
`Access to the evaluation context is blocked for security reasons`. The one exemption is the
|
|
129
|
+
walk's **own** context as a member's object, matched by identity as well as position, so
|
|
130
|
+
`this.k` is unaffected — it resolves through the context's chain and reads nothing off the
|
|
131
|
+
instance. **Two routes are outside this by construction**: the check reads the value pushed and
|
|
132
|
+
does not look inside it, and it does not run on `evaluateAsync`'s promise unwrap, which happens
|
|
133
|
+
after the walk — so a host that places its own context inside a value an expression can read,
|
|
134
|
+
nested in an object or an array or behind a promise, still gets it back as a result. Reading it
|
|
135
|
+
back one hop later is refused.
|
|
136
|
+
- **A `checkMemberWrite` held as an instance property now throws.** The policy and the opt-in
|
|
137
|
+
that turns object recording on are both resolved from the context's **prototype chain**, so a
|
|
138
|
+
policy on the instance would be inert. Rather than fail open in silence, building an
|
|
139
|
+
`EvalState` around such a context throws, naming the condition and the remedy.
|
|
140
|
+
**Declare it as a *method*** — `class C extends EvalContext { override checkMemberWrite(write) { … } }`,
|
|
141
|
+
which is what `@zvenigora/ng-eval-signals` does. **A class field will not do**:
|
|
142
|
+
`class C extends EvalContext { checkMemberWrite = (write) => … }` is an instance property, as
|
|
143
|
+
is an assignment in a constructor or `context.checkMemberWrite = fn` after the fact, and all
|
|
144
|
+
three now throw. This is the same rule as for `push` and `pop` above, and for the same reason:
|
|
145
|
+
an expression must not be able to supply one — and the only party who can still hold one on an
|
|
146
|
+
instance is a host that meant it, which deserves to be told exactly what to change.
|
|
147
|
+
- **A context whose class defines `push` but no `pop` is refused at the first scope push**,
|
|
148
|
+
with the same named refusal. The pop runs in a `finally`, where a throw would replace the
|
|
149
|
+
error the body was propagating, so it is tolerant; refusing the pair at the push is what
|
|
150
|
+
keeps them symmetric. No context `EvalContext.fromContext` produces has this shape.
|
|
151
|
+
- **Why it is in this release rather than later.** The own property shadowed a method of the
|
|
152
|
+
class, and the evaluator calls `push` on the context at four sites, so a planted function was
|
|
153
|
+
invoked with the real context as its `this` — the capture that made a cross-context disclosure
|
|
154
|
+
possible. It is also an **availability** defect: a plant over `push` that evaluates anything
|
|
155
|
+
recurses until the stack is gone and persists on the context, so every later evaluation on a
|
|
156
|
+
reused context throws. `@zvenigora/ng-eval-signals` and `@zvenigora/ng-eval-forms` both reuse
|
|
157
|
+
one context by design; neither is exposed, because a signal context refuses the planting write
|
|
158
|
+
through `checkMemberWrite`, and `eval-forms` evaluates through `eval-signals`.
|
|
159
|
+
- **Methods the evaluator calls on a context are taken from its class**, not from the instance,
|
|
160
|
+
at the scope pushes and pops, the write path and the policy — so an own property arriving by
|
|
161
|
+
any other route is not what the evaluator invokes.
|
|
162
|
+
|
|
163
|
+
### Performance
|
|
164
|
+
- **These checks cost about 10% on the member-write path, and less elsewhere.** Measured against
|
|
165
|
+
0.12.1's evaluator in plain Node, production bundles, twelve paired rotations per path, medians:
|
|
166
|
+
a member write **+10.0%**, a bare call **+7.6%**, a member read **+1.85%**. The member write is
|
|
167
|
+
positive in all twelve rotations, so it is a consistent cost rather than one that disappears
|
|
168
|
+
into run-to-run variation, and it is stated here as such: an expression that assigns to object
|
|
169
|
+
properties in a loop is the shape that pays most. The member read is indistinguishable from the
|
|
170
|
+
baseline. No evaluation result changes.
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
17
174
|
## [0.12.1] - 2026-10-17
|
|
18
175
|
|
|
19
176
|
**Partial hardening of the call sandbox, which does not close every route, so keep
|
|
20
177
|
[`SECURITY.md`'s mitigations](../../SECURITY.md#mitigations) in place whatever the version.** A
|
|
21
178
|
tagged template's tag goes through the call sandbox ([A36](../../docs/backlog-retired.md#a36)), and
|
|
22
179
|
a dangerous function value is refused at the call, `new` and tag sites and at every other read the
|
|
23
|
-
walk makes but `typeof`'s operand ([A35](../../docs/backlog.md#a35)). A sequence leaves one value on
|
|
180
|
+
walk makes but `typeof`'s operand ([A35](../../docs/backlog-retired.md#a35)). A sequence leaves one value on
|
|
24
181
|
the stack ([A37](../../docs/backlog-retired.md#a37)). Two routes past the walk's own values stay
|
|
25
182
|
open: a container the host provides, which stays a limit, and a route through `this`, which 0.13.0
|
|
26
183
|
closes. The Security entry below states both, and `SECURITY.md`'s
|
|
@@ -69,7 +226,7 @@ ranges are `>=0.11.0 <0.13.0` and `>=0.12.0 <0.13.0`.
|
|
|
69
226
|
- **A tag that is not a function** throws the call's error, `Cannot call undefined or null
|
|
70
227
|
function` or `Value is not a function: <type>`. It threw a `TypeError` from `apply`.
|
|
71
228
|
- **A call, `new` or tagged template whose callee is a dangerous function is refused by its value,
|
|
72
|
-
under any name — [A35](../../docs/backlog.md#a35).** The sandboxes read the callee's written name,
|
|
229
|
+
under any name — [A35](../../docs/backlog-retired.md#a35).** The sandboxes read the callee's written name,
|
|
73
230
|
so with `eval` in the context as `run`, `run("1+1")` gave 2. `new`'s list of names never held the
|
|
74
231
|
timers either. In a browser application with zone.js, `new setTimeout("<code>", 0)` constructed
|
|
75
232
|
under the timer's own name, and zone.js handed the string to the browser's timer, which runs it
|
|
@@ -89,7 +246,7 @@ ranges are `>=0.11.0 <0.13.0` and `>=0.12.0 <0.13.0`.
|
|
|
89
246
|
before the call. Such a callee is a sequence, a conditional, a logical, an assignment, or a
|
|
90
247
|
parenthesised or optional-chain expression.
|
|
91
248
|
- **Every read of a dangerous function the walk makes is refused, except as a callee, a tag or
|
|
92
|
-
`typeof`'s operand — [A35](../../docs/backlog.md#a35).** The call sandbox checked only the
|
|
249
|
+
`typeof`'s operand — [A35](../../docs/backlog-retired.md#a35).** The call sandbox checked only the
|
|
93
250
|
callee, so a listed value handed on as anything else reached the native code that calls it. With
|
|
94
251
|
`eval` in the context, `["1+1"].map(eval)` gave `[2]` and `eval.call(null, "1+1")` gave 2. With
|
|
95
252
|
`Function`, `Function.call(null, "return 7")()` gave 7. Every published version up to 0.12.0 is
|
package/README.md
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
1
|
# @zvenigora/ng-eval-core
|
|
2
2
|
|
|
3
|
-
An expression evaluator for Angular.
|
|
3
|
+
An expression evaluator for Angular: JavaScript expression parsing and evaluation, built on [acorn](https://github.com/acornjs/acorn) and exposed as injectable services. An expression is evaluated against a context the host supplies, and resolves names only against that context. This file is the package's whole documentation.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## Install
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```sh
|
|
8
|
+
npm install --save @zvenigora/ng-eval-core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Peer dependencies: `@angular/core >=19.0.0`, `acorn ^8.11.2`, `acorn-walk ^8.3.0` and `js-sha256 ^0.10.1 || ^0.11.0 || ^0.12.0 || ^1.0.0`.
|
|
12
|
+
|
|
13
|
+
## Sibling packages
|
|
14
|
+
|
|
15
|
+
- [`@zvenigora/ng-eval-signals`](https://github.com/zvenigora/ng-eval/tree/master/modules/eval-signals#readme) — an expression over a context of signals as an Angular `Signal`, which recomputes exactly when a key the expression read has changed.
|
|
16
|
+
- [`@zvenigora/ng-eval-forms`](https://github.com/zvenigora/ng-eval/tree/master/modules/eval-forms#readme) — Angular form field properties driven by expressions that arrive as strings at runtime, for Reactive Forms and Signal Forms.
|
|
17
|
+
|
|
18
|
+
The sources for all three are in the [@zvenigora/ng-eval](https://github.com/zvenigora/ng-eval) repository.
|
|
8
19
|
|
|
9
|
-
|
|
20
|
+
## Security
|
|
10
21
|
|
|
11
|
-
**
|
|
22
|
+
**ng-eval is not a sandbox.** An expression reaches whatever its context holds, and every function in the context runs with the host's privileges. [`SECURITY.md`](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md) covers the threat model, the protections the code has, and their [documented limits](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md#documented-limits) — read it before evaluating an expression you did not write. [GHSA-qrqj-3445-3rjx](https://github.com/Zvenigora/ng-eval/security/advisories/GHSA-qrqj-3445-3rjx), dangerous functions and the evaluation context reachable past the call sandbox, affects `@zvenigora/ng-eval-core` up to 0.12.1 and is fixed in 0.13.0. `SECURITY.md` also records [reviewed external advisories](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md#reviewed-external-advisories) — advisories raised against related projects and whether this library shares the defect. [GHSA-pj3p-xpg7-h7gw](https://github.com/Zvenigora/jse-eval/security/advisories/GHSA-pj3p-xpg7-h7gw), the case-insensitive guard bypass reported against the separate `@zvenigora/jse-eval` package, **does not apply to `@zvenigora/ng-eval-core`**: this library does not depend on `jse-eval`, and the advisory's proof-of-concept was run against this evaluator and is blocked.
|
|
12
23
|
|
|
13
24
|
## Exported entry points
|
|
14
25
|
|
|
15
|
-
|
|
26
|
+
Each service below is documented in its own section. `EvalService` (evaluation) and `CompilerService` (compile once, call repeatedly) are used throughout.
|
|
16
27
|
|
|
17
|
-
`
|
|
28
|
+
Each service also has a form that needs no injector. The free functions `parse`, `extract`, `evaluate`, `evaluateAsync`, `compile`, `call`, `compileAsync` and `callAsync` are what the services call. `parse` takes the expression text; `extract`, `compile` and `compileAsync` take the AST node `parse` returns, not a string; and `evaluate`, `evaluateAsync`, `call` and `callAsync` take an `EvalState`, which `EvalState.fromContext(context, options)` builds.
|
|
18
29
|
|
|
19
30
|
### Parsing — `ParserService`
|
|
20
31
|
|
|
@@ -27,6 +38,124 @@ const ast = service.parse('1 + foo'); // an ESTree AST
|
|
|
27
38
|
ast.type; // 'BinaryExpression'
|
|
28
39
|
```
|
|
29
40
|
|
|
41
|
+
The result of the parse is an AST (abstract syntax tree):
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"type": "BinaryExpression",
|
|
46
|
+
"start": 0,
|
|
47
|
+
"end": 7,
|
|
48
|
+
"left": {
|
|
49
|
+
"type": "Literal",
|
|
50
|
+
"start": 0,
|
|
51
|
+
"end": 1,
|
|
52
|
+
"value": 1,
|
|
53
|
+
"raw": "1"
|
|
54
|
+
},
|
|
55
|
+
"operator": "+",
|
|
56
|
+
"right": {
|
|
57
|
+
"type": "Identifier",
|
|
58
|
+
"start": 4,
|
|
59
|
+
"end": 7,
|
|
60
|
+
"name": "foo"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`ParserService` parses with `ecmaVersion: 2020`, keeps a cache of 100 parses, and sets `extractExpressions`, so `parse` returns the expression itself — the `BinaryExpression` above — rather than the `Program` around it. `EvalService`, `CompilerService` and `DiscoveryService` parse with `extractExpressions` off, into a `Program`, which is what lets an expression be a statement list.
|
|
66
|
+
|
|
67
|
+
### Evaluation — `EvalService`
|
|
68
|
+
|
|
69
|
+
`simpleEval(expression, context)` evaluates an expression against the given context. Without a context, the context is empty.
|
|
70
|
+
|
|
71
|
+
```javascript
|
|
72
|
+
import { EvalService } from '@zvenigora/ng-eval-core';
|
|
73
|
+
|
|
74
|
+
const service = inject(EvalService);
|
|
75
|
+
|
|
76
|
+
const expression = '2 + 3 * a';
|
|
77
|
+
const context = { a: 10 };
|
|
78
|
+
const result = service.simpleEval(expression, context); // 32
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Since the default context is empty, an expression cannot reach JavaScript's global built-ins, such as `Math`, `parseInt` or `Date`. The methods of the values it holds stay callable: `'abc'.toUpperCase()` and `[3, 1, 2].map(x => x * 2)` run over an empty context. To allow the globals, add them to the context passed to `simpleEval`:
|
|
82
|
+
|
|
83
|
+
```javascript
|
|
84
|
+
const context = {
|
|
85
|
+
Date,
|
|
86
|
+
Array,
|
|
87
|
+
Object,
|
|
88
|
+
encodeURI,
|
|
89
|
+
decodeURI,
|
|
90
|
+
isFinite,
|
|
91
|
+
isNaN,
|
|
92
|
+
JSON,
|
|
93
|
+
Math,
|
|
94
|
+
parseFloat,
|
|
95
|
+
parseInt,
|
|
96
|
+
RegExp,
|
|
97
|
+
// ...myCustomPropertiesAndFunctions,
|
|
98
|
+
};
|
|
99
|
+
service.simpleEval('Math.max(1, 2) + parseInt("40")', context); // 42
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Compilation — `CompilerService`
|
|
103
|
+
|
|
104
|
+
```javascript
|
|
105
|
+
import { CompilerService } from '@zvenigora/ng-eval-core';
|
|
106
|
+
|
|
107
|
+
const service = inject(CompilerService);
|
|
108
|
+
|
|
109
|
+
const fn = service.compile('x + y');
|
|
110
|
+
const context = { x: 1, y: 2 };
|
|
111
|
+
const options = { caseInsensitive: false };
|
|
112
|
+
const value = service.simpleCall(fn, context, options); // 3
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Async evaluation and compilation
|
|
116
|
+
|
|
117
|
+
Asynchronous evaluation is limited, and based on promises. The walk itself is synchronous, and a promise is awaited once it has finished, wherever it sits in the result: the result itself, or an element or property of an array or object the expression builds.
|
|
118
|
+
|
|
119
|
+
```javascript
|
|
120
|
+
import { EvalService } from '@zvenigora/ng-eval-core';
|
|
121
|
+
|
|
122
|
+
const service = inject(EvalService);
|
|
123
|
+
|
|
124
|
+
const context = {
|
|
125
|
+
one: 1,
|
|
126
|
+
two: 2,
|
|
127
|
+
asyncFunc: async (a: number, b: number) => { return await (a+b); }
|
|
128
|
+
};
|
|
129
|
+
const expr = 'asyncFunc(one, two)';
|
|
130
|
+
const value = await service.simpleEvalAsync(expr, context); // 3
|
|
131
|
+
|
|
132
|
+
await service.simpleEvalAsync('[asyncFunc(one, two), two]', context); // [3, 2]
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
```javascript
|
|
136
|
+
import { CompilerService } from '@zvenigora/ng-eval-core';
|
|
137
|
+
|
|
138
|
+
const service = inject(CompilerService);
|
|
139
|
+
|
|
140
|
+
const context = {
|
|
141
|
+
one: 1,
|
|
142
|
+
two: 2,
|
|
143
|
+
promiseFunc: (a: number, b: number) => {
|
|
144
|
+
return new Promise((resolve) => {
|
|
145
|
+
setTimeout(() => {
|
|
146
|
+
return resolve(a + b);
|
|
147
|
+
}, 10);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
const expr = 'promiseFunc(one, two)';
|
|
152
|
+
const fn = service.compileAsync(expr);
|
|
153
|
+
const result = await service.simpleCallAsync(fn, context); // 3
|
|
154
|
+
|
|
155
|
+
const nested = service.compileAsync('({ sum: promiseFunc(one, two) })');
|
|
156
|
+
await service.simpleCallAsync(nested, context); // { sum: 3 }
|
|
157
|
+
```
|
|
158
|
+
|
|
30
159
|
### Discovery — `DiscoveryService`
|
|
31
160
|
|
|
32
161
|
Finds every node of a given type in an expression.
|
|
@@ -123,8 +252,142 @@ service.simpleEval('({a:1}).a'); // throws SyntaxError - write (
|
|
|
123
252
|
|
|
124
253
|
**Read events and dependencies stay dotted.** A colon-joined name is one segment of a `path`: reading `obj.Q2:3` reports the `key` `Q2:3` and the `path` `obj.Q2:3`, and `createDependencyTracker()` records `obj.Q2:3`. Split a path on `.`, never on `:`.
|
|
125
254
|
|
|
255
|
+
## Supported syntax
|
|
256
|
+
|
|
257
|
+
### ESTree nodes supported
|
|
258
|
+
|
|
259
|
+
The project has been tested with the following node types:
|
|
260
|
+
- `BinaryExpression`
|
|
261
|
+
- `Identifier`
|
|
262
|
+
- `Literal`
|
|
263
|
+
- `CallExpression` *potentially unsafe*
|
|
264
|
+
- `AwaitExpression`
|
|
265
|
+
- `ConditionalExpression`
|
|
266
|
+
- `MemberExpression`
|
|
267
|
+
- `ArrayExpression`
|
|
268
|
+
- `UnaryExpression`
|
|
269
|
+
- `LogicalExpression`
|
|
270
|
+
- `ThisExpression` — only as the object of a member access, `this.k`, `this['k']` or `this.fn()`;
|
|
271
|
+
anywhere else it throws, since `@zvenigora/ng-eval-core` 0.13.0. Up to 0.12.1 it evaluated to the
|
|
272
|
+
evaluation context
|
|
273
|
+
- `NewExpression`
|
|
274
|
+
- `TemplateLiteral`
|
|
275
|
+
- `TaggedTemplateExpression`
|
|
276
|
+
- `ObjectExpression`
|
|
277
|
+
- `AssignmentExpression` — to an identifier or a member, parenthesised or not. Destructuring
|
|
278
|
+
assignment, `[a, b] = arr` or `({ m } = o)`, throws `Unsupported assignment target`;
|
|
279
|
+
before `@zvenigora/ng-eval-core` 0.7.0 it silently did nothing
|
|
280
|
+
- `UpdateExpression` — to an identifier or a member, parenthesised or not
|
|
281
|
+
- `ArrowFunctionExpression` *potentially unsafe* (AssignmentPattern is not implemented, so a
|
|
282
|
+
destructuring default — `({ a = 1 }) => a` — is rejected rather than defaulted)
|
|
283
|
+
- `SequenceExpression` — each expression in order, the value the last one's
|
|
284
|
+
|
|
285
|
+
Object and array destructuring bind the names JavaScript binds, in parameter lists and in
|
|
286
|
+
`let` / `const` declarations alike: shorthand, renaming, nesting, literal and computed keys,
|
|
287
|
+
and rest elements. **Before `@zvenigora/ng-eval-core` 0.5.0 the renaming forms bound the wrong
|
|
288
|
+
names** — see the 0.5.0 entry in the
|
|
289
|
+
[CHANGELOG](https://github.com/zvenigora/ng-eval/blob/master/modules/eval-core/CHANGELOG.md#050---2026-09-17).
|
|
290
|
+
|
|
291
|
+
Statements, since `@zvenigora/ng-eval-core` 0.4.0:
|
|
292
|
+
|
|
293
|
+
- `Program`
|
|
294
|
+
- `ExpressionStatement`
|
|
295
|
+
- `EmptyStatement`
|
|
296
|
+
- `BlockStatement`
|
|
297
|
+
- `VariableDeclaration` — `let` and `const` only; `var` is rejected
|
|
298
|
+
- `IfStatement`
|
|
299
|
+
- `ForStatement` — the classic three-part form only
|
|
300
|
+
|
|
301
|
+
**Every other statement type is rejected with `Unsupported statement type: <type>`.**
|
|
302
|
+
That is a change of kind, not only of coverage: before 0.4.0 an unsupported statement was
|
|
303
|
+
handed to `acorn-walk`'s base walker, which walked the subtree as an expression and left
|
|
304
|
+
whatever it pushed on the value stack — so `throw 1` evaluated to `1` and threw nothing, and
|
|
305
|
+
`switch (1) { case 1: 2 }` evaluated to `2`. See the
|
|
306
|
+
[CHANGELOG](https://github.com/zvenigora/ng-eval/blob/master/modules/eval-core/CHANGELOG.md#040---2026-09-15) for the full before/after table.
|
|
307
|
+
|
|
308
|
+
`WhileStatement`, `DoWhileStatement`, `ForInStatement`, `ForOfStatement`, `SwitchStatement`,
|
|
309
|
+
`TryStatement`, `ThrowStatement`, `LabeledStatement`, `BreakStatement`, `ContinueStatement`,
|
|
310
|
+
`FunctionDeclaration` and `ClassDeclaration` are among the rejected types. The three that
|
|
311
|
+
imply **abrupt completion** and are reachable — `break`, `continue`, `throw` — are out by
|
|
312
|
+
design rather than by schedule: the evaluator has no completion record to carry them, and
|
|
313
|
+
adding one is a redesign of the walker rather than another visitor. `return` never reaches
|
|
314
|
+
the evaluator at all: an expression is parsed outside any function, so `return 1` is a parse
|
|
315
|
+
error (`'return' outside of function`) both before and after 0.4.0.
|
|
316
|
+
|
|
317
|
+
### How statements differ from JavaScript
|
|
318
|
+
|
|
319
|
+
Seven deliberate divergences, each a documented rule rather than an accident:
|
|
320
|
+
|
|
321
|
+
1. **An arrow function with a block body returns the block's completion value**, where
|
|
322
|
+
JavaScript returns `undefined` without a `return`. `x => { 1 }` yields `1` here. With
|
|
323
|
+
`return` unsupported, the completion value is the only answer available that is not an
|
|
324
|
+
error.
|
|
325
|
+
2. **`const` reassignment throws at the write, not at parse time.**
|
|
326
|
+
3. **An unsupported statement type throws**, where before 0.4.0 it returned a value.
|
|
327
|
+
4. **No hoisting.** A `let` binds when its declaration is reached; reading it earlier reads
|
|
328
|
+
the enclosing context rather than raising a temporal-dead-zone error.
|
|
329
|
+
5. **Closures do not capture their lexical scope.** An arrow resolves its free variables
|
|
330
|
+
against the context *as it is when it is called*, not as it was where it was written — so
|
|
331
|
+
`for (let i = 0; i < 3; i++) { fns.push(() => i) }` leaves three functions that all read
|
|
332
|
+
whatever `i` resolves to at call time. This is pre-existing behaviour that statements
|
|
333
|
+
neither cause nor worsen.
|
|
334
|
+
6. **A pattern form the binder does not implement throws** rather than binding nothing.
|
|
335
|
+
7. **A binding name on the prototype-pollution blocklist is rejected — including as an arrow
|
|
336
|
+
function parameter.** `(toString => toString)(1)` returned `1` before 0.4.0 and now
|
|
337
|
+
throws; so do `constructor`, `prototype`, `valueOf`, `hasOwnProperty`, `isPrototypeOf`,
|
|
338
|
+
`propertyIsEnumerable`, `toLocaleString` and the four `__define`/`__lookup` accessors.
|
|
339
|
+
Binding writes share the blocklist with every other write site, which is wider than the
|
|
340
|
+
threat — only `__proto__` is an actual write vector — and is kept wide so that "is this
|
|
341
|
+
name blocked?" does not depend on which visitor reached it. From 0.4.0 to 0.6.x a throw
|
|
342
|
+
from inside a called arrow function was re-wrapped, so this one arrived as
|
|
343
|
+
`Function call error: Access to dangerous property "toString" is blocked…`; since 0.7.0
|
|
344
|
+
it arrives as thrown, without the prefix.
|
|
345
|
+
|
|
126
346
|
## Options
|
|
127
347
|
|
|
348
|
+
To change the evaluator's default behaviour, pass `options`: the last argument of `simpleEval`, `simpleCall` and `createState`.
|
|
349
|
+
|
|
350
|
+
### Case-insensitive evaluation
|
|
351
|
+
|
|
352
|
+
While JavaScript is a case-sensitive language, some may find it hard to use. To provide case-insensitive evaluation, set `caseInsensitive` to `true`. It applies to identifiers and to member names alike.
|
|
353
|
+
|
|
354
|
+
```javascript
|
|
355
|
+
import { EvalService } from '@zvenigora/ng-eval-core';
|
|
356
|
+
|
|
357
|
+
const service = inject(EvalService);
|
|
358
|
+
|
|
359
|
+
const options = { caseInsensitive: true };
|
|
360
|
+
|
|
361
|
+
const expression = '2 + 3 * A';
|
|
362
|
+
const context = { a: 10 };
|
|
363
|
+
const result = service.simpleEval(expression, context, options); // 32
|
|
364
|
+
|
|
365
|
+
service.simpleEval('User.NAME', { user: { name: 'Ann' } }, options); // 'Ann'
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
### Evaluation with state
|
|
369
|
+
|
|
370
|
+
`eval(expression, state)` evaluates against a state rather than a context. The state holds the context, the result and the options; the visitors read it as they walk, so it can extend the evaluator — for example with the execution history, or the time each node type took. `simpleEval` builds a state internally and never hands it back, so reading back what the walk recorded — `nodeTimings`, the trace, collected hook errors — needs this style.
|
|
371
|
+
|
|
372
|
+
```javascript
|
|
373
|
+
import { EvalService } from '@zvenigora/ng-eval-core';
|
|
374
|
+
|
|
375
|
+
const service = inject(EvalService);
|
|
376
|
+
|
|
377
|
+
const expression = '2 + 3 * A';
|
|
378
|
+
const context = { a: 10 };
|
|
379
|
+
const options = { caseInsensitive: true };
|
|
380
|
+
const state = service.createState(context, options);
|
|
381
|
+
// update the state if required - register hooks on state.hooks, for example
|
|
382
|
+
|
|
383
|
+
const result = service.eval(expression, state); // 32
|
|
384
|
+
|
|
385
|
+
// read the state: the execution history, one entry per value the walk pushed
|
|
386
|
+
state.result.trace.map((item) => `${item.expression} = ${item.value}`);
|
|
387
|
+
// ['2 = 2', '3 = 3', 'A = 10', '3 * A = 30', '2 + 3 * A = 32', '2 + 3 * A = 32', '2 + 3 * A = 32']
|
|
388
|
+
state.result.traceTruncated; // false - did it stop short? see `maxTraceItems`
|
|
389
|
+
```
|
|
390
|
+
|
|
128
391
|
### Per-node timing
|
|
129
392
|
|
|
130
393
|
Set `trackTime` to `true` to accumulate per-node-type timings for an evaluation. They are read back from the state as `nodeTimings`, so this option needs the state-first style — `simpleEval` builds its state internally and never hands it back.
|