@zvenigora/ng-eval-core 0.2.2 → 0.4.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,4 +6,300 @@ 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 names the exported entry points, then documents the options that need more than a snippet.
10
+
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
+
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
+
79
+ ## Options
80
+
81
+ ### Per-node timing
82
+
83
+ 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.
84
+
85
+ ```javascript
86
+ import { EvalService } from '@zvenigora/ng-eval-core';
87
+
88
+ const service = inject(EvalService);
89
+
90
+ const context = { a: 2, b: 3, c: 4 };
91
+ const state = service.createState(context, { trackTime: true });
92
+
93
+ const result = service.eval('a + b * c', state); // 14
94
+
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> }
98
+ ```
99
+
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.
101
+
102
+ **Turning this on makes the walk dispatch a hook on every node.** That is inherent to the feature rather than an oversight: per-node-type totals cannot be produced without visiting each node. If a single walk-level total is all you need, `state.result.duration` already provides one on every evaluation, at no cost, whether or not `trackTime` is set.
103
+
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:
105
+
106
+ ```javascript
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
114
+
115
+ const off = createTimingHook().install(state.hooks);
116
+
117
+ service.eval('a + b * c', state);
118
+ state.nodeTimings.get('BinaryExpression'); // { count: 2, total: <ms> }
119
+ ```
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
+
146
+ ### Evaluation hooks
147
+
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.
149
+
150
+ ```javascript
151
+ import { EvalService } from '@zvenigora/ng-eval-core';
152
+
153
+ const service = inject(EvalService);
154
+ const state = service.createState({ a: 2, b: 3 });
155
+
156
+ const off = state.hooks.on('after', 'BinaryExpression', (event) => {
157
+ event.node.type; // 'BinaryExpression'
158
+ event.value; // the value the visitor pushed
159
+ });
160
+
161
+ service.eval('a + b', state); // 5
162
+ off(); // every `on` returns its unsubscribe
163
+ ```
164
+
165
+ `on(phase, type, hook)` takes `'before'` or `'after'`, and either a concrete node type or `'*'` for every node. `onRead(hook)` registers a read hook instead, fired once per resolved context read with the key as the context actually resolved it — case-corrected when `caseInsensitive` is set, which is not recoverable from the AST node alone:
166
+
167
+ ```javascript
168
+ state.hooks.onRead((event) => {
169
+ event.kind; // 'identifier' | 'member'
170
+ event.key; // the resolved key
171
+ event.path; // 'a.b' when statically reconstructible, else undefined
172
+ event.scoped; // true for arrow-function parameters - not dependencies
173
+ });
174
+ ```
175
+
176
+ If you want a dependency set rather than raw events, `createDependencyTracker()` builds one and applies the `scoped` filtering for you.
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
+
199
+ #### Hooks are synchronous
200
+
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.
202
+
203
+ A hook that returns a promise is therefore **not** awaited, and whatever it meant to do lands after the evaluation has finished. The dispatcher reports this as an error carrying the exported `ASYNC_HOOK_MESSAGE`, routed through the configured policy like any other hook error — collected by default, and thrown under `'throw'`. Matching on the constant tells it apart from an error your own hook threw:
204
+
205
+ ```javascript
206
+ import { ASYNC_HOOK_MESSAGE } from '@zvenigora/ng-eval-core';
207
+
208
+ state.hookErrors.some(
209
+ (e) => e.error instanceof Error && e.error.message === ASYNC_HOOK_MESSAGE
210
+ );
211
+ ```
212
+
213
+ #### Hook errors
214
+
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:
216
+
217
+ ```javascript
218
+ const service = inject(EvalService);
219
+ const context = { a: 2, b: 3 };
220
+
221
+ const state = service.createState(context, { onHookError: 'collect' }); // the default
222
+ state.hooks.on('after', 'Identifier', () => { throw new Error('faulty observer'); });
223
+
224
+ service.eval('a + b', state);
225
+ state.hookErrors; // [{ phase, nodeType, error }, ...]
226
+ ```
227
+
228
+ `onHookError` also accepts `'throw'` (rethrow into the visitor, failing the evaluation) and `'ignore'`.
229
+
230
+ Two things to know about it:
231
+
232
+ - **Reading `hookErrors` requires the state-first style.** `simpleEval` builds its state internally and never hands it back, so there is nowhere to read them from. Use `createState` plus `eval`.
233
+ - **Passing both `hooks` and `onHookError` silently ignores `onHookError`.** A registry you pass through `options.hooks` is yours, and it keeps the policy it was constructed with; options never reconfigure an adopted registry. Pass the policy where the registry is built instead:
234
+
235
+ ```javascript
236
+ import { EvalHooks } from '@zvenigora/ng-eval-core';
237
+
238
+ const service = inject(EvalService);
239
+ const context = { a: 2, b: 3 };
240
+
241
+ const hooks = new EvalHooks({ onHookError: 'throw' });
242
+ const state = service.createState(context, { hooks });
243
+ ```
244
+
245
+ One thing the library *does* do to a registry you own: `EvalService.ngOnDestroy()` clears the registries of the states it created, adopted ones included, so that a registry outliving the service cannot keep those states and their AST nodes reachable. Do not share one registry with a state whose lifetime is meant to outlast the service.
246
+
247
+ #### `completed: false` events
248
+
249
+ An `'after'` event normally means a visitor finished and pushed a value. When it carries `completed: false` it was *synthesised* — the visitor never closed the node itself — and there is no `value`.
250
+
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.
252
+
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:
254
+
255
+ ```javascript
256
+ const service = inject(EvalService);
257
+
258
+ const boom = () => { throw new Error('kaboom'); };
259
+ const state = service.createState({ boom });
260
+ const seen = [];
261
+
262
+ state.hooks.on('after', '*', (e) => {
263
+ if (!e.completed) seen.push([e.node.type, 'error' in e]);
264
+ });
265
+
266
+ try { service.eval('1 + boom()', state); } catch { /* rethrown */ }
267
+
268
+ // seen === [['CallExpression', true], ['BinaryExpression', true],
269
+ // ['ExpressionStatement', true], ['Program', true]]
270
+ // innermost first, each carrying the error that aborted the walk
271
+ ```
272
+
273
+ **2. An enclosing visitor moved on without its child.** The node is flushed when the enclosing one closes, and there is **no** `error` — nothing was reported as thrown, and the evaluation may still produce a value:
274
+
275
+ ```javascript
276
+ import { CompilerService, EvalService } from '@zvenigora/ng-eval-core';
277
+
278
+ const service = inject(EvalService);
279
+ const compiler = inject(CompilerService);
280
+
281
+ const state = service.createState({ obj: {} });
282
+ const seen = [];
283
+
284
+ state.hooks.on('after', '*', (e) => {
285
+ if (!e.completed) seen.push([e.node.type, 'error' in e]);
286
+ });
287
+
288
+ const fn = compiler.compile('async () => await obj.__proto__');
289
+ const arrow = compiler.call(fn, state); // returns the closure; seen === []
290
+ await arrow().catch(() => undefined); // the body runs here
291
+
292
+ // seen === [['MemberExpression', false]] - completed: false, but no error
293
+ ```
294
+
295
+ So: test for the `error` property, not for `completed === false`.
296
+
297
+ #### Cost
298
+
299
+ The no-hooks path is a single boolean check per node, so an evaluation with nothing registered pays essentially nothing. Registering any hook turns per-node dispatch on for the whole walk; registering a *read* hook additionally turns on key resolution and path reconstruction at each read site, which node hooks alone do not pay for.
300
+
301
+ Note that `trackTime: true` registers a hook, so it makes the walk dispatch per node exactly as an explicit registration would.
302
+
303
+ Hooks are observers: a hook's return value is discarded and cannot replace or suppress the value a visitor produces.
304
+
9
305
  License: MIT