@zvenigora/ng-eval-core 0.13.0 → 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.
Files changed (3) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +270 -7
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -14,6 +14,22 @@ 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
+
17
33
  ## [0.13.0] - 2026-10-20
18
34
 
19
35
  **The route through `this` is closed, in both halves — the value and the receiver — and the
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
- The sources for this package are in the main [@zvenigora/ng-eval](https://github.com/zvenigora/ng-eval) repo.
5
+ ## Install
6
6
 
7
- This library was generated with [Nx](https://nx.dev).
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
- Full documentation — parsing, evaluation, compilation, async evaluation, discovery, and the `caseInsensitive` / state / scope options — is in the [repository README](https://github.com/zvenigora/ng-eval#readme). This file names the exported entry points, then documents the options that need more than a snippet.
20
+ ## Security
10
21
 
11
- **Security.** [`SECURITY.md`](https://github.com/zvenigora/ng-eval/blob/master/SECURITY.md) covers the threat model, the prototype-pollution and call-sandboxing protections, and their documented limits. It 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. Note that ng-eval does not attempt to be a complete sandbox — see the threat model before evaluating untrusted expressions.
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
- The [repository README](https://github.com/zvenigora/ng-eval#readme) walks through each of these in full. They are named here because they are what installing this package gives you: a symbol documented only in the repository README is one the consumer who installed the package cannot read about.
26
+ Each service below is documented in its own section. `EvalService` (evaluation) and `CompilerService` (compile once, call repeatedly) are used throughout.
16
27
 
17
- `EvalService` (evaluation) and `CompilerService` (compile once, call repeatedly) are used throughout the sections below.
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvenigora/ng-eval-core",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "An expression evaluator for Angular",
5
5
  "repository": {
6
6
  "type": "git",