@zvenigora/ng-eval-core 0.10.0 → 0.11.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.
@@ -400,48 +400,6 @@ class Registry {
400
400
  }
401
401
  }
402
402
 
403
- /**
404
- * Represents a generic queue data structure.
405
- * @template T The type of elements stored in the queue.
406
- */
407
- class Queue {
408
- /**
409
- * Creates a new instance of the Queue class.
410
- * @param _queue Optional initial array of elements.
411
- */
412
- constructor(_queue = []) {
413
- this._queue = _queue;
414
- }
415
- /**
416
- * Gets the number of elements in the queue.
417
- */
418
- get length() {
419
- return this._queue.length;
420
- }
421
- /**
422
- * Removes and returns the first element in the queue.
423
- * @returns The first element in the queue, or undefined if the queue is empty.
424
- */
425
- dequeue() {
426
- return this._queue.shift();
427
- }
428
- /**
429
- * Adds an element to the end of the queue.
430
- * @param value The element to add to the queue.
431
- * @returns The new length of the queue.
432
- */
433
- enqueue(value) {
434
- return this._queue.push(value);
435
- }
436
- /**
437
- * Returns the first element in the queue without removing it.
438
- * @returns The first element in the queue.
439
- */
440
- peek() {
441
- return this._queue[0];
442
- }
443
- }
444
-
445
403
  /**
446
404
  * Represents a stack data structure with proper memory management.
447
405
  * @template T The type of elements in the stack.
@@ -675,84 +633,6 @@ class Cache {
675
633
  }
676
634
  }
677
635
 
678
- /**
679
- * Strips the `ParenthesizedExpression` wrappers acorn keeps around a node
680
- * under `preserveParens`, so `(a)` and `((a))` are handled as `a`. A walk
681
- * passes through them without help, since `acorn-walk`'s base visitor does;
682
- * only a visitor that branches on a child's *type* has to unwrap it first.
683
- * @param node - The node, possibly parenthesised.
684
- * @returns The innermost node that is not a `ParenthesizedExpression`.
685
- */
686
- const unwrapParentheses = (node) => {
687
- let inner = node;
688
- while (inner.type === 'ParenthesizedExpression') {
689
- inner = inner.expression;
690
- }
691
- return inner;
692
- };
693
- /**
694
- * Retrieves the key-value pair from an object based on the provided key.
695
- * @param obj - The object to search for the key-value pair.
696
- * @param key - The key to search for in the object.
697
- * @param caseInsesitive - Specifies whether the key comparison should be case-insensitive.
698
- * @returns The key-value pair as an array, or undefined if the key is not found.
699
- */
700
- const getKeyValue = (obj, key, caseInsesitive) => {
701
- if (!caseInsesitive || typeof key !== 'string') {
702
- const value = obj[key];
703
- return [key, value];
704
- }
705
- if (typeof key === 'string') {
706
- let currentObj = obj;
707
- do {
708
- const keys = Object.getOwnPropertyNames(currentObj);
709
- if (Array.isArray(keys)) {
710
- const foundKey = keys.find(k => equalIgnoreCase(key, k));
711
- if (foundKey) {
712
- const value = currentObj[foundKey];
713
- return [foundKey, value];
714
- }
715
- }
716
- } while ((currentObj = Object.getPrototypeOf(currentObj)));
717
- }
718
- return undefined;
719
- };
720
- /**
721
- * Compares two values for equality, ignoring case sensitivity.
722
- * @param a - The first value to compare.
723
- * @param b - The second value to compare.
724
- * @returns `true` if the values are equal, `false` otherwise.
725
- */
726
- const equalIgnoreCase = (a, b) => {
727
- if (typeof a === 'number' || typeof b === 'number') {
728
- return a === b;
729
- }
730
- else if (typeof a === 'symbol' || typeof b === 'symbol') {
731
- return a === b;
732
- }
733
- else if (typeof a === 'string' || typeof b === 'string') {
734
- return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0;
735
- }
736
- return undefined;
737
- };
738
- /**
739
- * Retrieves the value from an object, ignoring the case of the key.
740
- * @param obj - The object to retrieve the value from.
741
- * @param key - The key to search for, ignoring the case.
742
- * @returns The value associated with the key, or undefined if the key is not found.
743
- */
744
- const getValueIgnoreCase = (obj, key) => {
745
- const pair = getKeyValue(obj, key, true);
746
- if (pair) {
747
- return pair[1];
748
- }
749
- return undefined;
750
- };
751
-
752
- function isRegistryContext(context) {
753
- const value = ['Registry', 'CaseInsensitiveRegistry', 'BaseRegistry'].includes(context?.type);
754
- return value;
755
- }
756
636
  /**
757
637
  * Converts a context object to a Context instance.
758
638
  * @param context - The context object to convert.
@@ -813,33 +693,6 @@ const setContextValue = (context, key, value) => {
813
693
  object[key] = value;
814
694
  }
815
695
  };
816
- /**
817
- * Retrieves the key from the given context object.
818
- * If the context is an instance of Registry, it searches for the key in a case-insensitive manner if specified.
819
- * If the context is an instance of Object, it uses the getKeyValue function to retrieve the key-value pair.
820
- * @param context - The context object.
821
- * @param key - The key to retrieve.
822
- * @param caseInsensitive - Specifies whether the search should be case-insensitive (only applicable for Registry instances).
823
- * @returns The retrieved key, or undefined if the key is not found.
824
- */
825
- const getContextKey = (context, key, caseInsensitive) => {
826
- if (context instanceof Registry) {
827
- const keys = [...context.keys]; // : (string | number | symbol)[]
828
- const foundKey = caseInsensitive && typeof key === 'string'
829
- ? keys.find(k => equalIgnoreCase(key, k))
830
- : keys.find(k => k === key);
831
- if (foundKey) {
832
- return foundKey;
833
- }
834
- }
835
- else if (context instanceof Object) {
836
- const pair = getKeyValue(context, key, caseInsensitive);
837
- if (pair) {
838
- return pair[0];
839
- }
840
- }
841
- return undefined;
842
- };
843
696
 
844
697
  /**
845
698
  * The two push helpers each carry their own trace-bound call rather than
@@ -922,274 +775,78 @@ const afterVisitor = (node, st) => {
922
775
  st.hooks.dispatch('after', node, st, value);
923
776
  };
924
777
 
925
- var RecursiveVisitorResultType;
926
- (function (RecursiveVisitorResultType) {
927
- RecursiveVisitorResultType[RecursiveVisitorResultType["Stack"] = 0] = "Stack";
928
- RecursiveVisitorResultType[RecursiveVisitorResultType["Registry"] = 1] = "Registry";
929
- })(RecursiveVisitorResultType || (RecursiveVisitorResultType = {}));
930
-
931
- const literals = Registry.fromObject({
932
- 'undefined': undefined,
933
- 'null': null,
934
- 'true': true,
935
- 'false': false,
936
- }, { caseInsensitive: true });
937
778
  /**
938
- * Reports a resolved identifier read to the hook layer.
939
- *
940
- * The key is the one the context actually matched, so a case-insensitive
941
- * lookup reports the corrected spelling; `getKey` returns undefined for a name
942
- * the context does not hold - a literal-registry resolution, or a miss - and
943
- * the source name stands in. The path is always the source spelling, since it
944
- * is reconstructed statically.
945
- *
946
- * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
947
- * an arrow-function parameter. It is asked of `EvalContext.hasInScopes`, which
948
- * tests for the binding rather than for its value: a parameter bound to
949
- * `undefined` is still a parameter, and reading the flag off the resolved value
950
- * would make it vary with the data rather than with the expression.
951
- *
952
- * It is deliberately *not* set for `priorScopes`: those hold caller-registered,
953
- * long-lived objects and are real dependencies, so the discriminator is
954
- * lifetime rather than `instanceof EvalScope`. The property is omitted rather
955
- * than set to false, so absent reads as "not scoped" the same way it does at
956
- * the member emission sites.
957
- *
958
- * The scope stack is empty for any expression without an arrow function, and
959
- * `Stack.asArray` allocates, so the common case is short-circuited on length.
779
+ * Strips the `ParenthesizedExpression` wrappers acorn keeps around a node
780
+ * under `preserveParens`, so `(a)` and `((a))` are handled as `a`. A walk
781
+ * passes through them without help, since `acorn-walk`'s base visitor does;
782
+ * only a visitor that branches on a child's *type* has to unwrap it first.
783
+ * @param node - The node, possibly parenthesised.
784
+ * @returns The innermost node that is not a `ParenthesizedExpression`.
960
785
  */
961
- const emitRead = (node, st, value) => {
962
- const key = st.context?.getKey(node.name) ?? node.name;
963
- const scoped = !!st.context
964
- && st.context.scopes.length > 0
965
- && st.context.hasInScopes(node.name);
966
- st.hooks.dispatchRead({
967
- kind: 'identifier',
968
- node,
969
- state: st,
970
- key,
971
- target: st.context,
972
- path: node.name,
973
- value,
974
- ...(scoped ? { scoped: true } : {})
975
- });
786
+ const unwrapParentheses = (node) => {
787
+ let inner = node;
788
+ while (inner.type === 'ParenthesizedExpression') {
789
+ inner = inner.expression;
790
+ }
791
+ return inner;
976
792
  };
977
- const identifierVisitor = (node, st) => {
978
- if (st.options?.caseInsensitive) {
979
- return identifierVisitorCaseInsensitive(node, st);
793
+ /**
794
+ * Retrieves the key-value pair from an object based on the provided key.
795
+ * @param obj - The object to search for the key-value pair.
796
+ * @param key - The key to search for in the object.
797
+ * @param caseInsesitive - Specifies whether the key comparison should be case-insensitive.
798
+ * @returns The key-value pair as an array, or undefined if the key is not found.
799
+ */
800
+ const getKeyValue = (obj, key, caseInsesitive) => {
801
+ if (!caseInsesitive || typeof key !== 'string') {
802
+ const value = obj[key];
803
+ return [key, value];
980
804
  }
981
- beforeVisitor(node, st);
982
- const context = st.context;
983
- const isThis = node.name === 'this';
984
- const value = isThis
985
- ? st.context
986
- : context?.get(node.name);
987
- // `this` resolves to the context object itself rather than to a key within
988
- // it, so it is not a read: reporting it would have a dependency tracker
989
- // record the whole context and re-fire on every change to it.
990
- if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
991
- emitRead(node, st, value);
805
+ if (typeof key === 'string') {
806
+ let currentObj = obj;
807
+ do {
808
+ const keys = Object.getOwnPropertyNames(currentObj);
809
+ if (Array.isArray(keys)) {
810
+ const foundKey = keys.find(k => equalIgnoreCase(key, k));
811
+ if (foundKey) {
812
+ const value = currentObj[foundKey];
813
+ return [foundKey, value];
814
+ }
815
+ }
816
+ } while ((currentObj = Object.getPrototypeOf(currentObj)));
992
817
  }
993
- pushVisitorResult(node, st, value);
994
- afterVisitor(node, st);
818
+ return undefined;
995
819
  };
996
- const identifierVisitorCaseInsensitive = (node, st) => {
997
- beforeVisitor(node, st);
998
- const context = st.context;
999
- const isThis = !!equalIgnoreCase(node.name, 'this');
1000
- const value = isThis
1001
- ? st.context
1002
- : context?.get(node.name) ?? literals.get(node.name);
1003
- if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
1004
- emitRead(node, st, value);
820
+ /**
821
+ * Compares two values for equality, ignoring case sensitivity.
822
+ * @param a - The first value to compare.
823
+ * @param b - The second value to compare.
824
+ * @returns `true` if the values are equal, `false` otherwise.
825
+ */
826
+ const equalIgnoreCase = (a, b) => {
827
+ if (typeof a === 'number' || typeof b === 'number') {
828
+ return a === b;
1005
829
  }
1006
- pushVisitorResult(node, st, value);
1007
- afterVisitor(node, st);
1008
- };
1009
-
1010
- const literalVisitor = (node, st) => {
1011
- beforeVisitor(node, st);
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);
830
+ else if (typeof a === 'symbol' || typeof b === 'symbol') {
831
+ return a === b;
1025
832
  }
1026
- pushVisitorResult(node, st, value);
1027
- afterVisitor(node, st);
833
+ else if (typeof a === 'string' || typeof b === 'string') {
834
+ return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0;
835
+ }
836
+ return undefined;
1028
837
  };
1029
-
1030
- // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
1031
838
  /**
1032
- * Converts value to primitive for comparison operations
839
+ * Retrieves the value from an object, ignoring the case of the key.
840
+ * @param obj - The object to retrieve the value from.
841
+ * @param key - The key to search for, ignoring the case.
842
+ * @returns The value associated with the key, or undefined if the key is not found.
1033
843
  */
1034
- const toPrimitive = (value, hint) => {
1035
- if (value === null || value === undefined)
1036
- return value;
1037
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||
1038
- typeof value === 'symbol' || typeof value === 'bigint')
1039
- return value;
1040
- // For objects, call valueOf/toString based on hint
1041
- if (typeof value === 'object') {
1042
- if (hint === 'number') {
1043
- const valueOf = value.valueOf;
1044
- if (typeof valueOf === 'function') {
1045
- const result = valueOf.call(value);
1046
- if (typeof result !== 'object')
1047
- return result;
1048
- }
1049
- const toString = value.toString;
1050
- if (typeof toString === 'function') {
1051
- return toString.call(value);
1052
- }
1053
- }
1054
- else {
1055
- const toString = value.toString;
1056
- if (typeof toString === 'function') {
1057
- const result = toString.call(value);
1058
- if (typeof result === 'string')
1059
- return result;
1060
- }
1061
- const valueOf = value.valueOf;
1062
- if (typeof valueOf === 'function') {
1063
- const result = valueOf.call(value);
1064
- if (typeof result !== 'object')
1065
- return result;
1066
- }
1067
- }
1068
- }
1069
- return String(value);
1070
- };
1071
- /**
1072
- * Safely evaluates binary operations with proper type coercion
1073
- */
1074
- const evaluateBinaryOperation = (operator, left, right) => {
1075
- switch (operator) {
1076
- case '+': {
1077
- // Handle string concatenation and numeric addition according to JavaScript rules
1078
- const leftPrim = toPrimitive(left);
1079
- const rightPrim = toPrimitive(right);
1080
- if (typeof leftPrim === 'string' || typeof rightPrim === 'string') {
1081
- return String(leftPrim) + String(rightPrim);
1082
- }
1083
- return Number(leftPrim) + Number(rightPrim);
1084
- }
1085
- case '-':
1086
- return Number(toPrimitive(left, 'number')) - Number(toPrimitive(right, 'number'));
1087
- case '*':
1088
- return Number(toPrimitive(left, 'number')) * Number(toPrimitive(right, 'number'));
1089
- case '/':
1090
- return Number(toPrimitive(left, 'number')) / Number(toPrimitive(right, 'number'));
1091
- case '%':
1092
- return Number(toPrimitive(left, 'number')) % Number(toPrimitive(right, 'number'));
1093
- case '**':
1094
- return Number(toPrimitive(left, 'number')) ** Number(toPrimitive(right, 'number'));
1095
- // Bitwise operations - convert to 32-bit integers
1096
- case '<<':
1097
- return (Number(toPrimitive(left, 'number')) | 0) << (Number(toPrimitive(right, 'number')) | 0);
1098
- case '>>':
1099
- return (Number(toPrimitive(left, 'number')) | 0) >> (Number(toPrimitive(right, 'number')) | 0);
1100
- case '>>>':
1101
- return (Number(toPrimitive(left, 'number')) >>> 0) >>> (Number(toPrimitive(right, 'number')) | 0);
1102
- case '&':
1103
- return (Number(toPrimitive(left, 'number')) | 0) & (Number(toPrimitive(right, 'number')) | 0);
1104
- case '^':
1105
- return (Number(toPrimitive(left, 'number')) | 0) ^ (Number(toPrimitive(right, 'number')) | 0);
1106
- case '|':
1107
- return (Number(toPrimitive(left, 'number')) | 0) | (Number(toPrimitive(right, 'number')) | 0);
1108
- // Comparison operations - follow JavaScript's abstract comparison rules
1109
- case '==':
1110
- return left == right;
1111
- case '!=':
1112
- return left != right;
1113
- case '===':
1114
- return left === right;
1115
- case '!==':
1116
- return left !== right;
1117
- case '<': {
1118
- const leftComp = toPrimitive(left, 'number');
1119
- const rightComp = toPrimitive(right, 'number');
1120
- // If both are strings, do string comparison
1121
- if (typeof leftComp === 'string' && typeof rightComp === 'string') {
1122
- return leftComp < rightComp;
1123
- }
1124
- return Number(leftComp) < Number(rightComp);
1125
- }
1126
- case '<=': {
1127
- const leftLE = toPrimitive(left, 'number');
1128
- const rightLE = toPrimitive(right, 'number');
1129
- if (typeof leftLE === 'string' && typeof rightLE === 'string') {
1130
- return leftLE <= rightLE;
1131
- }
1132
- return Number(leftLE) <= Number(rightLE);
1133
- }
1134
- case '>': {
1135
- const leftGT = toPrimitive(left, 'number');
1136
- const rightGT = toPrimitive(right, 'number');
1137
- if (typeof leftGT === 'string' && typeof rightGT === 'string') {
1138
- return leftGT > rightGT;
1139
- }
1140
- return Number(leftGT) > Number(rightGT);
1141
- }
1142
- case '>=': {
1143
- const leftGE = toPrimitive(left, 'number');
1144
- const rightGE = toPrimitive(right, 'number');
1145
- if (typeof leftGE === 'string' && typeof rightGE === 'string') {
1146
- return leftGE >= rightGE;
1147
- }
1148
- return Number(leftGE) >= Number(rightGE);
1149
- }
1150
- // Special operations
1151
- case 'in': {
1152
- if (typeof left === 'string' || typeof left === 'number' || typeof left === 'symbol') {
1153
- if (right == null) {
1154
- throw new Error(`Cannot use 'in' operator with null or undefined right operand`);
1155
- }
1156
- return left in right;
1157
- }
1158
- throw new Error(`Invalid left operand for 'in' operator: ${typeof left}`);
1159
- }
1160
- case 'instanceof': {
1161
- if (typeof right === 'function') {
1162
- return left instanceof right;
1163
- }
1164
- throw new Error(`Right operand of 'instanceof' is not a constructor`);
1165
- }
1166
- case '??':
1167
- return left ?? right;
1168
- default:
1169
- throw new Error(`Unsupported binary operator: ${operator}`);
844
+ const getValueIgnoreCase = (obj, key) => {
845
+ const pair = getKeyValue(obj, key, true);
846
+ if (pair) {
847
+ return pair[1];
1170
848
  }
1171
- };
1172
- /**
1173
- * Safely evaluates binary expressions with proper type handling
1174
- */
1175
- const binaryExpressionVisitor = (node, st, callback) => {
1176
- beforeVisitor(node, st);
1177
- // Disable visitor result caching for now due to context sensitivity issues
1178
- // const cachedResult = getCachedVisitorResult(node, st.context);
1179
- // if (cachedResult !== undefined) {
1180
- // pushVisitorResult(node, st, cachedResult);
1181
- // afterVisitor(node, st);
1182
- // return;
1183
- // }
1184
- callback(node.left, st);
1185
- const left = popVisitorResult(node, st);
1186
- callback(node.right, st);
1187
- const right = popVisitorResult(node, st);
1188
- const value = evaluateBinaryOperation(node.operator, left, right);
1189
- // Disable visitor result caching for now
1190
- // setCachedVisitorResult(node, st.context, value);
1191
- pushVisitorResult(node, st, value);
1192
- afterVisitor(node, st);
849
+ return undefined;
1193
850
  };
1194
851
 
1195
852
  /**
@@ -1238,6 +895,14 @@ const DANGEROUS_PRIMITIVE_PROPERTY_NAMES = new Set([
1238
895
  '__lookupGetter__',
1239
896
  '__lookupSetter__'
1240
897
  ]);
898
+ /**
899
+ * DANGEROUS_PROPERTY_NAMES lower-cased, for {@link mayMatchDangerousProperty}.
900
+ */
901
+ const LOWERED_DANGEROUS_PROPERTY_NAMES = new Set(Array.from(DANGEROUS_PROPERTY_NAMES, (name) => name.toLowerCase()));
902
+ /**
903
+ * Any UTF-16 code unit outside ASCII, for {@link mayMatchDangerousProperty}.
904
+ */
905
+ const NON_ASCII = /[\u0080-￿]/;
1241
906
  /**
1242
907
  * Set of constructor names that should be blocked from modification
1243
908
  */
@@ -1275,6 +940,25 @@ const isDangerousPrimitiveProperty = (key) => {
1275
940
  }
1276
941
  return false;
1277
942
  };
943
+ /**
944
+ * Whether a name, matched against a context under `caseInsensitive`, could
945
+ * match a key in DANGEROUS_PROPERTY_NAMES: the cheap filter ahead of
946
+ * `EvalContext.getKey`, which says which key it did match. False means it
947
+ * cannot, so an identifier pays for `getKey` only when it is near a dangerous
948
+ * name.
949
+ *
950
+ * A context matches another spelling in two ways. A case-insensitive
951
+ * `Registry`, and an `eval-signals` source, compare `toLowerCase()` forms, so
952
+ * a name can match a dangerous key only if its own lower-case form is one. A
953
+ * prior scope's namespace is compared by `localeCompare` at base sensitivity,
954
+ * which ignores accents as well as case: on ASCII identifier characters that
955
+ * is the same comparison, but a name with any other character may match a
956
+ * dangerous key - `cönstructor` matches `constructor` - so such a name always
957
+ * answers true.
958
+ * @param name The name as written
959
+ * @returns false if the name cannot match a dangerous key, true otherwise
960
+ */
961
+ const mayMatchDangerousProperty = (name) => NON_ASCII.test(name) || LOWERED_DANGEROUS_PROPERTY_NAMES.has(name.toLowerCase());
1278
962
  /**
1279
963
  * Checks if an object is a dangerous constructor that shouldn't be modified
1280
964
  * @param obj The object to check
@@ -1385,39 +1069,346 @@ const createSafeObject = (entries = []) => {
1385
1069
  if (isDangerousProperty(key)) {
1386
1070
  throw new Error(`Cannot create object with dangerous property "${String(key)}"`);
1387
1071
  }
1388
- // Safely set the property
1389
- if (typeof key === 'string' || typeof key === 'number') {
1390
- obj[key] = value;
1072
+ // Safely set the property
1073
+ if (typeof key === 'string' || typeof key === 'number') {
1074
+ obj[key] = value;
1075
+ }
1076
+ else if (typeof key === 'symbol') {
1077
+ obj[key] = value;
1078
+ }
1079
+ }
1080
+ return obj;
1081
+ };
1082
+ /**
1083
+ * Validates that an object is safe from prototype pollution
1084
+ * @param obj The object to validate
1085
+ * @throws Error if the object contains dangerous properties
1086
+ */
1087
+ const validateSafeObject = (obj) => {
1088
+ if (!obj || typeof obj !== 'object') {
1089
+ return;
1090
+ }
1091
+ const keys = Object.getOwnPropertyNames(obj);
1092
+ for (const key of keys) {
1093
+ if (isDangerousProperty(key)) {
1094
+ throw new Error(`Object contains dangerous property "${key}" that could lead to prototype pollution`);
1095
+ }
1096
+ }
1097
+ // Also check symbol properties
1098
+ const symbols = Object.getOwnPropertySymbols(obj);
1099
+ for (const symbol of symbols) {
1100
+ const description = symbol.description;
1101
+ if (description && isDangerousProperty(description)) {
1102
+ throw new Error(`Object contains dangerous symbol property "${description}" that could lead to prototype pollution`);
1103
+ }
1104
+ }
1105
+ };
1106
+
1107
+ const literals = Registry.fromObject({
1108
+ 'undefined': undefined,
1109
+ 'null': null,
1110
+ 'true': true,
1111
+ 'false': false,
1112
+ }, { caseInsensitive: true });
1113
+ /**
1114
+ * Reports a resolved identifier read to the hook layer.
1115
+ *
1116
+ * The key is the one the context actually matched, so a case-insensitive
1117
+ * lookup reports the corrected spelling; `getKey` returns undefined for a name
1118
+ * the context does not hold - a literal-registry resolution, or a miss - and
1119
+ * the source name stands in. The path is always the source spelling, since it
1120
+ * is reconstructed statically.
1121
+ *
1122
+ * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
1123
+ * an arrow-function parameter. It is asked of `EvalContext.hasInScopes`, which
1124
+ * tests for the binding rather than for its value: a parameter bound to
1125
+ * `undefined` is still a parameter, and reading the flag off the resolved value
1126
+ * would make it vary with the data rather than with the expression.
1127
+ *
1128
+ * It is deliberately *not* set for `priorScopes`: those hold caller-registered,
1129
+ * long-lived objects and are real dependencies, so the discriminator is
1130
+ * lifetime rather than `instanceof EvalScope`. The property is omitted rather
1131
+ * than set to false, so absent reads as "not scoped" the same way it does at
1132
+ * the member emission sites.
1133
+ *
1134
+ * The scope stack is empty for any expression without an arrow function, and
1135
+ * `Stack.asArray` allocates, so the common case is short-circuited on length.
1136
+ */
1137
+ const emitRead = (node, st, value) => {
1138
+ const key = st.context?.getKey(node.name) ?? node.name;
1139
+ const scoped = !!st.context
1140
+ && st.context.scopes.length > 0
1141
+ && st.context.hasInScopes(node.name);
1142
+ st.hooks.dispatchRead({
1143
+ kind: 'identifier',
1144
+ node,
1145
+ state: st,
1146
+ key,
1147
+ target: st.context,
1148
+ path: node.name,
1149
+ value,
1150
+ ...(scoped ? { scoped: true } : {})
1151
+ });
1152
+ };
1153
+ /**
1154
+ * Refuses an identifier whose name is on the prototype-pollution blocklist,
1155
+ * before any lookup, with the member visitor's error.
1156
+ *
1157
+ * An identifier is resolved against the context, and `EvalContext.get` reads a
1158
+ * plain object there - the original, or a scope - with a bare property access.
1159
+ * So up to 0.10.x a name on the blocklist resolved to what the context inherits
1160
+ * from `Object.prototype` (`docs/backlog-retired.md` B6): the blocklist guarded
1161
+ * member access to the objects an expression holds, and the context is not one
1162
+ * of them. Every kind of context is refused alike, including those - a
1163
+ * `Registry`, a signal context's source - that hold such a name only as a key
1164
+ * of their own.
1165
+ */
1166
+ const refuseDangerousName = (node) => {
1167
+ if (isDangerousProperty(node.name)) {
1168
+ throw new Error(`Access to dangerous property "${node.name}" is blocked for security reasons`);
1169
+ }
1170
+ };
1171
+ /**
1172
+ * Under `caseInsensitive`, refuses an identifier whose lookup matched a key on
1173
+ * the blocklist - `CONSTRUCTOR` over a context holding `constructor` - as the
1174
+ * member visitor re-checks `foundKey` for another object.
1175
+ *
1176
+ * The matched key is asked of `getKey`, which answers the key `get` resolves,
1177
+ * and only for a name `mayMatchDangerousProperty` lets through. Any other name
1178
+ * cannot match a blocklisted key, and an identifier must not pay a second
1179
+ * resolution for nothing: the performance spec's read-emission guard asserts
1180
+ * that, with no read hook, `getKey` is not called per identifier.
1181
+ */
1182
+ const refuseDangerousMatch = (node, st) => {
1183
+ if (!st.context || !mayMatchDangerousProperty(node.name)) {
1184
+ return;
1185
+ }
1186
+ const matched = st.context.getKey(node.name);
1187
+ if (isDangerousProperty(matched)) {
1188
+ throw new Error(`Access to dangerous property "${String(matched)}" is blocked for security reasons`);
1189
+ }
1190
+ };
1191
+ const identifierVisitor = (node, st) => {
1192
+ if (st.options?.caseInsensitive) {
1193
+ return identifierVisitorCaseInsensitive(node, st);
1194
+ }
1195
+ beforeVisitor(node, st);
1196
+ refuseDangerousName(node);
1197
+ const context = st.context;
1198
+ const isThis = node.name === 'this';
1199
+ const value = isThis
1200
+ ? st.context
1201
+ : context?.get(node.name);
1202
+ // `this` resolves to the context object itself rather than to a key within
1203
+ // it, so it is not a read: reporting it would have a dependency tracker
1204
+ // record the whole context and re-fire on every change to it.
1205
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
1206
+ emitRead(node, st, value);
1207
+ }
1208
+ pushVisitorResult(node, st, value);
1209
+ afterVisitor(node, st);
1210
+ };
1211
+ const identifierVisitorCaseInsensitive = (node, st) => {
1212
+ beforeVisitor(node, st);
1213
+ refuseDangerousName(node);
1214
+ const context = st.context;
1215
+ const isThis = !!equalIgnoreCase(node.name, 'this');
1216
+ if (!isThis) {
1217
+ refuseDangerousMatch(node, st);
1218
+ }
1219
+ const value = isThis
1220
+ ? st.context
1221
+ : context?.get(node.name) ?? literals.get(node.name);
1222
+ if (st.hasHooks && st.hooks.hasReadHooks && !isThis) {
1223
+ emitRead(node, st, value);
1224
+ }
1225
+ pushVisitorResult(node, st, value);
1226
+ afterVisitor(node, st);
1227
+ };
1228
+
1229
+ const literalVisitor = (node, st) => {
1230
+ beforeVisitor(node, st);
1231
+ // A regex literal is a new `RegExp` on every evaluation, as it is in
1232
+ // JavaScript. Acorn builds `node.value` once, at parse time, and every walk of
1233
+ // the parsed tree used to push that one object - a cached `simpleEval` string
1234
+ // and each recompute of a compiled expression alike - so `lastIndex` carried
1235
+ // from one evaluation into the next, and `/a/g.test("a")` answered true, then
1236
+ // false. A copy starts at `lastIndex` 0, and being new it is recorded under a
1237
+ // member-write policy, as a literal is - `EvalContext.checkMemberWrite`. When
1238
+ // acorn could not build the regex in this environment, `value` is null and is
1239
+ // pushed as before.
1240
+ let value = node.value;
1241
+ if (value instanceof RegExp) {
1242
+ value = new RegExp(value);
1243
+ st.createdObjects?.add(value);
1244
+ }
1245
+ pushVisitorResult(node, st, value);
1246
+ afterVisitor(node, st);
1247
+ };
1248
+
1249
+ // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
1250
+ /**
1251
+ * Converts value to primitive for comparison operations
1252
+ */
1253
+ const toPrimitive = (value, hint) => {
1254
+ if (value === null || value === undefined)
1255
+ return value;
1256
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||
1257
+ typeof value === 'symbol' || typeof value === 'bigint')
1258
+ return value;
1259
+ // For objects, call valueOf/toString based on hint
1260
+ if (typeof value === 'object') {
1261
+ if (hint === 'number') {
1262
+ const valueOf = value.valueOf;
1263
+ if (typeof valueOf === 'function') {
1264
+ const result = valueOf.call(value);
1265
+ if (typeof result !== 'object')
1266
+ return result;
1267
+ }
1268
+ const toString = value.toString;
1269
+ if (typeof toString === 'function') {
1270
+ return toString.call(value);
1271
+ }
1272
+ }
1273
+ else {
1274
+ const toString = value.toString;
1275
+ if (typeof toString === 'function') {
1276
+ const result = toString.call(value);
1277
+ if (typeof result === 'string')
1278
+ return result;
1279
+ }
1280
+ const valueOf = value.valueOf;
1281
+ if (typeof valueOf === 'function') {
1282
+ const result = valueOf.call(value);
1283
+ if (typeof result !== 'object')
1284
+ return result;
1285
+ }
1286
+ }
1287
+ }
1288
+ return String(value);
1289
+ };
1290
+ /**
1291
+ * Safely evaluates binary operations with proper type coercion
1292
+ */
1293
+ const evaluateBinaryOperation = (operator, left, right) => {
1294
+ switch (operator) {
1295
+ case '+': {
1296
+ // Handle string concatenation and numeric addition according to JavaScript rules
1297
+ const leftPrim = toPrimitive(left);
1298
+ const rightPrim = toPrimitive(right);
1299
+ if (typeof leftPrim === 'string' || typeof rightPrim === 'string') {
1300
+ return String(leftPrim) + String(rightPrim);
1301
+ }
1302
+ return Number(leftPrim) + Number(rightPrim);
1303
+ }
1304
+ case '-':
1305
+ return Number(toPrimitive(left, 'number')) - Number(toPrimitive(right, 'number'));
1306
+ case '*':
1307
+ return Number(toPrimitive(left, 'number')) * Number(toPrimitive(right, 'number'));
1308
+ case '/':
1309
+ return Number(toPrimitive(left, 'number')) / Number(toPrimitive(right, 'number'));
1310
+ case '%':
1311
+ return Number(toPrimitive(left, 'number')) % Number(toPrimitive(right, 'number'));
1312
+ case '**':
1313
+ return Number(toPrimitive(left, 'number')) ** Number(toPrimitive(right, 'number'));
1314
+ // Bitwise operations - convert to 32-bit integers
1315
+ case '<<':
1316
+ return (Number(toPrimitive(left, 'number')) | 0) << (Number(toPrimitive(right, 'number')) | 0);
1317
+ case '>>':
1318
+ return (Number(toPrimitive(left, 'number')) | 0) >> (Number(toPrimitive(right, 'number')) | 0);
1319
+ case '>>>':
1320
+ return (Number(toPrimitive(left, 'number')) >>> 0) >>> (Number(toPrimitive(right, 'number')) | 0);
1321
+ case '&':
1322
+ return (Number(toPrimitive(left, 'number')) | 0) & (Number(toPrimitive(right, 'number')) | 0);
1323
+ case '^':
1324
+ return (Number(toPrimitive(left, 'number')) | 0) ^ (Number(toPrimitive(right, 'number')) | 0);
1325
+ case '|':
1326
+ return (Number(toPrimitive(left, 'number')) | 0) | (Number(toPrimitive(right, 'number')) | 0);
1327
+ // Comparison operations - follow JavaScript's abstract comparison rules
1328
+ case '==':
1329
+ return left == right;
1330
+ case '!=':
1331
+ return left != right;
1332
+ case '===':
1333
+ return left === right;
1334
+ case '!==':
1335
+ return left !== right;
1336
+ case '<': {
1337
+ const leftComp = toPrimitive(left, 'number');
1338
+ const rightComp = toPrimitive(right, 'number');
1339
+ // If both are strings, do string comparison
1340
+ if (typeof leftComp === 'string' && typeof rightComp === 'string') {
1341
+ return leftComp < rightComp;
1342
+ }
1343
+ return Number(leftComp) < Number(rightComp);
1344
+ }
1345
+ case '<=': {
1346
+ const leftLE = toPrimitive(left, 'number');
1347
+ const rightLE = toPrimitive(right, 'number');
1348
+ if (typeof leftLE === 'string' && typeof rightLE === 'string') {
1349
+ return leftLE <= rightLE;
1350
+ }
1351
+ return Number(leftLE) <= Number(rightLE);
1391
1352
  }
1392
- else if (typeof key === 'symbol') {
1393
- obj[key] = value;
1353
+ case '>': {
1354
+ const leftGT = toPrimitive(left, 'number');
1355
+ const rightGT = toPrimitive(right, 'number');
1356
+ if (typeof leftGT === 'string' && typeof rightGT === 'string') {
1357
+ return leftGT > rightGT;
1358
+ }
1359
+ return Number(leftGT) > Number(rightGT);
1360
+ }
1361
+ case '>=': {
1362
+ const leftGE = toPrimitive(left, 'number');
1363
+ const rightGE = toPrimitive(right, 'number');
1364
+ if (typeof leftGE === 'string' && typeof rightGE === 'string') {
1365
+ return leftGE >= rightGE;
1366
+ }
1367
+ return Number(leftGE) >= Number(rightGE);
1368
+ }
1369
+ // Special operations
1370
+ case 'in': {
1371
+ if (typeof left === 'string' || typeof left === 'number' || typeof left === 'symbol') {
1372
+ if (right == null) {
1373
+ throw new Error(`Cannot use 'in' operator with null or undefined right operand`);
1374
+ }
1375
+ return left in right;
1376
+ }
1377
+ throw new Error(`Invalid left operand for 'in' operator: ${typeof left}`);
1378
+ }
1379
+ case 'instanceof': {
1380
+ if (typeof right === 'function') {
1381
+ return left instanceof right;
1382
+ }
1383
+ throw new Error(`Right operand of 'instanceof' is not a constructor`);
1394
1384
  }
1385
+ case '??':
1386
+ return left ?? right;
1387
+ default:
1388
+ throw new Error(`Unsupported binary operator: ${operator}`);
1395
1389
  }
1396
- return obj;
1397
1390
  };
1398
1391
  /**
1399
- * Validates that an object is safe from prototype pollution
1400
- * @param obj The object to validate
1401
- * @throws Error if the object contains dangerous properties
1392
+ * Safely evaluates binary expressions with proper type handling
1402
1393
  */
1403
- const validateSafeObject = (obj) => {
1404
- if (!obj || typeof obj !== 'object') {
1405
- return;
1406
- }
1407
- const keys = Object.getOwnPropertyNames(obj);
1408
- for (const key of keys) {
1409
- if (isDangerousProperty(key)) {
1410
- throw new Error(`Object contains dangerous property "${key}" that could lead to prototype pollution`);
1411
- }
1412
- }
1413
- // Also check symbol properties
1414
- const symbols = Object.getOwnPropertySymbols(obj);
1415
- for (const symbol of symbols) {
1416
- const description = symbol.description;
1417
- if (description && isDangerousProperty(description)) {
1418
- throw new Error(`Object contains dangerous symbol property "${description}" that could lead to prototype pollution`);
1419
- }
1420
- }
1394
+ const binaryExpressionVisitor = (node, st, callback) => {
1395
+ beforeVisitor(node, st);
1396
+ // Disable visitor result caching for now due to context sensitivity issues
1397
+ // const cachedResult = getCachedVisitorResult(node, st.context);
1398
+ // if (cachedResult !== undefined) {
1399
+ // pushVisitorResult(node, st, cachedResult);
1400
+ // afterVisitor(node, st);
1401
+ // return;
1402
+ // }
1403
+ callback(node.left, st);
1404
+ const left = popVisitorResult(node, st);
1405
+ callback(node.right, st);
1406
+ const right = popVisitorResult(node, st);
1407
+ const value = evaluateBinaryOperation(node.operator, left, right);
1408
+ // Disable visitor result caching for now
1409
+ // setCachedVisitorResult(node, st.context, value);
1410
+ pushVisitorResult(node, st, value);
1411
+ afterVisitor(node, st);
1421
1412
  };
1422
1413
 
1423
1414
  /**
@@ -1633,10 +1624,22 @@ const evaluateMember = (node, st, callback) => {
1633
1624
  }
1634
1625
  // Get the value with context-aware or prototype pollution protection
1635
1626
  if (object === st.context) {
1627
+ // `this.k` resolves `k` against the context, as an identifier does, so it
1628
+ // is refused as one is (`identifier.ts`, `docs/backlog-retired.md` B6): a
1629
+ // blocklisted key before the lookup, and under `caseInsensitive` a
1630
+ // blocklisted key the lookup matched. Up to 0.10.x neither was checked,
1631
+ // and `this.constructor` over a plain object was `Object`.
1632
+ if (isDangerousProperty(key)) {
1633
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1634
+ }
1636
1635
  // For context objects, preserve case-insensitive behavior
1637
- const contextKey = st.options?.caseInsensitive && typeof key === 'string'
1638
- ? st.context.getKey(key)
1639
- : key;
1636
+ let contextKey = key;
1637
+ if (st.options?.caseInsensitive && typeof key === 'string') {
1638
+ contextKey = st.context.getKey(key);
1639
+ if (isDangerousProperty(contextKey)) {
1640
+ throw new Error(`Access to dangerous property "${String(contextKey)}" is blocked for security reasons`);
1641
+ }
1642
+ }
1640
1643
  const value = st.context.get(contextKey);
1641
1644
  const thisValue = st.context.getThis(contextKey);
1642
1645
  if (st.hasHooks && st.hooks.hasReadHooks) {
@@ -1653,6 +1656,11 @@ const evaluateMember = (node, st, callback) => {
1653
1656
  return [thisValue ?? object, contextKey, value];
1654
1657
  }
1655
1658
  else if (object instanceof EvalScope) {
1659
+ // A global scope reads its object as the context does, with a bare
1660
+ // property access, so a blocklisted key is refused here as it is above.
1661
+ if (isDangerousProperty(key)) {
1662
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1663
+ }
1656
1664
  // For scope objects, preserve original behavior (no getKey method)
1657
1665
  const value = object.get(key);
1658
1666
  const thisValue = object;
@@ -1814,6 +1822,146 @@ const evaluateArray = (node, items, st, callback) => {
1814
1822
  return elements;
1815
1823
  };
1816
1824
 
1825
+ /**
1826
+ * Whether `value` can be held in a `WeakSet` - an object or a function.
1827
+ */
1828
+ const isObjectLike = (value) => (typeof value === 'object' && value !== null) || typeof value === 'function';
1829
+ /**
1830
+ * Records `value` as created by the walk, unless it is a primitive.
1831
+ *
1832
+ * For the one recording site whose value may be a primitive: an array or
1833
+ * parameter rest is `args.slice(i)`, which is a string when the destructured
1834
+ * source is one (`let [h, ...t] = "abc"`), and `WeakSet.add` throws on a
1835
+ * primitive. The literal, object-rest and arrow-function sites always create
1836
+ * an object and add directly.
1837
+ *
1838
+ * @param created - `st.createdObjects`, already read and found set by the caller.
1839
+ * @param value - The value the walk created.
1840
+ */
1841
+ const recordCreated = (created, value) => {
1842
+ if (isObjectLike(value)) {
1843
+ created.add(value);
1844
+ }
1845
+ };
1846
+ /**
1847
+ * Asks the context whether a member write may happen, through
1848
+ * `EvalContext.checkMemberWrite`. A refusal is a throw, and it propagates from
1849
+ * here unchanged: nothing has been written yet.
1850
+ *
1851
+ * Called by the member branches of `assignment-expression.ts` and
1852
+ * `update-expression.ts`, immediately before `safeSetProperty`, and only after
1853
+ * the caller has read `st.createdObjects` and found it set. That read is the
1854
+ * whole of the default path's cost: a state whose context has no policy holds
1855
+ * no set, so neither visitor reaches this call.
1856
+ *
1857
+ * @param st - The state of the walk making the write.
1858
+ * @param created - `st.createdObjects`, already read by the caller.
1859
+ * @param target - The object about to receive the write.
1860
+ * @param key - The property about to be written.
1861
+ */
1862
+ const consultMemberWrite = (st, created, target, key) => {
1863
+ st.context?.checkMemberWrite?.({
1864
+ target,
1865
+ key,
1866
+ createdByEvaluation: isObjectLike(target) && created.has(target),
1867
+ });
1868
+ };
1869
+ /**
1870
+ * The built-ins that write into their receiver or their first argument, keyed
1871
+ * by the function itself. Identity is the point: a method of the caller's own
1872
+ * named `push` is not one of these, and `Array.prototype.push` reached under
1873
+ * another name is.
1874
+ *
1875
+ * Read through property descriptors, since `%TypedArray%.prototype` carries
1876
+ * getters that throw when read off the prototype itself. Built once, from this
1877
+ * realm's built-ins: an array made in another realm - an iframe - holds that
1878
+ * realm's `push`, which is not in here.
1879
+ */
1880
+ const MUTATING_BUILT_INS = (() => {
1881
+ const table = new Map();
1882
+ const add = (owner, ownerName, names, writes) => {
1883
+ for (const name of names) {
1884
+ const fn = Object.getOwnPropertyDescriptor(owner, name)?.value;
1885
+ if (typeof fn === 'function') {
1886
+ table.set(fn, { name: `${ownerName}.${name}`, writes });
1887
+ }
1888
+ }
1889
+ };
1890
+ add(Array.prototype, 'Array.prototype', ['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], 'receiver');
1891
+ add(Object.getPrototypeOf(Int8Array.prototype), '%TypedArray%.prototype', ['copyWithin', 'fill', 'reverse', 'set', 'sort'], 'receiver');
1892
+ add(Map.prototype, 'Map.prototype', ['set', 'delete', 'clear'], 'receiver');
1893
+ add(Set.prototype, 'Set.prototype', ['add', 'delete', 'clear'], 'receiver');
1894
+ add(WeakMap.prototype, 'WeakMap.prototype', ['set', 'delete'], 'receiver');
1895
+ add(WeakSet.prototype, 'WeakSet.prototype', ['add', 'delete'], 'receiver');
1896
+ add(Date.prototype, 'Date.prototype', Object.getOwnPropertyNames(Date.prototype).filter((name) => name.startsWith('set')), 'receiver');
1897
+ add(Object, 'Object', ['assign', 'defineProperty', 'defineProperties', 'setPrototypeOf', 'freeze', 'seal', 'preventExtensions'], 'first argument');
1898
+ return table;
1899
+ })();
1900
+ /**
1901
+ * `Function.prototype`'s three ways to run a function with a `this` the
1902
+ * caller chooses. Read once, from this realm, as the table above is.
1903
+ */
1904
+ const FUNCTION_CALL = Function.prototype.call;
1905
+ const FUNCTION_APPLY = Function.prototype.apply;
1906
+ const FUNCTION_BIND = Function.prototype.bind;
1907
+ /**
1908
+ * The arguments `Function.prototype.apply` passes on: its second argument, read
1909
+ * as an array-like, as `apply` reads it. Nothing for anything else - `apply`
1910
+ * passes none for `null` or `undefined`, and throws for a primitive.
1911
+ */
1912
+ const argumentsOf = (list) => isObjectLike(list) ? Array.prototype.slice.call(list) : [];
1913
+ /**
1914
+ * Asks the context whether a call may run, when the function is a built-in
1915
+ * that writes into an object it is handed, through
1916
+ * `EvalContext.checkMemberWrite` with `method` naming it. Any other function is
1917
+ * not asked about. A refusal is a throw, and it propagates from here
1918
+ * unchanged: the call has not been made.
1919
+ *
1920
+ * Reached through `Function.prototype.call`, `apply` or `bind`, the function
1921
+ * the visitor calls is one of those three and not the built-in, so it is asked
1922
+ * about as a direct call of the function they run: its receiver is the `this`
1923
+ * they pass, and its arguments are the rest, or `apply`'s list. Followed
1924
+ * through `call.call`, `call.apply` and the like, since each hop is one more of
1925
+ * the three. `bind` makes a new function, which no table could recognise when
1926
+ * it is called later, so it is asked at bind time, about the bound `this` and
1927
+ * arguments: binding a built-in to an object the walk did not create is
1928
+ * refused before the bound function exists (`docs/backlog-retired.md` C5).
1929
+ *
1930
+ * Called by `call-expression.ts` immediately before the call, and only after
1931
+ * it has read `st.createdObjects` and found it set, as for a member write.
1932
+ *
1933
+ * @param st - The state of the walk making the call.
1934
+ * @param created - `st.createdObjects`, already read by the caller.
1935
+ * @param fn - The function about to be called.
1936
+ * @param receiver - The `this` it is about to be called with.
1937
+ * @param args - The arguments it is about to be called with.
1938
+ */
1939
+ const consultMethodWrite = (st, created, fn, receiver, args) => {
1940
+ if (fn === FUNCTION_CALL) {
1941
+ consultMethodWrite(st, created, receiver, args[0], args.slice(1));
1942
+ return;
1943
+ }
1944
+ if (fn === FUNCTION_APPLY) {
1945
+ consultMethodWrite(st, created, receiver, args[0], argumentsOf(args[1]));
1946
+ return;
1947
+ }
1948
+ if (fn === FUNCTION_BIND) {
1949
+ consultMethodWrite(st, created, receiver, args[0], args.slice(1));
1950
+ return;
1951
+ }
1952
+ const builtIn = MUTATING_BUILT_INS.get(fn);
1953
+ if (!builtIn) {
1954
+ return;
1955
+ }
1956
+ const target = builtIn.writes === 'receiver' ? receiver : args[0];
1957
+ st.context?.checkMemberWrite?.({
1958
+ target,
1959
+ key: undefined,
1960
+ createdByEvaluation: isObjectLike(target) && created.has(target),
1961
+ method: builtIn.name,
1962
+ });
1963
+ };
1964
+
1817
1965
  /**
1818
1966
  * Security: List of dangerous functions that should not be callable
1819
1967
  */
@@ -1948,6 +2096,12 @@ const scopeReceiver = (st, object) => {
1948
2096
  };
1949
2097
  /**
1950
2098
  * Enhanced call expression visitor with security checks
2099
+ *
2100
+ * A context with a member-write policy is asked, before the call, about a
2101
+ * built-in that writes into its receiver or its first argument - see
2102
+ * `consultMethodWrite`. The receiver asked about is the one the call is made
2103
+ * with: the member's object, a prior scope's `thisArg`, or the context itself
2104
+ * for a bare call. A context without a policy pays one field read per call.
1951
2105
  */
1952
2106
  const callExpressionVisitor = (node, st, callback) => {
1953
2107
  beforeVisitor(node, st);
@@ -1955,7 +2109,12 @@ const callExpressionVisitor = (node, st, callback) => {
1955
2109
  if (node.callee.type === 'MemberExpression') {
1956
2110
  const [object, propertyName, fn] = evaluateMember(node.callee, st, callback);
1957
2111
  const functionName = typeof propertyName === 'string' ? propertyName : undefined;
1958
- const value = safeCall(fn, scopeReceiver(st, object), args, node.callee.optional, functionName);
2112
+ const receiver = scopeReceiver(st, object);
2113
+ const created = st.createdObjects;
2114
+ if (created) {
2115
+ consultMethodWrite(st, created, fn, receiver, args);
2116
+ }
2117
+ const value = safeCall(fn, receiver, args, node.callee.optional, functionName);
1959
2118
  pushVisitorResult(node, st, value);
1960
2119
  }
1961
2120
  else {
@@ -1966,6 +2125,10 @@ const callExpressionVisitor = (node, st, callback) => {
1966
2125
  if (node.callee.type === 'Identifier') {
1967
2126
  functionName = node.callee.name;
1968
2127
  }
2128
+ const created = st.createdObjects;
2129
+ if (created) {
2130
+ consultMethodWrite(st, created, caller, st.context, args);
2131
+ }
1969
2132
  const value = safeCall(caller, st.context, args, node.optional, functionName);
1970
2133
  pushVisitorResult(node, st, value);
1971
2134
  }
@@ -2366,51 +2529,6 @@ const getDefaultVisitors = () => {
2366
2529
  return visitors;
2367
2530
  };
2368
2531
 
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
-
2414
2532
  // based on evalArrowContext
2415
2533
  // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
2416
2534
  /**
@@ -3788,9 +3906,8 @@ class EvalScope {
3788
3906
  * Whether a context holds a key at all, regardless of the value bound to it.
3789
3907
  *
3790
3908
  * There is no `getContextValue` counterpart for this: that helper cannot
3791
- * distinguish an absent key from one bound to `undefined`, and `getContextKey`
3792
- * with `caseInsensitive: false` reports every key as present for a plain
3793
- * object. Own properties only - the scopes this is used on are object literals
3909
+ * distinguish an absent key from one bound to `undefined`. Own properties
3910
+ * only - the scopes this is used on are object literals
3794
3911
  * built by `evaluatePatterns`, and inherited names are not bindings.
3795
3912
  */
3796
3913
  const hasContextKey = (context, key) => {
@@ -6174,5 +6291,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImpor
6174
6291
  * Generated bundle index. Do not edit.
6175
6292
  */
6176
6293
 
6177
- export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, 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 };
6294
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextValue, parse };
6178
6295
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map