@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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable } from '@angular/core';
2
+ import { Injectable, inject } from '@angular/core';
3
3
  import { sha256 } from 'js-sha256';
4
4
  import { defaultOptions, parse as parse$1, version } from 'acorn';
5
5
  import * as walk from 'acorn-walk';
@@ -826,6 +826,22 @@ const getContextKey = (context, key, caseInsensitive) => {
826
826
  return undefined;
827
827
  };
828
828
 
829
+ /**
830
+ * Whether a context holds a key at all, regardless of the value bound to it.
831
+ *
832
+ * There is no `getContextValue` counterpart for this: that helper cannot
833
+ * distinguish an absent key from one bound to `undefined`, and `getContextKey`
834
+ * with `caseInsensitive: false` reports every key as present for a plain
835
+ * object. Own properties only - the scopes this is used on are object literals
836
+ * built by `evaluatePatterns`, and inherited names are not bindings.
837
+ */
838
+ const hasContextKey = (context, key) => {
839
+ if (context instanceof Registry) {
840
+ return context.has(key);
841
+ }
842
+ return context instanceof Object
843
+ && Object.prototype.hasOwnProperty.call(context, key);
844
+ };
829
845
  /**
830
846
  * Represents the evaluation context for the code execution.
831
847
  */
@@ -892,11 +908,9 @@ class EvalContext {
892
908
  * @returns The value associated with the key, or undefined if not found.
893
909
  */
894
910
  get(key) {
895
- for (const scope of this._scopes.asArray()) {
896
- const value = getContextValue(scope, key);
897
- if (value !== undefined) {
898
- return value;
899
- }
911
+ const scoped = this.getFromScopes(key);
912
+ if (scoped !== undefined) {
913
+ return scoped;
900
914
  }
901
915
  if (this._original) {
902
916
  const value = getContextValue(this._original, key);
@@ -918,6 +932,59 @@ class EvalContext {
918
932
  }
919
933
  return undefined;
920
934
  }
935
+ /**
936
+ * Step 1 of {@link get}'s resolution order on its own: the scopes pushed
937
+ * during this evaluation, innermost first.
938
+ *
939
+ * {@link get} calls this rather than inlining the loop, so that the read
940
+ * hooks' `scoped` flag and the resolution it describes are the *same*
941
+ * implementation. A second copy of the order would drift - `getKey` already
942
+ * shows what that looks like when it does.
943
+ *
944
+ * A binding whose value is `undefined` reads as absent here, exactly as it
945
+ * does in {@link get}, which falls through to the original context for it.
946
+ *
947
+ * @param key - The key to retrieve the value for.
948
+ * @returns The value bound by the innermost scope holding the key, or
949
+ * undefined when no pushed scope holds it.
950
+ */
951
+ getFromScopes(key) {
952
+ for (const scope of this._scopes.asArray()) {
953
+ const value = getContextValue(scope, key);
954
+ if (value !== undefined) {
955
+ return value;
956
+ }
957
+ }
958
+ return undefined;
959
+ }
960
+ /**
961
+ * Whether any scope pushed during this evaluation *binds* the key - the
962
+ * question the read hooks' `scoped` flag asks.
963
+ *
964
+ * Deliberately about binding rather than about value, which is where it parts
965
+ * company with {@link getFromScopes}: a parameter bound to `undefined` is
966
+ * still a parameter, but `get` falls through past it to the original context.
967
+ * Reading the flag off the value would make it depend on the *data* - the
968
+ * same arrow function over `[{ name: 'a' }]` and over `[undefined]` would
969
+ * report different bindings, and a dependency tracker's output would vary
970
+ * between two recomputes of one expression. That is the failure this flag
971
+ * exists to prevent, so presence is the correct predicate.
972
+ *
973
+ * Both queries iterate the same stack in the same direction, so neither is a
974
+ * second copy of the four-step resolution order; they answer two different
975
+ * questions about its first step.
976
+ *
977
+ * @param key - The key to look for.
978
+ * @returns True when a pushed scope holds the key, whatever its value.
979
+ */
980
+ hasInScopes(key) {
981
+ for (const scope of this._scopes.asArray()) {
982
+ if (hasContextKey(scope, key)) {
983
+ return true;
984
+ }
985
+ }
986
+ return false;
987
+ }
921
988
  /**
922
989
  * Retrieves the `this` value of the specified key from the evaluation context.
923
990
  * The value is searched in the original context, prior scopes, and lookup functions.
@@ -1186,6 +1253,524 @@ class EvalResult {
1186
1253
  }
1187
1254
  }
1188
1255
 
1256
+ const DEFAULT_POLICY = 'collect';
1257
+ const POLICIES = ['collect', 'throw', 'ignore'];
1258
+ /**
1259
+ * The message carried by the error raised when a hook returns a promise.
1260
+ *
1261
+ * Hooks are synchronous by contract (§ 3.3): the walk is synchronous even under
1262
+ * `evaluateAsync`, so a returned promise is never awaited and whatever the hook
1263
+ * meant to do lands after the evaluation finished. The dispatcher reports it as
1264
+ * an error carrying this message, routed through the configured policy like any
1265
+ * other hook error - collected by default, and thrown into the visitor under
1266
+ * `'throw'`, which does fail the evaluation.
1267
+ *
1268
+ * Exported so a consumer inspecting `EvalState.hookErrors` can tell this
1269
+ * diagnostic apart from an error its own hook threw, without matching on
1270
+ * message text it would have to keep in sync by hand.
1271
+ */
1272
+ const ASYNC_HOOK_MESSAGE = 'async hook returned a promise; it will not be awaited';
1273
+ /**
1274
+ * Reads the error policy out of the evaluation options. `EvalOptions` is a union
1275
+ * and does not index directly, so the read goes through a cast - the same one
1276
+ * `before-visitor.ts` performs.
1277
+ */
1278
+ const readPolicy = (options) => {
1279
+ const value = options?.['onHookError'];
1280
+ return POLICIES.includes(value)
1281
+ ? value
1282
+ : DEFAULT_POLICY;
1283
+ };
1284
+ const isPromiseLike = (value) => !!value &&
1285
+ (typeof value === 'object' || typeof value === 'function') &&
1286
+ typeof value.then === 'function';
1287
+ /**
1288
+ * A registry of node hooks, keyed by node type with wildcard support, and the
1289
+ * dispatcher that keeps `before` and `after` balanced when a visitor throws.
1290
+ *
1291
+ * It holds *registration* only. Everything whose lifetime is a single
1292
+ * evaluation - the open-node stack and the collected errors - lives on the
1293
+ * `EvalState` instead, because a consumer may hand one `EvalHooks` to several
1294
+ * evaluations and expect each to observe both.
1295
+ *
1296
+ * Hooks are synchronous by design: the walk in `evaluate` is synchronous even
1297
+ * under `evaluateAsync`, so there is no point at which a hook could be awaited.
1298
+ */
1299
+ class EvalHooks {
1300
+ /**
1301
+ * @param options The evaluation options; `onHookError` selects the error policy.
1302
+ */
1303
+ constructor(options) {
1304
+ this._before = new Map();
1305
+ this._after = new Map();
1306
+ this._read = [];
1307
+ this._size = 0;
1308
+ this._active = false;
1309
+ this._policy = readPolicy(options);
1310
+ }
1311
+ /**
1312
+ * True while no hook is registered. Read on the hot path, so it is a counter
1313
+ * rather than a walk of the registries.
1314
+ */
1315
+ get isEmpty() {
1316
+ return this._size === 0;
1317
+ }
1318
+ /**
1319
+ * The dispatch guard, behind `EvalState.hasHooks`.
1320
+ *
1321
+ * Unlike {@link isEmpty} this *latches*: it turns true on the first
1322
+ * registration and only `clear` turns it off again. The guard wraps the
1323
+ * open-node stack as well as the hooks themselves, so a value that changed
1324
+ * mid-walk would leave `enter` and `exit` unpaired - which is exactly what
1325
+ * one-shot and self-unsubscribing hooks would otherwise cause.
1326
+ *
1327
+ * Calling `clear` during a walk is therefore unsupported.
1328
+ */
1329
+ get isActive() {
1330
+ return this._active;
1331
+ }
1332
+ /**
1333
+ * True while at least one read hook is registered.
1334
+ *
1335
+ * The second half of the read-emission guard: `st.hasHooks` says a registry
1336
+ * exists and has been used, this says a *read* hook is there to observe the
1337
+ * event. Without it a consumer that registered only 'before'/'after' hooks
1338
+ * would pay `getKey` per identifier and `readPath` plus an object literal per
1339
+ * member for events it can never see - which the timing hook turns from
1340
+ * theoretical into routine, since it latches `hasHooks` for a whole walk.
1341
+ *
1342
+ * **Non-latching, unlike {@link isActive}.** That getter latches because it
1343
+ * wraps the open-node stack, so a value changing mid-walk would leave `enter`
1344
+ * and `exit` unpaired. `dispatchRead` touches no bookkeeping, so a read guard
1345
+ * that flips mid-walk can only drop read events - never unbalance anything.
1346
+ * A one-shot or self-unsubscribing read hook is therefore safe here, and the
1347
+ * guard can report the current registration count rather than history.
1348
+ */
1349
+ get hasReadHooks() {
1350
+ return this._read.length > 0;
1351
+ }
1352
+ /**
1353
+ * Registers a node hook.
1354
+ * @param phase Whether to fire before or after the visitor body.
1355
+ * @param type A concrete node type, or '*' for every node.
1356
+ * @param hook The hook to register.
1357
+ * @returns A function that removes this hook.
1358
+ */
1359
+ on(phase, type, hook) {
1360
+ const registry = this.registry(phase);
1361
+ const hooks = registry.get(type);
1362
+ if (hooks) {
1363
+ hooks.push(hook);
1364
+ }
1365
+ else {
1366
+ registry.set(type, [hook]);
1367
+ }
1368
+ this._size++;
1369
+ this._active = true;
1370
+ let unsubscribed = false;
1371
+ return () => {
1372
+ if (unsubscribed) {
1373
+ return;
1374
+ }
1375
+ unsubscribed = true;
1376
+ this.off(phase, type, hook);
1377
+ };
1378
+ }
1379
+ /**
1380
+ * Registers a read hook, fired once per resolved context read.
1381
+ *
1382
+ * Read hooks are not keyed by node type: there are only two emission points
1383
+ * and a consumer filters on {@link EvalReadEvent.kind} if it cares.
1384
+ *
1385
+ * Registration latches {@link isActive} exactly as {@link on} does, because
1386
+ * the visitors reach their emission points through the same
1387
+ * `EvalState.hasHooks` guard.
1388
+ *
1389
+ * @param hook The hook to register.
1390
+ * @returns A function that removes this hook.
1391
+ */
1392
+ onRead(hook) {
1393
+ this._read.push(hook);
1394
+ this._size++;
1395
+ this._active = true;
1396
+ let unsubscribed = false;
1397
+ return () => {
1398
+ if (unsubscribed) {
1399
+ return;
1400
+ }
1401
+ unsubscribed = true;
1402
+ this.offRead(hook);
1403
+ };
1404
+ }
1405
+ /**
1406
+ * Removes one read hook, or every read hook when `hook` is omitted.
1407
+ */
1408
+ offRead(hook) {
1409
+ if (hook === undefined) {
1410
+ this._size -= this._read.length;
1411
+ this._read = [];
1412
+ return;
1413
+ }
1414
+ const index = this._read.indexOf(hook);
1415
+ if (index < 0) {
1416
+ return;
1417
+ }
1418
+ this._read.splice(index, 1);
1419
+ this._size--;
1420
+ }
1421
+ /**
1422
+ * Removes one hook, or every hook registered for a key when `hook` is omitted.
1423
+ */
1424
+ off(phase, type, hook) {
1425
+ const registry = this.registry(phase);
1426
+ const hooks = registry.get(type);
1427
+ if (!hooks) {
1428
+ return;
1429
+ }
1430
+ if (hook === undefined) {
1431
+ registry.delete(type);
1432
+ this._size -= hooks.length;
1433
+ return;
1434
+ }
1435
+ const index = hooks.indexOf(hook);
1436
+ if (index < 0) {
1437
+ return;
1438
+ }
1439
+ hooks.splice(index, 1);
1440
+ this._size--;
1441
+ if (hooks.length === 0) {
1442
+ registry.delete(type);
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Removes every hook from both phases and unlatches {@link isActive}.
1447
+ *
1448
+ * Per-run bookkeeping is untouched: the open-node stack and the collected
1449
+ * errors belong to the `EvalState`, not to this registry. Errors in
1450
+ * particular are a record of what already happened.
1451
+ */
1452
+ clear() {
1453
+ this._before.clear();
1454
+ this._after.clear();
1455
+ this._read = [];
1456
+ this._size = 0;
1457
+ this._active = false;
1458
+ }
1459
+ /**
1460
+ * Fires the hooks registered for a node, keyed first and wildcard second.
1461
+ *
1462
+ * Bookkeeping runs before user code on both edges: 'before' pushes the node
1463
+ * onto the open-node stack and *then* emits, 'after' pops and *then* emits.
1464
+ * The shared rule is that hook code only ever runs once the stack already
1465
+ * tells the truth about this node, because `emit` can throw - under the
1466
+ * 'throw' policy a hook's error propagates out of it. Emitting first on the
1467
+ * 'before' edge would leave a node that some hooks had already been told
1468
+ * about missing from the stack, and therefore invisible to `unwindTo`.
1469
+ *
1470
+ * @param value The value the visitor pushed; meaningful on 'after' only.
1471
+ */
1472
+ dispatch(phase, node, state, value) {
1473
+ if (phase === 'after') {
1474
+ this.exit(state, node);
1475
+ this.emit({ phase, node, state, value, completed: true }, false);
1476
+ return;
1477
+ }
1478
+ this.enter(node, state);
1479
+ this.emit({ phase, node, state, completed: true }, false);
1480
+ }
1481
+ /**
1482
+ * Fires the read hooks for one resolved context read.
1483
+ *
1484
+ * The event is built by the caller rather than assembled from positional
1485
+ * arguments here, so the visitors allocate nothing on the no-hooks path: the
1486
+ * whole construction sits inside their `st.hasHooks` guard.
1487
+ *
1488
+ * Touches no bookkeeping. A read is not a frame - it happens *within* a
1489
+ * node's before/after pair, so the open-node stack is none of its business.
1490
+ */
1491
+ dispatchRead(event) {
1492
+ if (this._read.length === 0) {
1493
+ return;
1494
+ }
1495
+ // Iterated as a copy so a hook that unsubscribes itself does not shift the
1496
+ // list out from under the loop.
1497
+ for (const hook of this._read.slice()) {
1498
+ this.invokeRead(hook, event);
1499
+ }
1500
+ }
1501
+ /**
1502
+ * Records a node as open on the state. Called by the 'before' dispatcher
1503
+ * before its hooks fire.
1504
+ */
1505
+ enter(node, state) {
1506
+ state.hookBookkeeping.open.push(node);
1507
+ }
1508
+ /**
1509
+ * Closes `node`, matching it by **identity** rather than by position. Called
1510
+ * by the 'after' dispatcher before its hooks fire.
1511
+ *
1512
+ * Three cases:
1513
+ *
1514
+ * 1. `node` is on top - pop it. The ordinary path, one reference comparison.
1515
+ * 2. `node` is open but not on top - some visitor between here and there
1516
+ * never closed itself. Flush those frames innermost-first as
1517
+ * `completed: false`, then pop `node`.
1518
+ * 3. `node` is not open at all - pop nothing and emit nothing.
1519
+ *
1520
+ * Case 3 is what keeps a stray `exit` from draining the stack: the naive
1521
+ * "pop until you find it" would walk to the bottom, synthesise an event for
1522
+ * every genuinely-open enclosing frame, and leave a later real failure with
1523
+ * nothing to unwind.
1524
+ *
1525
+ * Popping positionally instead would be correct only if every visitor
1526
+ * bracketed its body exactly. `await-expression.ts` does not - it catches a
1527
+ * child's synchronous throw and continues to its own `afterVisitor` - so a
1528
+ * positional pop closes the child's frame under the parent's name, drops the
1529
+ * child's `after` entirely, and leaks one frame onto the state for good.
1530
+ *
1531
+ * The synthesised events carry no `value` (the node never pushed one) and no
1532
+ * `error` (nothing threw; the frames are being closed because an enclosing
1533
+ * visitor moved on without them).
1534
+ *
1535
+ * They are emitted under the collect policy even when the consumer chose
1536
+ * 'throw'. That is required, not merely lenient: a rethrow here would escape
1537
+ * the flush loop before it finished popping, re-creating the leak this
1538
+ * identity check exists to prevent. A 'throw'-policy consumer sees these in
1539
+ * `state.hookErrors` instead.
1540
+ */
1541
+ exit(state, node) {
1542
+ const open = state.hookBookkeeping.open;
1543
+ if (open.length > 0 && open[open.length - 1] === node) {
1544
+ open.pop();
1545
+ return;
1546
+ }
1547
+ // The innermost occurrence is the one being closed: a node can legitimately
1548
+ // be open twice, since an arrow-function body is re-walked on every call.
1549
+ const index = open.lastIndexOf(node);
1550
+ if (index < 0) {
1551
+ return;
1552
+ }
1553
+ while (open.length > index + 1) {
1554
+ const stranded = open.pop();
1555
+ if (!stranded) {
1556
+ break;
1557
+ }
1558
+ this.emit({ phase: 'after', node: stranded, state, completed: false }, true);
1559
+ }
1560
+ open.pop();
1561
+ }
1562
+ /**
1563
+ * How many nodes the state has open. Captured as a mark before a walk, since
1564
+ * `evaluate` is re-entered with the same state from an arrow-function body.
1565
+ *
1566
+ * This is a method rather than a getter because the stack it measures lives
1567
+ * on the state, not on this registry.
1568
+ */
1569
+ depth(state) {
1570
+ return state.hookBookkeeping.open.length;
1571
+ }
1572
+ /**
1573
+ * Fires 'after' for every node the state has open above `mark`, innermost
1574
+ * first, marked incomplete. Invoked from the catch in `evaluate`, so that a
1575
+ * visitor which throws still leaves every 'before' matched by exactly one
1576
+ * 'after'.
1577
+ *
1578
+ * Unwinding to a mark rather than to the bottom is what keeps a nested
1579
+ * `evaluate` from draining the enclosing walk's open nodes when a host
1580
+ * function swallows the nested throw.
1581
+ *
1582
+ * Idempotent, so the sync and async entry points can both call it.
1583
+ *
1584
+ * A hook that throws here cannot stop the drain: while unwinding, the 'throw'
1585
+ * policy is downgraded to 'collect' - evaluation has already failed, and the
1586
+ * original error is the one worth propagating.
1587
+ */
1588
+ unwindTo(mark, error, state) {
1589
+ const open = state.hookBookkeeping.open;
1590
+ while (open.length > mark) {
1591
+ const node = open.pop();
1592
+ if (!node) {
1593
+ break;
1594
+ }
1595
+ this.emit({ phase: 'after', node, state, completed: false, error }, true);
1596
+ }
1597
+ }
1598
+ /**
1599
+ * Drains the state's whole open-node stack. Equivalent to `unwindTo(0, ...)`,
1600
+ * for callers that own the entire walk.
1601
+ */
1602
+ unwind(error, state) {
1603
+ this.unwindTo(0, error, state);
1604
+ }
1605
+ registry(phase) {
1606
+ return phase === 'before' ? this._before : this._after;
1607
+ }
1608
+ emit(event, unwinding) {
1609
+ const registry = this.registry(event.phase);
1610
+ if (registry.size === 0) {
1611
+ return;
1612
+ }
1613
+ this.invokeAll(registry.get(event.node.type), event, unwinding);
1614
+ this.invokeAll(registry.get('*'), event, unwinding);
1615
+ }
1616
+ /**
1617
+ * Iterates a copy so that a hook which unsubscribes itself does not shift the
1618
+ * list out from under the loop.
1619
+ */
1620
+ invokeAll(hooks, event, unwinding) {
1621
+ if (!hooks || hooks.length === 0) {
1622
+ return;
1623
+ }
1624
+ for (const hook of hooks.slice()) {
1625
+ this.invoke(hook, event, unwinding);
1626
+ }
1627
+ }
1628
+ invoke(hook, event, unwinding) {
1629
+ let result;
1630
+ try {
1631
+ result = hook(event);
1632
+ }
1633
+ catch (error) {
1634
+ this.handleError(event.state, event.phase, event.node.type, error, unwinding);
1635
+ return;
1636
+ }
1637
+ if (isPromiseLike(result)) {
1638
+ this.handleError(event.state, event.phase, event.node.type, new Error(ASYNC_HOOK_MESSAGE), unwinding);
1639
+ }
1640
+ }
1641
+ /**
1642
+ * The read counterpart of {@link invoke}. There is no unwinding equivalent
1643
+ * for reads - a read never opens a frame - so the policy always applies in
1644
+ * full.
1645
+ */
1646
+ invokeRead(hook, event) {
1647
+ let result;
1648
+ try {
1649
+ result = hook(event);
1650
+ }
1651
+ catch (error) {
1652
+ this.handleError(event.state, 'read', event.node.type, error, false);
1653
+ return;
1654
+ }
1655
+ if (isPromiseLike(result)) {
1656
+ this.handleError(event.state, 'read', event.node.type, new Error(ASYNC_HOOK_MESSAGE), false);
1657
+ }
1658
+ }
1659
+ handleError(state, phase, nodeType, error, unwinding) {
1660
+ if (this._policy === 'ignore') {
1661
+ return;
1662
+ }
1663
+ if (this._policy === 'throw' && !unwinding) {
1664
+ throw error;
1665
+ }
1666
+ state.hookBookkeeping.errors.push({ phase, nodeType, error });
1667
+ }
1668
+ }
1669
+
1670
+ /**
1671
+ * Creates a timing hook that accumulates inclusive per-node-type totals.
1672
+ *
1673
+ * Replaces the `console.time` / `console.timeEnd` pair the old `trackTime`
1674
+ * emitted, which mismatched its labels and produced no readable figure. The
1675
+ * readings are `performance.now()`, and nothing is written to the console.
1676
+ *
1677
+ * ```ts
1678
+ * const state = evalService.createState(context);
1679
+ * const off = createTimingHook().install(state.hooks);
1680
+ * evalService.eval('a + b * c', state);
1681
+ * state.nodeTimings.get('BinaryExpression'); // { count: 2, total: 0.081 }
1682
+ * off();
1683
+ * ```
1684
+ *
1685
+ * Equivalent to passing `{ trackTime: true }`, which installs one of these on
1686
+ * the state's own registry.
1687
+ *
1688
+ * @returns A handle whose `install` registers the pair on a registry.
1689
+ */
1690
+ const createTimingHook = () => {
1691
+ /**
1692
+ * Start times for the nodes this handle currently has open, per state.
1693
+ *
1694
+ * Keyed by state because one handle may be installed on a registry that
1695
+ * several evaluations dispatch through, and a shared stack would interleave
1696
+ * them. Weak, so a finished evaluation's state is collectable while the
1697
+ * consumer holds the handle. Per *handle* rather than module-level, so two
1698
+ * handles installed on one state cannot pop each other's readings.
1699
+ *
1700
+ * A stack works because `EvalHooks` guarantees exactly one 'after' *frame*
1701
+ * per 'before' frame, innermost first, on every exit path - including the
1702
+ * synthesised events `exit` flushes for stranded frames and the ones
1703
+ * `unwindTo` emits when a visitor throws. It has to be a stack rather than a
1704
+ * map keyed by node: an arrow-function body is re-walked on every call, so
1705
+ * the same node can be open more than once.
1706
+ *
1707
+ * The guarantee is about frames, not about hook *invocations*. Under the
1708
+ * 'throw' policy an earlier hook can abort `dispatch`'s emit loop after
1709
+ * `enter` has already run, so this push is skipped while the frame stays
1710
+ * open; the `unwindTo` that follows then pops an enclosing node's reading and
1711
+ * attributes it to the wrong type. Pops never outnumber pushes, so nothing
1712
+ * strands into a later run on the same state - and the evaluation has failed
1713
+ * regardless, which is why the totals are left as they fall.
1714
+ */
1715
+ const starts = new WeakMap();
1716
+ const stackFor = (state) => {
1717
+ const existing = starts.get(state);
1718
+ if (existing) {
1719
+ return existing;
1720
+ }
1721
+ const created = [];
1722
+ starts.set(state, created);
1723
+ return created;
1724
+ };
1725
+ const before = (event) => {
1726
+ stackFor(event.state).push(performance.now());
1727
+ };
1728
+ const after = (event) => {
1729
+ const started = starts.get(event.state)?.pop();
1730
+ if (started === undefined) {
1731
+ // No matching 'before'. Reachable when this handle was installed midway
1732
+ // through a walk, or when a throwing hook skipped the push above;
1733
+ // recording a total from an unknown start would be worse than skipping.
1734
+ return;
1735
+ }
1736
+ record(event.state, event.node.type, performance.now() - started);
1737
+ };
1738
+ return {
1739
+ install(hooks) {
1740
+ const offBefore = hooks.on('before', '*', before);
1741
+ const offAfter = hooks.on('after', '*', after);
1742
+ return () => {
1743
+ offBefore();
1744
+ offAfter();
1745
+ };
1746
+ }
1747
+ };
1748
+ };
1749
+ const record = (state, type, elapsed) => {
1750
+ const timings = state.hookBookkeeping.timings;
1751
+ const current = timings.get(type);
1752
+ timings.set(type, current
1753
+ ? { count: current.count + 1, total: current.total + elapsed }
1754
+ : { count: 1, total: elapsed });
1755
+ };
1756
+
1757
+ /**
1758
+ * Reads a caller-supplied hook registry out of the evaluation options.
1759
+ *
1760
+ * `EvalOptions` is a union and does not index directly, so the read goes
1761
+ * through a cast - the same one `before-visitor.ts` performs. The registry is
1762
+ * adopted as-is and never cloned: the caller holds the unsubscribe closures
1763
+ * `on` returned, and a copy would leave those closures editing a registry that
1764
+ * is no longer the one being dispatched.
1765
+ */
1766
+ const adoptHooks = (options) => {
1767
+ const value = options?.['hooks'];
1768
+ return value instanceof EvalHooks ? value : undefined;
1769
+ };
1770
+ /**
1771
+ * Whether the caller asked for per-node timings. Same cast, same reason.
1772
+ */
1773
+ const readTrackTime = (options) => !!options?.['trackTime'];
1189
1774
  /**
1190
1775
  * Represents the evaluation state, which includes the context, result, and options.
1191
1776
  */
@@ -1214,6 +1799,101 @@ class EvalState {
1214
1799
  get isAsync() {
1215
1800
  return this._isAsync;
1216
1801
  }
1802
+ /**
1803
+ * Gets the hook registry for this evaluation, creating an empty one on first
1804
+ * access. A registry supplied through `options.hooks` is adopted instead.
1805
+ *
1806
+ * Merely reading this does not turn {@link hasHooks} on; registering does.
1807
+ */
1808
+ get hooks() {
1809
+ return (this._hooks ??= new EvalHooks(this._options));
1810
+ }
1811
+ /**
1812
+ * The dispatch guard read by `beforeVisitor` / `afterVisitor`. One field read
1813
+ * and no options lookup, so the no-hooks path stays cheap.
1814
+ */
1815
+ get hasHooks() {
1816
+ return !!this._hooks && this._hooks.isActive;
1817
+ }
1818
+ /**
1819
+ * Errors raised by hooks during this evaluation and collected under the
1820
+ * 'collect' policy.
1821
+ *
1822
+ * They live here rather than on {@link hooks} because an `EvalHooks` may be
1823
+ * shared across evaluations, and an error describes one run.
1824
+ *
1825
+ * The array is the live one, so a reference taken before evaluating fills as
1826
+ * errors arrive. Returning a shared empty array until the first collection
1827
+ * would be cheaper by one allocation and wrong: the reference would silently
1828
+ * stop tracking the moment anything was collected.
1829
+ */
1830
+ get hookErrors() {
1831
+ return this.hookBookkeeping.errors;
1832
+ }
1833
+ /**
1834
+ * Per-node-type timings for **this state**, keyed by node type. Empty unless
1835
+ * a timing hook was installed - by `options.trackTime`, or by the caller
1836
+ * through `createTimingHook().install(state.hooks)`.
1837
+ *
1838
+ * Accumulates for the life of the state, not per `evaluate` call: under the
1839
+ * `createState` + repeated `eval` style the counts are the running totals
1840
+ * across every run on this state, which is what makes them comparable. A
1841
+ * caller who wants per-run figures uses a fresh state, or drops these along
1842
+ * with the rest of the run record via {@link resetHookBookkeeping}.
1843
+ *
1844
+ * Here rather than on the handle `createTimingHook` returns for the same
1845
+ * reason {@link hookErrors} is: timings describe one run, and an `EvalHooks`
1846
+ * may be handed to several. It is also the only place a `trackTime` caller
1847
+ * could reach them, since that installation happens in this constructor and
1848
+ * hands the handle to nobody.
1849
+ *
1850
+ * Totals are inclusive of child nodes; see `EvalNodeTiming`.
1851
+ */
1852
+ get nodeTimings() {
1853
+ return this.hookBookkeeping.timings;
1854
+ }
1855
+ /**
1856
+ * The per-run bookkeeping `EvalHooks` reads and writes: the open-node stack
1857
+ * and the collected errors, grouped behind a single accessor.
1858
+ *
1859
+ * The state owns this storage and `eval-hooks.ts` only type-imports the
1860
+ * state, which keeps the runtime import graph acyclic. Holding it in a
1861
+ * module-private `WeakMap` inside `eval-hooks.ts` was the alternative and was
1862
+ * rejected: `hookErrors` would then need a *runtime* import of that module
1863
+ * while it already imports this one, and the resulting cycle is a hazard in
1864
+ * the ng-packagr build.
1865
+ *
1866
+ * @internal Not part of the published API.
1867
+ */
1868
+ get hookBookkeeping() {
1869
+ return (this._hookBookkeeping ??= { open: [], errors: [], timings: new Map() });
1870
+ }
1871
+ /**
1872
+ * Drops every per-run record this state holds: the collected hook errors, the
1873
+ * open-node stack, and the accumulated timings.
1874
+ *
1875
+ * It resets the whole record rather than only the errors, which is why it is
1876
+ * not named for them. `EvalHooks.clear` cannot reach any of this - the
1877
+ * bookkeeping belongs to the state - so without this method nothing drains
1878
+ * the open-node stack at all. Frames left on it keep their AST nodes
1879
+ * reachable for as long as the state is, and `EvalService` holds its states
1880
+ * in a strong `Set`.
1881
+ *
1882
+ * The errors matter for the same reason under the state-first style:
1883
+ * `createState` plus repeated `eval` on one state accumulates them for the
1884
+ * life of that state, and a thrown value can close over consumer objects.
1885
+ *
1886
+ * The record is replaced rather than emptied in place, so a caller still
1887
+ * holding the array {@link hookErrors} handed out keeps its own contents and
1888
+ * simply stops tracking - the alternative would mutate a collection the
1889
+ * caller owns a reference to.
1890
+ *
1891
+ * Calling this mid-walk is unsupported for the same reason `EvalHooks.clear`
1892
+ * is: it abandons frames the dispatcher expects to close.
1893
+ */
1894
+ resetHookBookkeeping() {
1895
+ this._hookBookkeeping = undefined;
1896
+ }
1217
1897
  /**
1218
1898
  * Represents the state of an evaluation.
1219
1899
  * @param context The evaluation context.
@@ -1226,6 +1906,21 @@ class EvalState {
1226
1906
  this._result = result;
1227
1907
  this._options = options;
1228
1908
  this._isAsync = isAsync;
1909
+ this._hooks = adoptHooks(options);
1910
+ // Options configure the registry this state owns, never an adopted one -
1911
+ // the same rule `onHookError` follows, and for the same reason: an adopted
1912
+ // `EvalHooks` belongs to the caller, and installing into it would leave a
1913
+ // hook firing on every later evaluation they run through it, with the
1914
+ // unsubscribe this call discards as the only way off. A caller who wants
1915
+ // both passes their own registry and installs the hook on it themselves.
1916
+ if (!this._hooks && readTrackTime(options)) {
1917
+ // Registering here rather than lazily means `isActive` has latched before
1918
+ // the walk starts, so every node dispatches for its whole duration. That
1919
+ // is what was asked for: per-node-type totals cannot be had without
1920
+ // visiting each node, and `EvalResult.duration` already covers the
1921
+ // cheaper walk-level question.
1922
+ createTimingHook().install(this.hooks);
1923
+ }
1229
1924
  }
1230
1925
  /**
1231
1926
  * Creates an instance of EvalState from a given context, options, and async flag.
@@ -1273,24 +1968,41 @@ const popVisitorResultAsync = (node, st) => {
1273
1968
  return value;
1274
1969
  };
1275
1970
 
1971
+ /**
1972
+ * Opens a node: records it as open and fires the registered 'before' hooks.
1973
+ *
1974
+ * Called at the top of every visitor body. The guard is a single boolean field
1975
+ * read - no options lookup - so an evaluation with no hooks pays almost
1976
+ * nothing, and it wraps the open-node bookkeeping as well as the hooks
1977
+ * themselves so `enter` and `exit` cannot become unpaired mid-walk.
1978
+ */
1276
1979
  const beforeVisitor = (node, st) => {
1277
- const options = st.options;
1278
- if (options?.['trackTime']) {
1279
- const t = performance.now();
1280
- console.time('before: ' + node.type);
1281
- return t;
1980
+ if (!st.hasHooks) {
1981
+ return;
1282
1982
  }
1283
- return undefined;
1983
+ st.hooks.dispatch('before', node, st);
1284
1984
  };
1285
1985
 
1986
+ /**
1987
+ * Closes a node: pops it off the open-node stack and fires the registered
1988
+ * 'after' hooks.
1989
+ *
1990
+ * The event's `value` is read **positionally** - it is whatever sits on top of
1991
+ * the result stack right now, not something keyed to this node. Reading it here
1992
+ * is what makes the value available without changing any visitor's call
1993
+ * signature, and it is correct for every visitor that pushes its result
1994
+ * immediately before calling this. A visitor that reaches this without pushing
1995
+ * would report its *neighbour's* value, not `undefined`; the length check below
1996
+ * only guards the empty stack, since `Stack.peek` is non-destructive but does
1997
+ * not bounds-check.
1998
+ */
1286
1999
  const afterVisitor = (node, st) => {
1287
- const options = st.options;
1288
- if (options?.['trackTime']) {
1289
- const t = performance.now();
1290
- console.time('after: ' + node.type);
1291
- return t;
2000
+ if (!st.hasHooks) {
2001
+ return;
1292
2002
  }
1293
- return undefined;
2003
+ const stack = st.result?.stack;
2004
+ const value = stack && stack.length > 0 ? stack.peek() : undefined;
2005
+ st.hooks.dispatch('after', node, st, value);
1294
2006
  };
1295
2007
 
1296
2008
  var RecursiveVisitorResultType;
@@ -1305,24 +2017,75 @@ const literals = Registry.fromObject({
1305
2017
  'true': true,
1306
2018
  'false': false,
1307
2019
  }, { caseInsensitive: true });
2020
+ /**
2021
+ * Reports a resolved identifier read to the hook layer.
2022
+ *
2023
+ * The key is the one the context actually matched, so a case-insensitive
2024
+ * lookup reports the corrected spelling; `getKey` returns undefined for a name
2025
+ * the context does not hold - a literal-registry resolution, or a miss - and
2026
+ * the source name stands in. The path is always the source spelling, since it
2027
+ * is reconstructed statically.
2028
+ *
2029
+ * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
2030
+ * an arrow-function parameter. It is asked of `EvalContext.hasInScopes`, which
2031
+ * tests for the binding rather than for its value: a parameter bound to
2032
+ * `undefined` is still a parameter, and reading the flag off the resolved value
2033
+ * would make it vary with the data rather than with the expression.
2034
+ *
2035
+ * It is deliberately *not* set for `priorScopes`: those hold caller-registered,
2036
+ * long-lived objects and are real dependencies, so the discriminator is
2037
+ * lifetime rather than `instanceof EvalScope`. The property is omitted rather
2038
+ * than set to false, so absent reads as "not scoped" the same way it does at
2039
+ * the member emission sites.
2040
+ *
2041
+ * The scope stack is empty for any expression without an arrow function, and
2042
+ * `Stack.asArray` allocates, so the common case is short-circuited on length.
2043
+ */
2044
+ const emitRead = (node, st, value) => {
2045
+ const key = st.context?.getKey(node.name) ?? node.name;
2046
+ const scoped = !!st.context
2047
+ && st.context.scopes.length > 0
2048
+ && st.context.hasInScopes(node.name);
2049
+ st.hooks.dispatchRead({
2050
+ kind: 'identifier',
2051
+ node,
2052
+ state: st,
2053
+ key,
2054
+ target: st.context,
2055
+ path: node.name,
2056
+ value,
2057
+ ...(scoped ? { scoped: true } : {})
2058
+ });
2059
+ };
1308
2060
  const identifierVisitor = (node, st) => {
1309
2061
  if (st.options?.caseInsensitive) {
1310
2062
  return identifierVisitorCaseInsensitive(node, st);
1311
2063
  }
1312
2064
  beforeVisitor(node, st);
1313
2065
  const context = st.context;
1314
- const value = node.name === 'this'
2066
+ const isThis = node.name === 'this';
2067
+ const value = isThis
1315
2068
  ? st.context
1316
2069
  : context?.get(node.name);
2070
+ // `this` resolves to the context object itself rather than to a key within
2071
+ // it, so it is not a read: reporting it would have a dependency tracker
2072
+ // record the whole context and re-fire on every change to it.
2073
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
2074
+ emitRead(node, st, value);
2075
+ }
1317
2076
  pushVisitorResult(node, st, value);
1318
2077
  afterVisitor(node, st);
1319
2078
  };
1320
2079
  const identifierVisitorCaseInsensitive = (node, st) => {
1321
2080
  beforeVisitor(node, st);
1322
2081
  const context = st.context;
1323
- const value = equalIgnoreCase(node.name, 'this')
2082
+ const isThis = !!equalIgnoreCase(node.name, 'this');
2083
+ const value = isThis
1324
2084
  ? st.context
1325
2085
  : context?.get(node.name) ?? literals.get(node.name);
2086
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
2087
+ emitRead(node, st, value);
2088
+ }
1326
2089
  pushVisitorResult(node, st, value);
1327
2090
  afterVisitor(node, st);
1328
2091
  };
@@ -1834,6 +2597,37 @@ function getPropertyLookupCacheStats() {
1834
2597
  }
1835
2598
 
1836
2599
  // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
2600
+ /**
2601
+ * Reconstructs the dotted source path of a member chain (`a.b.c`).
2602
+ *
2603
+ * Static only: a computed hop (`a[expr]`, `a["b"]`) leaves the path
2604
+ * unreconstructible and yields undefined, and a consumer falls back to
2605
+ * `target` + `key` identity - which is exact either way. The parts are source
2606
+ * spellings, so under `caseInsensitive` the path is not corrected even though
2607
+ * the reported key is; optional markers are not represented either, so `a?.b`
2608
+ * reconstructs as `a.b`. A chain rooted at anything but an `Identifier` - a
2609
+ * `this`, a call, a `super` - yields undefined.
2610
+ *
2611
+ * Walks the chain once per member read, so every call site sits behind
2612
+ * `st.hasHooks && st.hooks.hasReadHooks`: a consumer that registered only node
2613
+ * hooks must not pay for a path it can never observe.
2614
+ */
2615
+ const readPath = (node) => {
2616
+ const parts = [];
2617
+ let current = node;
2618
+ while (current.type === 'MemberExpression') {
2619
+ if (current.computed || current.property.type !== 'Identifier') {
2620
+ return undefined;
2621
+ }
2622
+ parts.unshift(current.property.name);
2623
+ current = current.object;
2624
+ }
2625
+ if (current.type !== 'Identifier') {
2626
+ return undefined;
2627
+ }
2628
+ parts.unshift(current.name);
2629
+ return parts.join('.');
2630
+ };
1837
2631
  const memberExpressionVisitor = (node, st, callback) => {
1838
2632
  beforeVisitor(node, st);
1839
2633
  // Disable visitor result caching for now due to context sensitivity issues
@@ -1877,17 +2671,42 @@ const evaluateMember = (node, st, callback) => {
1877
2671
  : key;
1878
2672
  const value = st.context.get(contextKey);
1879
2673
  const thisValue = st.context.getThis(contextKey);
2674
+ if (st.hasHooks && st.hooks.hasReadHooks) {
2675
+ st.hooks.dispatchRead({
2676
+ kind: 'member',
2677
+ node,
2678
+ state: st,
2679
+ key: contextKey ?? key,
2680
+ target: st.context,
2681
+ path: readPath(node),
2682
+ value
2683
+ });
2684
+ }
1880
2685
  return [thisValue ?? object, contextKey, value];
1881
2686
  }
1882
2687
  else if (object instanceof EvalScope) {
1883
2688
  // For scope objects, preserve original behavior (no getKey method)
1884
2689
  const value = object.get(key);
1885
2690
  const thisValue = object;
2691
+ if (st.hasHooks && st.hooks.hasReadHooks) {
2692
+ st.hooks.dispatchRead({
2693
+ kind: 'member',
2694
+ node,
2695
+ state: st,
2696
+ key,
2697
+ target: object,
2698
+ path: readPath(node),
2699
+ value
2700
+ });
2701
+ }
1886
2702
  return [thisValue ?? object, key, value];
1887
2703
  }
1888
2704
  else {
1889
2705
  // For regular objects, we need both case-insensitive lookup AND prototype pollution protection
1890
2706
  let value;
2707
+ // The key the lookup actually matched, reported to the read hooks. The
2708
+ // returned tuple keeps the original `key`; only the event is corrected.
2709
+ let resolvedKey = key;
1891
2710
  // Check if this is a primitive type (string, number, boolean) - these are safe for method access
1892
2711
  const isPrimitive = (typeof object === 'string' || typeof object === 'number' || typeof object === 'boolean');
1893
2712
  if (st.options?.caseInsensitive && typeof key === 'string') {
@@ -1947,6 +2766,9 @@ const evaluateMember = (node, st, callback) => {
1947
2766
  // For objects, use safe property access
1948
2767
  value = foundKey ? obj[foundKey] : safeGetProperty(object, key);
1949
2768
  }
2769
+ if (foundKey) {
2770
+ resolvedKey = foundKey;
2771
+ }
1950
2772
  }
1951
2773
  else {
1952
2774
  // Use safe property access for prototype pollution protection (but not for primitives)
@@ -1958,6 +2780,17 @@ const evaluateMember = (node, st, callback) => {
1958
2780
  value = safeGetProperty(object, key);
1959
2781
  }
1960
2782
  }
2783
+ if (st.hasHooks && st.hooks.hasReadHooks) {
2784
+ st.hooks.dispatchRead({
2785
+ kind: 'member',
2786
+ node,
2787
+ state: st,
2788
+ key: resolvedKey,
2789
+ target: object,
2790
+ path: readPath(node),
2791
+ value
2792
+ });
2793
+ }
1961
2794
  return [object, key, value];
1962
2795
  }
1963
2796
  };
@@ -2643,6 +3476,9 @@ const extractExpression = (program) => {
2643
3476
  const evaluate = (node, state) => {
2644
3477
  if (node) {
2645
3478
  state.result.start();
3479
+ // Captured inside the `if (node)` block on purpose: callers reach the early
3480
+ // return above with a bare state that has no hooks to read. Do not hoist.
3481
+ const mark = state.hasHooks ? state.hooks.depth(state) : 0;
2646
3482
  try {
2647
3483
  const visitors = getDefaultVisitors();
2648
3484
  walk.recursive(node, state, visitors);
@@ -2653,6 +3489,13 @@ const evaluate = (node, state) => {
2653
3489
  }
2654
3490
  catch (error) {
2655
3491
  state.result.stop();
3492
+ // A visitor that throws skips its afterVisitor, so close whatever this
3493
+ // walk left open. Unwinding to the mark rather than to the bottom is what
3494
+ // stops a nested evaluate - the arrow-function body runs on this same
3495
+ // state - from draining the enclosing walk's open nodes.
3496
+ if (state.hasHooks) {
3497
+ state.hooks.unwindTo(mark, error, state);
3498
+ }
2656
3499
  state.result.setFailure(error);
2657
3500
  throw error;
2658
3501
  }
@@ -2722,6 +3565,9 @@ const evaluateAsync = async (ast, state) => {
2722
3565
  return undefined;
2723
3566
  }
2724
3567
  state.result.start();
3568
+ // Captured after the `!ast` early return above, for the same reason the sync
3569
+ // entry point captures inside its `if (node)` block. Do not hoist.
3570
+ const mark = state.hasHooks ? state.hooks.depth(state) : 0;
2725
3571
  try {
2726
3572
  const visitors = getDefaultVisitors();
2727
3573
  walk.recursive(ast, state, visitors);
@@ -2743,6 +3589,14 @@ const evaluateAsync = async (ast, state) => {
2743
3589
  }
2744
3590
  catch (error) {
2745
3591
  state.result.stop();
3592
+ // The walk here is synchronous too, so it strands open nodes on a throw
3593
+ // exactly as the sync entry point does. This catch also receives the
3594
+ // rethrow from the awaitAllPromises handler above; in that case the walk
3595
+ // had already closed every node it opened, the depth is back at the mark,
3596
+ // and unwindTo correctly synthesises nothing.
3597
+ if (state.hasHooks) {
3598
+ state.hooks.unwindTo(mark, error, state);
3599
+ }
2746
3600
  state.result.setFailure(error);
2747
3601
  throw error;
2748
3602
  }
@@ -3035,6 +3889,100 @@ class EvalScope {
3035
3889
  }
3036
3890
  }
3037
3891
 
3892
+ /** The first segment of a dotted path: `a.b.c` -> `a`. */
3893
+ const rootOf = (path) => {
3894
+ const dot = path.indexOf('.');
3895
+ return dot < 0 ? path : path.slice(0, dot);
3896
+ };
3897
+ /**
3898
+ * Creates a dependency tracker.
3899
+ *
3900
+ * `reads` keeps everything. `dependencies` is the filtered view, and three
3901
+ * rules do the filtering:
3902
+ *
3903
+ * 1. **Scope bindings are not dependencies.** A read flagged `scoped` resolved
3904
+ * from a scope pushed during the walk - an arrow-function parameter. Only
3905
+ * the walker can tell one from a real context read, which is why the flag
3906
+ * exists; a consumer using this tracker inherits the filtering for free.
3907
+ * 2. **Nor is anything reached *through* one.** `item` being a binding makes
3908
+ * `item.name` one too, and that read carries no flag of its own: `scoped` is
3909
+ * set at identifier resolution, and the member hop resolves against the
3910
+ * bound object rather than against a scope. So the bound names are
3911
+ * remembered and any path rooted at one is dropped.
3912
+ * 3. **A method reached through a member hop is a call target, not data.**
3913
+ * `list.map` in `list.map(item => item.name)` resolves to
3914
+ * `Array.prototype.map`; recording it would put a built-in in the dependency
3915
+ * set, while `list` - already recorded - is the thing whose change actually
3916
+ * matters. Bare identifiers are exempt, function-valued or not: a
3917
+ * context-level callable was named directly rather than reached through an
3918
+ * object, and there is no already-recorded object standing in for it.
3919
+ *
3920
+ * Two limits, both consequences of keying on path strings:
3921
+ *
3922
+ * - **A computed member contributes nothing.** `obj[expr]` has no
3923
+ * reconstructible path, and its resolved key alone is not a usable key
3924
+ * without one. It is in `reads` with an exact `key` and `target`, for a
3925
+ * consumer willing to key on identity.
3926
+ * - **Names collide.** Rule 2 keys on the *name*, so once `item` has been an
3927
+ * arrow parameter anywhere in the expression, a genuine `item.x` elsewhere in
3928
+ * it is dropped too. Path strings from different arrow bodies collide the
3929
+ * same way. § 9 hands the identity-versus-paths question to Phase 3; this is
3930
+ * the paths half of it.
3931
+ *
3932
+ * ```ts
3933
+ * const tracker = createDependencyTracker();
3934
+ * const state = evalService.createState({ a: { b: 1 }, c: 2 });
3935
+ * const off = tracker.install(state.hooks);
3936
+ *
3937
+ * evalService.eval('a.b + c', state);
3938
+ * tracker.dependencies; // Set { 'a', 'a.b', 'c' }
3939
+ *
3940
+ * tracker.reset();
3941
+ * off();
3942
+ * ```
3943
+ *
3944
+ * @returns A tracker; nothing is collected until {@link EvalDependencyTracker.install}
3945
+ * is called.
3946
+ */
3947
+ const createDependencyTracker = () => {
3948
+ const dependencies = new Set();
3949
+ const reads = [];
3950
+ const bindings = new Set();
3951
+ const record = (event) => {
3952
+ reads.push(event);
3953
+ const path = event.path;
3954
+ if (event.scoped) {
3955
+ // Rule 1, and the source of rule 2's name set.
3956
+ if (path !== undefined) {
3957
+ bindings.add(path);
3958
+ }
3959
+ return;
3960
+ }
3961
+ if (path === undefined) {
3962
+ return;
3963
+ }
3964
+ if (bindings.has(rootOf(path))) {
3965
+ return; // rule 2
3966
+ }
3967
+ if (event.kind === 'member' && typeof event.value === 'function') {
3968
+ return; // rule 3
3969
+ }
3970
+ dependencies.add(path);
3971
+ };
3972
+ return {
3973
+ install(hooks) {
3974
+ return hooks.onRead(record);
3975
+ },
3976
+ dependencies,
3977
+ reads,
3978
+ reset() {
3979
+ dependencies.clear();
3980
+ reads.length = 0;
3981
+ bindings.clear();
3982
+ }
3983
+ };
3984
+ };
3985
+
3038
3986
  /**
3039
3987
  * Base class for evaluation.
3040
3988
  */
@@ -3207,10 +4155,10 @@ class ParserService {
3207
4155
  }
3208
4156
  return undefined;
3209
4157
  }
3210
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: ParserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
3211
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: ParserService, providedIn: 'root' }); }
4158
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: ParserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
4159
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: ParserService, providedIn: 'root' }); }
3212
4160
  }
3213
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: ParserService, decorators: [{
4161
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: ParserService, decorators: [{
3214
4162
  type: Injectable,
3215
4163
  args: [{
3216
4164
  providedIn: 'root'
@@ -3223,14 +4171,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImpor
3223
4171
  class EvalService extends BaseEval {
3224
4172
  /**
3225
4173
  * Constructs a new instance of the EvalService class.
3226
- * @param parserService The parser service used for parsing expressions.
3227
4174
  */
3228
- constructor(parserService) {
3229
- super(parserService);
3230
- this.parserService = parserService;
4175
+ constructor() {
4176
+ super(inject(ParserService));
3231
4177
  this._isDestroyed = false;
3232
4178
  this._activeContexts = new Set();
3233
4179
  this._activeStates = new Set();
4180
+ this.parserService = inject(ParserService);
3234
4181
  this.parserOptions = defaultParserOptions;
3235
4182
  }
3236
4183
  /**
@@ -3275,6 +4222,23 @@ class EvalService extends BaseEval {
3275
4222
  if (state.context && typeof state.context === 'object' && 'clear' in state.context && typeof state.context.clear === 'function') {
3276
4223
  state.context.clear();
3277
4224
  }
4225
+ // Drop hook registrations so a long-lived closure cannot pin a
4226
+ // destroyed state. This matters most for a registry the caller passed
4227
+ // through `options.hooks` and still holds: one that outlives the
4228
+ // service keeps every state its closures captured reachable. A
4229
+ // state-owned registry would die with its state regardless.
4230
+ //
4231
+ // Guarded on `hasHooks` rather than reading `state.hooks`, because that
4232
+ // getter builds a registry on first access - allocating inside the
4233
+ // method whose job is releasing memory. The guard is exact for this
4234
+ // purpose: it is false only when no hook is registered, and clearing an
4235
+ // empty registry does nothing.
4236
+ if (state.hasHooks) {
4237
+ state.hooks.clear();
4238
+ }
4239
+ // Bookkeeping lives on the state and `clear` cannot reach it, so the
4240
+ // open-node stack and collected errors need dropping separately.
4241
+ state.resetHookBookkeeping();
3278
4242
  }
3279
4243
  catch (error) {
3280
4244
  console.warn('Error cleaning up EvalState:', error);
@@ -3398,31 +4362,31 @@ class EvalService extends BaseEval {
3398
4362
  }
3399
4363
  }
3400
4364
  }
3401
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EvalService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3402
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EvalService, providedIn: 'root' }); }
4365
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: EvalService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
4366
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: EvalService, providedIn: 'root' }); }
3403
4367
  }
3404
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EvalService, decorators: [{
4368
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: EvalService, decorators: [{
3405
4369
  type: Injectable,
3406
4370
  args: [{
3407
4371
  providedIn: 'root'
3408
4372
  }]
3409
- }], ctorParameters: () => [{ type: ParserService }] });
4373
+ }], ctorParameters: () => [] });
3410
4374
 
3411
4375
  /**
3412
4376
  * CompilerService class that extends BaseEval.
3413
4377
  * Provides methods for compiling and evaluating expressions with performance caching.
3414
4378
  */
3415
4379
  class CompilerService extends BaseEval {
3416
- constructor(parserService, evalService) {
3417
- super(parserService);
3418
- this.parserService = parserService;
3419
- this.evalService = evalService;
4380
+ constructor() {
4381
+ super(inject(ParserService));
3420
4382
  // Compilation cache with LRU eviction
3421
4383
  this._compilationCache = new Map();
3422
4384
  this._maxCacheSize = 200;
3423
4385
  this._cacheTTL = 10 * 60 * 1000; // 10 minutes
3424
4386
  this._accessOrder = new Set();
3425
4387
  this._isDestroyed = false;
4388
+ this.parserService = inject(ParserService);
4389
+ this.evalService = inject(EvalService);
3426
4390
  this.parserOptions = defaultParserOptions;
3427
4391
  this.setupCacheCleanup();
3428
4392
  }
@@ -3700,15 +4664,15 @@ class CompilerService extends BaseEval {
3700
4664
  }
3701
4665
  return undefined;
3702
4666
  }
3703
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: CompilerService, deps: [{ token: ParserService }, { token: EvalService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3704
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: CompilerService, providedIn: 'root' }); }
4667
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: CompilerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
4668
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: CompilerService, providedIn: 'root' }); }
3705
4669
  }
3706
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: CompilerService, decorators: [{
4670
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: CompilerService, decorators: [{
3707
4671
  type: Injectable,
3708
4672
  args: [{
3709
4673
  providedIn: 'root'
3710
4674
  }]
3711
- }], ctorParameters: () => [{ type: ParserService }, { type: EvalService }] });
4675
+ }], ctorParameters: () => [] });
3712
4676
 
3713
4677
  /**
3714
4678
  * Service responsible for discovering nodes in an abstract syntax tree (AST).
@@ -3716,11 +4680,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImpor
3716
4680
  class DiscoveryService extends BaseEval {
3717
4681
  /**
3718
4682
  * Creates a new instance of the DiscoveryService class.
3719
- * @param parserService The parser service to be used.
3720
4683
  */
3721
- constructor(parserService) {
3722
- super(parserService);
3723
- this.parserService = parserService;
4684
+ constructor() {
4685
+ super(inject(ParserService));
4686
+ this.parserService = inject(ParserService);
3724
4687
  this.parserOptions = {
3725
4688
  ...defaultParserOptions,
3726
4689
  cacheSize: undefined
@@ -3749,19 +4712,19 @@ class DiscoveryService extends BaseEval {
3749
4712
  }
3750
4713
  }
3751
4714
  }
3752
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: DiscoveryService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3753
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: DiscoveryService, providedIn: 'root' }); }
4715
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: DiscoveryService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
4716
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: DiscoveryService, providedIn: 'root' }); }
3754
4717
  }
3755
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: DiscoveryService, decorators: [{
4718
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImport: i0, type: DiscoveryService, decorators: [{
3756
4719
  type: Injectable,
3757
4720
  args: [{
3758
4721
  providedIn: 'root'
3759
4722
  }]
3760
- }], ctorParameters: () => [{ type: ParserService }] });
4723
+ }], ctorParameters: () => [] });
3761
4724
 
3762
4725
  /**
3763
4726
  * Generated bundle index. Do not edit.
3764
4727
  */
3765
4728
 
3766
- export { BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EvalContext, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Stack, call, callAsync, compile, compileAsync, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
4729
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
3767
4730
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map