@zvenigora/ng-eval-core 0.3.0 → 0.5.0

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/README.md CHANGED
@@ -6,10 +6,76 @@ The sources for this package are in the main [@zvenigora/ng-eval](https://github
6
6
 
7
7
  This library was generated with [Nx](https://nx.dev).
8
8
 
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 documents the options that need more than a snippet.
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.
10
10
 
11
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.
12
12
 
13
+ ## Exported entry points
14
+
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.
16
+
17
+ `EvalService` (evaluation) and `CompilerService` (compile once, call repeatedly) are used throughout the sections below.
18
+
19
+ ### Parsing — `ParserService`
20
+
21
+ ```javascript
22
+ import { ParserService } from '@zvenigora/ng-eval-core';
23
+
24
+ const service = inject(ParserService); // Angular's inject(), or constructor injection
25
+
26
+ const ast = service.parse('1 + foo'); // an ESTree AST
27
+ ast.type; // 'BinaryExpression'
28
+ ```
29
+
30
+ ### Discovery — `DiscoveryService`
31
+
32
+ Finds every node of a given type in an expression.
33
+
34
+ ```javascript
35
+ import { DiscoveryService } from '@zvenigora/ng-eval-core';
36
+
37
+ const service = inject(DiscoveryService);
38
+
39
+ const expressions = service.extract('1 + 2 * a', 'BinaryExpression');
40
+ expressions.length; // 2
41
+ ```
42
+
43
+ ### Scopes — `EvalContext`, `EvalScope`, `EvalScopeOptions`
44
+
45
+ An evaluation context may carry prior scopes, each with its own `namespace`, `thisArg` and case sensitivity. Bare identifiers are read from the context itself; a namespaced scope is reached through its namespace.
46
+
47
+ ```javascript
48
+ import { EvalContext, EvalScope, EvalScopeOptions,
49
+ EvalService } from '@zvenigora/ng-eval-core';
50
+
51
+ const service = inject(EvalService);
52
+
53
+ const cat = {
54
+ name: 'Miss Kitty',
55
+ num: 3,
56
+ action: function(args: string[], n: number, t: string) {
57
+ return this.name + ' ' + args.join(' ') + ' ' + n + ' ' + t;
58
+ }
59
+ };
60
+
61
+ // `args` is read as a bare identifier, so it belongs to the context itself
62
+ // rather than to the scope.
63
+ const evalContext = new EvalContext({ args: ['says', 'meow'] }, {});
64
+
65
+ const catOptions: EvalScopeOptions = {
66
+ global: false,
67
+ caseInsensitive: false,
68
+ namespace: 'cat',
69
+ thisArg: cat
70
+ };
71
+ evalContext.priorScopes.push(EvalScope.fromObject(cat, catOptions));
72
+
73
+ const result = service.simpleEval('cat.action(args, cat.num, "times")', evalContext);
74
+ // 'Miss Kitty says meow 3 times'
75
+ ```
76
+
77
+ Note that an `EvalContext` may back any number of evaluations, and that `caseInsensitive` set on the context alone does not reach the walk — pass it in the evaluation options too.
78
+
13
79
  ## Options
14
80
 
15
81
  ### Per-node timing
@@ -19,15 +85,16 @@ Set `trackTime` to `true` to accumulate per-node-type timings for an evaluation.
19
85
  ```javascript
20
86
  import { EvalService } from '@zvenigora/ng-eval-core';
21
87
 
22
- private service: EvalService;
23
- ...
88
+ const service = inject(EvalService);
89
+
24
90
  const context = { a: 2, b: 3, c: 4 };
25
91
  const state = service.createState(context, { trackTime: true });
26
92
 
27
93
  const result = service.eval('a + b * c', state); // 14
28
94
 
29
- state.nodeTimings.get('BinaryExpression'); // { count: 2, total: 0.081 }
30
- state.nodeTimings.get('Identifier'); // { count: 3, total: 0.014 }
95
+ // `count` is exact; `total` is wall-clock in milliseconds.
96
+ state.nodeTimings.get('BinaryExpression'); // { count: 2, total: <ms> }
97
+ state.nodeTimings.get('Identifier'); // { count: 3, total: <ms> }
31
98
  ```
32
99
 
33
100
  Totals are in milliseconds and **inclusive** of child nodes, so nested node types overlap and summing them exceeds the walk's duration — the figures are for comparing node types against each other, not for a breakdown that adds up. They accumulate for the life of the state rather than per `eval` call, so under the `createState` + repeated `eval` style the counts are running totals; use a fresh state for per-run figures.
@@ -37,11 +104,45 @@ Totals are in milliseconds and **inclusive** of child nodes, so nested node type
37
104
  `trackTime` configures the hook registry the state creates for itself. If you pass your own registry through `options.hooks`, that registry is yours and options never configure it — install the hook explicitly instead:
38
105
 
39
106
  ```javascript
40
- import { createTimingHook } from '@zvenigora/ng-eval-core';
107
+ import { EvalHooks, createTimingHook } from '@zvenigora/ng-eval-core';
108
+
109
+ const hooks = new EvalHooks(); // yours, so `trackTime` never configures it
110
+ const state = service.createState(context, { hooks, trackTime: true });
111
+
112
+ service.eval('a + b * c', state);
113
+ state.nodeTimings.size; // 0 — the option did not reach your registry
41
114
 
42
115
  const off = createTimingHook().install(state.hooks);
116
+
117
+ service.eval('a + b * c', state);
118
+ state.nodeTimings.get('BinaryExpression'); // { count: 2, total: <ms> }
43
119
  ```
44
120
 
121
+ ### Iteration budget
122
+
123
+ `for` loops are bounded so that a runaway expression fails fast rather than hanging the caller. The budget is **100,000 iterations per evaluation**, shared by every loop in the expression — a per-loop cap would multiply under nesting and so would not be a bound at all. Exceeding it throws; a runaway loop that silently returns a partial value is the failure mode this exists to prevent.
124
+
125
+ ```javascript
126
+ import { EvalService } from '@zvenigora/ng-eval-core';
127
+
128
+ const service = inject(EvalService);
129
+
130
+ service.simpleEval('for (let i = 0; i < 3; i++) { i }'); // 2
131
+
132
+ // Raise it, lower it, or set Infinity and own the consequence.
133
+ const state = service.createState({}, { maxIterations: 10 });
134
+
135
+ try {
136
+ service.eval('for (let i = 0; i < 100; i++) { i }', state);
137
+ } catch (e) {
138
+ e.message; // 'Iteration budget exhausted after 10 iterations'
139
+ }
140
+ ```
141
+
142
+ The budget is refilled per outermost `eval` call, not per state — so the `createState` + repeated `eval` style does not erode one budget across independent evaluations, and an arrow function that outlives the walk that created it does not carry that walk's spent budget into a later call.
143
+
144
+ **It bounds time, not memory.** `state.result.trace` gains an entry per pushed value and is never reset, so a long-running loop's trace grows as iterations × nodes and that allocation is paid before the throw. With `maxIterations: Infinity` there is no bound at all; prefer a large finite number.
145
+
45
146
  ### Evaluation hooks
46
147
 
47
148
  Hooks let you observe an evaluation as it happens: a callback per AST node, or per resolved context read. They are registered on the state's `hooks` registry, so they apply to that **state** — every evaluation you run through it, which under the `createState` + repeated `eval` style is more than one. `EvalService` is a root singleton, but hooks are never held on the service, so one consumer's hooks never reach another's.
@@ -49,6 +150,7 @@ Hooks let you observe an evaluation as it happens: a callback per AST node, or p
49
150
  ```javascript
50
151
  import { EvalService } from '@zvenigora/ng-eval-core';
51
152
 
153
+ const service = inject(EvalService);
52
154
  const state = service.createState({ a: 2, b: 3 });
53
155
 
54
156
  const off = state.hooks.on('after', 'BinaryExpression', (event) => {
@@ -73,6 +175,27 @@ state.hooks.onRead((event) => {
73
175
 
74
176
  If you want a dependency set rather than raw events, `createDependencyTracker()` builds one and applies the `scoped` filtering for you.
75
177
 
178
+ #### Statements and the empty-completion sentinel
179
+
180
+ Since 0.4.0 an expression may be a statement list, and a statement that produces no value — a declaration, an `if` that takes no branch, a `for` that runs zero iterations — pushes a sentinel rather than `undefined`. JavaScript's completion-value semantics keep the last *non-empty* value, and empty is not the same as `undefined`: in `a; noop()`, where `noop` returns `undefined`, the result is `undefined` and not `'A'`, because the call genuinely produced a value.
181
+
182
+ `EMPTY_COMPLETION` never leaves an evaluation's return value — it is converted to `undefined` at the walk boundary — but an `after` hook fires before that conversion, so a hook on a statement node **will** see it. It is exported so you can recognise it by identity rather than by guessing:
183
+
184
+ ```javascript
185
+ import { EMPTY_COMPLETION, EvalService } from '@zvenigora/ng-eval-core';
186
+
187
+ const service = inject(EvalService);
188
+ const state = service.createState({ a: 1 });
189
+
190
+ const produced = [];
191
+ state.hooks.on('after', 'VariableDeclaration', (event) => {
192
+ produced.push(event.value !== EMPTY_COMPLETION);
193
+ });
194
+
195
+ service.eval('let x = 1; x + a', state); // 2
196
+ produced; // [false] - the declaration produced nothing
197
+ ```
198
+
76
199
  #### Hooks are synchronous
77
200
 
78
201
  The walk is synchronous even under `evalAsync` — `evaluateAsync` runs the same synchronous traversal and only awaits the result at the end. There is no point at which a hook could be awaited.
@@ -92,7 +215,12 @@ state.hookErrors.some(
92
215
  By default an error thrown by a hook is collected rather than propagated, so a faulty observer cannot break the evaluation it is observing. Collected errors are read back from the state:
93
216
 
94
217
  ```javascript
218
+ const service = inject(EvalService);
219
+ const context = { a: 2, b: 3 };
220
+
95
221
  const state = service.createState(context, { onHookError: 'collect' }); // the default
222
+ state.hooks.on('after', 'Identifier', () => { throw new Error('faulty observer'); });
223
+
96
224
  service.eval('a + b', state);
97
225
  state.hookErrors; // [{ phase, nodeType, error }, ...]
98
226
  ```
@@ -107,6 +235,9 @@ Two things to know about it:
107
235
  ```javascript
108
236
  import { EvalHooks } from '@zvenigora/ng-eval-core';
109
237
 
238
+ const service = inject(EvalService);
239
+ const context = { a: 2, b: 3 };
240
+
110
241
  const hooks = new EvalHooks({ onHookError: 'throw' });
111
242
  const state = service.createState(context, { hooks });
112
243
  ```
@@ -119,9 +250,11 @@ An `'after'` event normally means a visitor finished and pushed a value. When it
119
250
 
120
251
  These come from two different places, and **the presence of `error` is what tells them apart**. A consumer that reads `completed: false` as "this evaluation failed" will be wrong on the second kind.
121
252
 
122
- **1. Evaluation actually failed.** The unwinder closes every node still open and supplies the `error`:
253
+ **1. Evaluation actually failed.** The unwinder closes every node still open and supplies the `error` — including the statement nodes enclosing the expression, since a program and its statements are walked like anything else:
123
254
 
124
255
  ```javascript
256
+ const service = inject(EvalService);
257
+
125
258
  const boom = () => { throw new Error('kaboom'); };
126
259
  const state = service.createState({ boom });
127
260
  const seen = [];
@@ -132,7 +265,8 @@ state.hooks.on('after', '*', (e) => {
132
265
 
133
266
  try { service.eval('1 + boom()', state); } catch { /* rethrown */ }
134
267
 
135
- // seen === [['CallExpression', true], ['BinaryExpression', true]]
268
+ // seen === [['CallExpression', true], ['BinaryExpression', true],
269
+ // ['ExpressionStatement', true], ['Program', true]]
136
270
  // innermost first, each carrying the error that aborted the walk
137
271
  ```
138
272
 
@@ -140,7 +274,9 @@ try { service.eval('1 + boom()', state); } catch { /* rethrown */ }
140
274
 
141
275
  ```javascript
142
276
  import { CompilerService, EvalService } from '@zvenigora/ng-eval-core';
143
- // `service` is an EvalService, `compiler` a CompilerService
277
+
278
+ const service = inject(EvalService);
279
+ const compiler = inject(CompilerService);
144
280
 
145
281
  const state = service.createState({ obj: {} });
146
282
  const seen = [];