@zvenigora/ng-eval-core 0.9.0 → 0.10.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/CHANGELOG.md CHANGED
@@ -14,7 +14,50 @@ Versions 0.1.104–0.1.107 are on npm without entries here.
14
14
 
15
15
  ---
16
16
 
17
- ## [0.9.0] - 2026-10-02
17
+ ## [0.10.0] - 2026-10-03
18
+
19
+ **An opt-in member-write policy on `EvalContext`, and three fixes.** Nothing changes for a context
20
+ that does not opt in, and every change to an exported symbol is an addition: `EvalContext` gains
21
+ an optional method and `EvalMemberWrite` is new. The three fixes change what an expression
22
+ evaluates to, where it was wrong, and one of them adds a behaviour: a member write now runs the
23
+ caller's setter. `eval-signals` 0.3.0 builds on the policy and requires this version.
24
+
25
+ ### Added
26
+ - **`EvalContext.checkMemberWrite?(write: EvalMemberWrite)`**, an optional method, and the
27
+ **`EvalMemberWrite`** interface, `{ target, key, createdByEvaluation }`. A subclass that
28
+ implements the method is asked before every member write — `o.k = v`, `o.k += v`, `o.k++` —
29
+ none of which reach `set`. To refuse one it throws, and nothing is written. `createdByEvaluation`
30
+ says whether the walk created the target: an object, array or regex literal, a rest value, or an
31
+ arrow function. A call's result and a `new` result never count, even when new, because either
32
+ can return an existing object — `[o].find(x => true)` returns `o`. Implementing the method is the
33
+ opt-in: the walk then records, per `EvalState`, the objects it creates. A context that does not
34
+ implement it pays one field read at each recording site and each member write, and nothing else.
35
+
36
+ ### Fixed
37
+ - **A regex literal is a new `RegExp` on each evaluation.** Acorn builds a regex literal's
38
+ `RegExp` once, at parse time, and every evaluation of one parsed expression shared it — a
39
+ string `EvalService` has cached, and each call of a compiled expression — so a global regex
40
+ carried `lastIndex` from one evaluation into the next: `let r = /a/g; r.test("a")` answered
41
+ `true`, then `false`. Each evaluation now pushes a copy with the same source and flags, at
42
+ `lastIndex` 0, and `let f = () => /a/; f() === f()` is `false`, as in JavaScript.
43
+ - **A hole in an array pattern keeps its position.** Holes were dropped before binding by index,
44
+ so every element after one read its neighbour's value: `let [, b] = [1, 2]` bound `b` to `1`,
45
+ `(([, y]) => y)([1, 2])` returned `1`, and `let [, ...r] = [1, 2, 3]` bound `r` to
46
+ `[1, 2, 3]`. They now bind as JavaScript does: `2`, `2` and `[2, 3]`.
47
+ - **A member write assigns, as JavaScript does — [A23](../../docs/backlog-retired.md#a23).**
48
+ `o.k = v`, `o.k += v` and `o.k++` defined the property with `Object.defineProperty` instead, after
49
+ the same prototype-pollution refusals, which are unchanged. So `r.lastIndex = 0` on a regex and
50
+ `a.length = 0` on an array threw `Failed to set property … Cannot redefine property`, as did any
51
+ non-configurable property; a non-enumerable property became enumerable; and a setter on the
52
+ object you passed in was replaced, or an inherited one hidden, without ever running. Now each
53
+ is an assignment. **Setters now run, and that is the only new behaviour**: reads already ran
54
+ your getters, and a write already ran the getter, reading its target first. A write the object
55
+ refuses — frozen, non-writable, an accessor with no setter — throws, prefixed
56
+ `Failed to set property`, where an accessor with no setter used to be silently replaced.
57
+
58
+ ---
59
+
60
+ ## [0.9.0] - 2026-10-03
18
61
 
19
62
  **A primitive receiver no longer skips the prototype-pollution guard —
20
63
  [B1](../../docs/backlog-retired.md#b1).** A breaking minor. No exported symbol changes shape, but an
@@ -1009,7 +1009,20 @@ const identifierVisitorCaseInsensitive = (node, st) => {
1009
1009
 
1010
1010
  const literalVisitor = (node, st) => {
1011
1011
  beforeVisitor(node, st);
1012
- const value = node.value;
1012
+ // A regex literal is a new `RegExp` on every evaluation, as it is in
1013
+ // JavaScript. Acorn builds `node.value` once, at parse time, and every walk of
1014
+ // the parsed tree used to push that one object - a cached `simpleEval` string
1015
+ // and each recompute of a compiled expression alike - so `lastIndex` carried
1016
+ // from one evaluation into the next, and `/a/g.test("a")` answered true, then
1017
+ // false. A copy starts at `lastIndex` 0, and being new it is recorded under a
1018
+ // member-write policy, as a literal is - `EvalContext.checkMemberWrite`. When
1019
+ // acorn could not build the regex in this environment, `value` is null and is
1020
+ // pushed as before.
1021
+ let value = node.value;
1022
+ if (value instanceof RegExp) {
1023
+ value = new RegExp(value);
1024
+ st.createdObjects?.add(value);
1025
+ }
1013
1026
  pushVisitorResult(node, st, value);
1014
1027
  afterVisitor(node, st);
1015
1028
  };
@@ -1274,11 +1287,14 @@ const isDangerousConstructor = (obj) => {
1274
1287
  return false;
1275
1288
  };
1276
1289
  /**
1277
- * Safely sets a property on an object with prototype pollution protection
1290
+ * Safely sets a property on an object with prototype pollution protection.
1291
+ * Refuses a dangerous target or key, then assigns - so a setter runs, and a
1292
+ * write the object refuses throws, prefixed "Failed to set property".
1278
1293
  * @param target The target object
1279
1294
  * @param key The property key
1280
1295
  * @param value The property value
1281
- * @throws Error if the operation would cause prototype pollution
1296
+ * @throws Error if the operation would cause prototype pollution, or if the
1297
+ * object refuses the write
1282
1298
  */
1283
1299
  const safeSetProperty = (target, key, value) => {
1284
1300
  if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
@@ -1309,15 +1325,18 @@ const safeSetProperty = (target, key, value) => {
1309
1325
  // For other types, try to convert to string
1310
1326
  propertyKey = String(key);
1311
1327
  }
1312
- // Use Object.defineProperty for safer assignment
1313
- const descriptor = {
1314
- value,
1315
- writable: true,
1316
- enumerable: true,
1317
- configurable: true
1318
- };
1328
+ // An assignment, after every refusal above - not a definition. Up to 0.9.x
1329
+ // this was `Object.defineProperty` with a writable, enumerable, configurable
1330
+ // descriptor (`docs/backlog-retired.md` A23), which a write in JavaScript is
1331
+ // not: it replaced an own accessor and hid an inherited one, so no setter
1332
+ // ever ran; it made a non-enumerable property enumerable; and it refused
1333
+ // every non-configurable property, `lastIndex` and an array's `length`
1334
+ // included. Reads already ran the caller's getters, so running its setters
1335
+ // here is the one behaviour this adds. This module is strict, so a write the
1336
+ // object refuses - frozen, non-writable, an accessor with no setter - throws
1337
+ // rather than failing silently, and is reported below.
1319
1338
  try {
1320
- Object.defineProperty(target, propertyKey, descriptor);
1339
+ target[propertyKey] = value;
1321
1340
  }
1322
1341
  catch (error) {
1323
1342
  throw new Error(`Failed to set property "${String(key)}": ${error instanceof Error ? error.message : String(error)}`);
@@ -1755,6 +1774,10 @@ const evaluateMember = (node, st, callback) => {
1755
1774
  const arrayExpressionVisitor = (node, st, callback) => {
1756
1775
  beforeVisitor(node, st);
1757
1776
  const elements = evaluateArray(node, node.elements, st, callback);
1777
+ // Recorded only under a member-write policy - `EvalContext.checkMemberWrite`.
1778
+ // Here and not in `evaluateArray`, which also builds call and `new` argument
1779
+ // lists: those are not literals the expression can hold.
1780
+ st.createdObjects?.add(elements);
1758
1781
  pushVisitorResult(node, st, elements);
1759
1782
  afterVisitor(node, st);
1760
1783
  };
@@ -2267,6 +2290,8 @@ const objectExpressionVisitor = (node, st, callback) => {
2267
2290
  // Create safe object with prototype pollution protection
2268
2291
  try {
2269
2292
  const obj = createSafeObject(entries);
2293
+ // Recorded only under a member-write policy - `EvalContext.checkMemberWrite`.
2294
+ st.createdObjects?.add(obj);
2270
2295
  pushVisitorResult(node, st, obj);
2271
2296
  }
2272
2297
  catch (error) {
@@ -2341,6 +2366,51 @@ const getDefaultVisitors = () => {
2341
2366
  return visitors;
2342
2367
  };
2343
2368
 
2369
+ /**
2370
+ * Whether `value` can be held in a `WeakSet` - an object or a function.
2371
+ */
2372
+ const isObjectLike = (value) => (typeof value === 'object' && value !== null) || typeof value === 'function';
2373
+ /**
2374
+ * Records `value` as created by the walk, unless it is a primitive.
2375
+ *
2376
+ * For the one recording site whose value may be a primitive: an array or
2377
+ * parameter rest is `args.slice(i)`, which is a string when the destructured
2378
+ * source is one (`let [h, ...t] = "abc"`), and `WeakSet.add` throws on a
2379
+ * primitive. The literal, object-rest and arrow-function sites always create
2380
+ * an object and add directly.
2381
+ *
2382
+ * @param created - `st.createdObjects`, already read and found set by the caller.
2383
+ * @param value - The value the walk created.
2384
+ */
2385
+ const recordCreated = (created, value) => {
2386
+ if (isObjectLike(value)) {
2387
+ created.add(value);
2388
+ }
2389
+ };
2390
+ /**
2391
+ * Asks the context whether a member write may happen, through
2392
+ * `EvalContext.checkMemberWrite`. A refusal is a throw, and it propagates from
2393
+ * here unchanged: nothing has been written yet.
2394
+ *
2395
+ * Called by the member branches of `assignment-expression.ts` and
2396
+ * `update-expression.ts`, immediately before `safeSetProperty`, and only after
2397
+ * the caller has read `st.createdObjects` and found it set. That read is the
2398
+ * whole of the default path's cost: a state whose context has no policy holds
2399
+ * no set, so neither visitor reaches this call.
2400
+ *
2401
+ * @param st - The state of the walk making the write.
2402
+ * @param created - `st.createdObjects`, already read by the caller.
2403
+ * @param target - The object about to receive the write.
2404
+ * @param key - The property about to be written.
2405
+ */
2406
+ const consultMemberWrite = (st, created, target, key) => {
2407
+ st.context?.checkMemberWrite?.({
2408
+ target,
2409
+ key,
2410
+ createdByEvaluation: isObjectLike(target) && created.has(target),
2411
+ });
2412
+ };
2413
+
2344
2414
  // based on evalArrowContext
2345
2415
  // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
2346
2416
  /**
@@ -2365,6 +2435,13 @@ const unsupportedBindingTarget = (type) => {
2365
2435
  const evaluatePatterns = (patterns, st, callback, args) => {
2366
2436
  let context = {};
2367
2437
  patterns.map((pattern, i) => {
2438
+ // A hole - the elision in `[, b]` - binds nothing, and is skipped *here*
2439
+ // so that every pattern after it keeps its own index into `args`, the
2440
+ // rest's `args.slice(i)` included. Only an array pattern can hold one: a
2441
+ // parameter list with a hole does not parse.
2442
+ if (pattern === null) {
2443
+ return;
2444
+ }
2368
2445
  switch (pattern.type) {
2369
2446
  case 'Identifier':
2370
2447
  {
@@ -2392,7 +2469,15 @@ const evaluatePatterns = (patterns, st, callback, args) => {
2392
2469
  break;
2393
2470
  case 'RestElement':
2394
2471
  {
2395
- const object = evaluateRestElement(pattern, st, callback, args.slice(i));
2472
+ // An array rest and a parameter rest are both this slice: a new
2473
+ // array the expression then holds. Recorded only under a member-write
2474
+ // policy - `EvalContext.checkMemberWrite`.
2475
+ const rest = args.slice(i);
2476
+ const created = st.createdObjects;
2477
+ if (created) {
2478
+ recordCreated(created, rest);
2479
+ }
2480
+ const object = evaluateRestElement(pattern, st, callback, rest);
2396
2481
  context = { ...context, ...object };
2397
2482
  }
2398
2483
  break;
@@ -2559,7 +2644,11 @@ const evaluateObjectPattern = (pattern, st, callback, arg) => {
2559
2644
  // element last in an object pattern, so `taken` is complete here.
2560
2645
  // Binding the whole argument left an already-destructured key on the
2561
2646
  // rest record - `docs/backlog.md` A13.
2562
- const object = evaluateRestElement(pattern, st, callback, restOf(arg, taken));
2647
+ // A new object, so recorded under a member-write policy exactly as
2648
+ // a literal is - `EvalContext.checkMemberWrite`.
2649
+ const rest = restOf(arg, taken);
2650
+ st.createdObjects?.add(rest);
2651
+ const object = evaluateRestElement(pattern, st, callback, rest);
2563
2652
  context = { ...context, ...object };
2564
2653
  }
2565
2654
  break;
@@ -2567,9 +2656,11 @@ const evaluateObjectPattern = (pattern, st, callback, arg) => {
2567
2656
  });
2568
2657
  return context;
2569
2658
  };
2659
+ // The elements go through with their holes in place. Filtering them out first
2660
+ // - which this did up to 0.9.0 - renumbered every element after a hole, so
2661
+ // `let [, b] = [1, 2]` bound `b` to 1.
2570
2662
  const evaluateArrayPattern = (pattern, st, callback, args) => {
2571
- const patterns = pattern.elements.filter(s => !!s);
2572
- const object = evaluatePatterns(patterns, st, callback, args);
2663
+ const object = evaluatePatterns(pattern.elements, st, callback, args);
2573
2664
  return object;
2574
2665
  };
2575
2666
  const evaluateRestElement = (pattern, st, callback, args) => {
@@ -2630,11 +2721,12 @@ const bindingScope = (st) => {
2630
2721
  * `pattern.ts` rather than of this module's contract with it.
2631
2722
  *
2632
2723
  * The write itself dispatches through `setContextValue`, not through
2633
- * `safeSetProperty`. `safeSetProperty` finishes with `Object.defineProperty`,
2634
- * which suits the plain records `pattern.ts` builds and **not** a scope: a
2635
- * `caseInsensitive` scope is a Map-backed `Registry`, and defining a property
2636
- * on the instance inserts nothing into its map. The binding would be written
2637
- * and then not found, silently, for that option only.
2724
+ * `safeSetProperty`. `safeSetProperty` writes a property onto the object it is
2725
+ * given - by assignment since 0.10.0, by `Object.defineProperty` before - which
2726
+ * suits the plain records `pattern.ts` builds and **not** a scope: a
2727
+ * `caseInsensitive` scope is a Map-backed `Registry`, and setting a property on
2728
+ * the instance, either way, inserts nothing into its map. The binding would be
2729
+ * written and then not found, silently, for that option only.
2638
2730
  */
2639
2731
  const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
2640
2732
  const bindings = evaluatePattern(declarator.id, st, callback, value);
@@ -2808,6 +2900,12 @@ const assignmentExpressionVisitor = (node, st, callback) => {
2808
2900
  else if (target.type === 'MemberExpression') {
2809
2901
  const [object, key,] = evaluateMember(target, st, callback);
2810
2902
  const value = func(left, right);
2903
+ // A member write never reaches `EvalContext.set`, so a context policing
2904
+ // writes is asked here instead - `EvalContext.checkMemberWrite`.
2905
+ const created = st.createdObjects;
2906
+ if (created) {
2907
+ consultMemberWrite(st, created, object, key);
2908
+ }
2811
2909
  // Use safe property assignment to prevent prototype pollution
2812
2910
  safeSetProperty(object, key, value);
2813
2911
  pushVisitorResult(node, st, value);
@@ -2842,6 +2940,11 @@ const updateExpressionVisitor = (node, st, callback) => {
2842
2940
  else if (target.type === 'MemberExpression') {
2843
2941
  const [object, property, value] = evaluateMember(target, st, callback);
2844
2942
  const newValue = updateOperators[node.operator](value);
2943
+ // The same consultation as `assignment-expression.ts`'s member branch.
2944
+ const created = st.createdObjects;
2945
+ if (created) {
2946
+ consultMemberWrite(st, created, object, property);
2947
+ }
2845
2948
  // Use safe property assignment to prevent prototype pollution
2846
2949
  safeSetProperty(object, property, newValue);
2847
2950
  pushVisitorResult(node, st, node.prefix ? newValue : value);
@@ -3199,6 +3302,9 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
3199
3302
  st.context?.pop();
3200
3303
  }
3201
3304
  };
3305
+ // A new function per evaluation of this node, so recorded under a
3306
+ // member-write policy - `EvalContext.checkMemberWrite`.
3307
+ st.createdObjects?.add(fn);
3202
3308
  pushVisitorResult(node, st, fn);
3203
3309
  afterVisitor(node, st);
3204
3310
  };
@@ -4053,8 +4159,10 @@ class EvalContext {
4053
4159
  * The write dispatches through `setContextValue` rather than through the
4054
4160
  * prototype-pollution guard's `safeSetProperty`, and the difference is not
4055
4161
  * cosmetic: {@link push} normalises a plain record into a `Registry` when
4056
- * `caseInsensitive` is set, and `Object.defineProperty` on a `Registry` would
4057
- * define a property on the instance while inserting nothing into its map. No
4162
+ * `caseInsensitive` is set, and `safeSetProperty` writes a property onto the
4163
+ * object it is given - by assignment since 0.10.0, by `Object.defineProperty`
4164
+ * before - which on a `Registry` sets a property on the instance while
4165
+ * inserting nothing into its map. No
4058
4166
  * guard is lost - this method only ever writes a key some scope already
4059
4167
  * *binds*, and a binding can only have been created through the guarded
4060
4168
  * declaration path, which rejects every blocklisted name.
@@ -5273,6 +5381,28 @@ class EvalState {
5273
5381
  isConstBinding(scope, key) {
5274
5382
  return !!this._constBindings?.get(scope)?.has(key);
5275
5383
  }
5384
+ /**
5385
+ * The objects this state's walk created for the expression to hold -
5386
+ * object, array and regex literals, rest values, arrow functions - or
5387
+ * undefined when its context does not police member writes. See
5388
+ * `EvalContext.checkMemberWrite`, whose presence is the opt-in, and
5389
+ * `EvalMemberWrite.createdByEvaluation` for what is deliberately left out.
5390
+ *
5391
+ * **Undefined is the default path, and the reason this is a field.** It is
5392
+ * decided once, in the constructor, so each recording site and the two
5393
+ * member-write branches pay one read of it and nothing else when no policy
5394
+ * is in force: no set is allocated and no object is recorded.
5395
+ *
5396
+ * Per state rather than per `evaluate` call, deliberately: an arrow-function
5397
+ * body re-enters the walk on this same state, possibly after the outer walk
5398
+ * has returned, and an object its enclosing expression created is still that
5399
+ * expression's own. A `WeakSet`, so recording an object never keeps it alive.
5400
+ *
5401
+ * @internal Not part of the published API.
5402
+ */
5403
+ get createdObjects() {
5404
+ return this._createdObjects;
5405
+ }
5276
5406
  /**
5277
5407
  * Drops every per-run record this state holds: the collected hook errors, the
5278
5408
  * open-node stack, the accumulated timings, and the walk bases bounding
@@ -5316,6 +5446,9 @@ class EvalState {
5316
5446
  this._options = options;
5317
5447
  this._isAsync = isAsync;
5318
5448
  this._hooks = adoptHooks(options);
5449
+ this._createdObjects = typeof context?.checkMemberWrite === 'function'
5450
+ ? new WeakSet()
5451
+ : undefined;
5319
5452
  // Options configure the registry this state owns, never an adopted one -
5320
5453
  // the same rule `onHookError` follows, and for the same reason: an adopted
5321
5454
  // `EvalHooks` belongs to the caller, and installing into it would leave a