@zvenigora/ng-eval-core 0.2.2 → 0.3.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,164 @@ 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.
|
|
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
|
+
## Options
|
|
14
|
+
|
|
15
|
+
### Per-node timing
|
|
16
|
+
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
```javascript
|
|
20
|
+
import { EvalService } from '@zvenigora/ng-eval-core';
|
|
21
|
+
|
|
22
|
+
private service: EvalService;
|
|
23
|
+
...
|
|
24
|
+
const context = { a: 2, b: 3, c: 4 };
|
|
25
|
+
const state = service.createState(context, { trackTime: true });
|
|
26
|
+
|
|
27
|
+
const result = service.eval('a + b * c', state); // 14
|
|
28
|
+
|
|
29
|
+
state.nodeTimings.get('BinaryExpression'); // { count: 2, total: 0.081 }
|
|
30
|
+
state.nodeTimings.get('Identifier'); // { count: 3, total: 0.014 }
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
**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.
|
|
36
|
+
|
|
37
|
+
`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
|
+
|
|
39
|
+
```javascript
|
|
40
|
+
import { createTimingHook } from '@zvenigora/ng-eval-core';
|
|
41
|
+
|
|
42
|
+
const off = createTimingHook().install(state.hooks);
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Evaluation hooks
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
```javascript
|
|
50
|
+
import { EvalService } from '@zvenigora/ng-eval-core';
|
|
51
|
+
|
|
52
|
+
const state = service.createState({ a: 2, b: 3 });
|
|
53
|
+
|
|
54
|
+
const off = state.hooks.on('after', 'BinaryExpression', (event) => {
|
|
55
|
+
event.node.type; // 'BinaryExpression'
|
|
56
|
+
event.value; // the value the visitor pushed
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
service.eval('a + b', state); // 5
|
|
60
|
+
off(); // every `on` returns its unsubscribe
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`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:
|
|
64
|
+
|
|
65
|
+
```javascript
|
|
66
|
+
state.hooks.onRead((event) => {
|
|
67
|
+
event.kind; // 'identifier' | 'member'
|
|
68
|
+
event.key; // the resolved key
|
|
69
|
+
event.path; // 'a.b' when statically reconstructible, else undefined
|
|
70
|
+
event.scoped; // true for arrow-function parameters - not dependencies
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
If you want a dependency set rather than raw events, `createDependencyTracker()` builds one and applies the `scoped` filtering for you.
|
|
75
|
+
|
|
76
|
+
#### Hooks are synchronous
|
|
77
|
+
|
|
78
|
+
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.
|
|
79
|
+
|
|
80
|
+
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:
|
|
81
|
+
|
|
82
|
+
```javascript
|
|
83
|
+
import { ASYNC_HOOK_MESSAGE } from '@zvenigora/ng-eval-core';
|
|
84
|
+
|
|
85
|
+
state.hookErrors.some(
|
|
86
|
+
(e) => e.error instanceof Error && e.error.message === ASYNC_HOOK_MESSAGE
|
|
87
|
+
);
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
#### Hook errors
|
|
91
|
+
|
|
92
|
+
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
|
+
|
|
94
|
+
```javascript
|
|
95
|
+
const state = service.createState(context, { onHookError: 'collect' }); // the default
|
|
96
|
+
service.eval('a + b', state);
|
|
97
|
+
state.hookErrors; // [{ phase, nodeType, error }, ...]
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`onHookError` also accepts `'throw'` (rethrow into the visitor, failing the evaluation) and `'ignore'`.
|
|
101
|
+
|
|
102
|
+
Two things to know about it:
|
|
103
|
+
|
|
104
|
+
- **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`.
|
|
105
|
+
- **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:
|
|
106
|
+
|
|
107
|
+
```javascript
|
|
108
|
+
import { EvalHooks } from '@zvenigora/ng-eval-core';
|
|
109
|
+
|
|
110
|
+
const hooks = new EvalHooks({ onHookError: 'throw' });
|
|
111
|
+
const state = service.createState(context, { hooks });
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
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.
|
|
115
|
+
|
|
116
|
+
#### `completed: false` events
|
|
117
|
+
|
|
118
|
+
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`.
|
|
119
|
+
|
|
120
|
+
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
|
+
|
|
122
|
+
**1. Evaluation actually failed.** The unwinder closes every node still open and supplies the `error`:
|
|
123
|
+
|
|
124
|
+
```javascript
|
|
125
|
+
const boom = () => { throw new Error('kaboom'); };
|
|
126
|
+
const state = service.createState({ boom });
|
|
127
|
+
const seen = [];
|
|
128
|
+
|
|
129
|
+
state.hooks.on('after', '*', (e) => {
|
|
130
|
+
if (!e.completed) seen.push([e.node.type, 'error' in e]);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
try { service.eval('1 + boom()', state); } catch { /* rethrown */ }
|
|
134
|
+
|
|
135
|
+
// seen === [['CallExpression', true], ['BinaryExpression', true]]
|
|
136
|
+
// innermost first, each carrying the error that aborted the walk
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
**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:
|
|
140
|
+
|
|
141
|
+
```javascript
|
|
142
|
+
import { CompilerService, EvalService } from '@zvenigora/ng-eval-core';
|
|
143
|
+
// `service` is an EvalService, `compiler` a CompilerService
|
|
144
|
+
|
|
145
|
+
const state = service.createState({ obj: {} });
|
|
146
|
+
const seen = [];
|
|
147
|
+
|
|
148
|
+
state.hooks.on('after', '*', (e) => {
|
|
149
|
+
if (!e.completed) seen.push([e.node.type, 'error' in e]);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const fn = compiler.compile('async () => await obj.__proto__');
|
|
153
|
+
const arrow = compiler.call(fn, state); // returns the closure; seen === []
|
|
154
|
+
await arrow().catch(() => undefined); // the body runs here
|
|
155
|
+
|
|
156
|
+
// seen === [['MemberExpression', false]] - completed: false, but no error
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
So: test for the `error` property, not for `completed === false`.
|
|
160
|
+
|
|
161
|
+
#### Cost
|
|
162
|
+
|
|
163
|
+
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.
|
|
164
|
+
|
|
165
|
+
Note that `trackTime: true` registers a hook, so it makes the walk dispatch per node exactly as an explicit registration would.
|
|
166
|
+
|
|
167
|
+
Hooks are observers: a hook's return value is discarded and cannot replace or suppress the value a visitor produces.
|
|
168
|
+
|
|
9
169
|
License: MIT
|