@zvenigora/ng-eval-core 0.1.106 → 0.2.1

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.
Files changed (96) hide show
  1. package/fesm2022/zvenigora-ng-eval-core.mjs +1323 -266
  2. package/fesm2022/zvenigora-ng-eval-core.mjs.map +1 -1
  3. package/lib/actual/services/compiler.service.d.ts +31 -4
  4. package/lib/actual/services/eval.service.d.ts +14 -2
  5. package/lib/actual/services/parser.service.d.ts +13 -1
  6. package/lib/internal/classes/common/public-api.d.ts +0 -2
  7. package/lib/internal/classes/common/stack.d.ts +19 -2
  8. package/lib/internal/classes/eval/eval-context.d.ts +2 -2
  9. package/lib/internal/classes/eval/eval-lookup.d.ts +1 -1
  10. package/lib/internal/interfaces/public-api.d.ts +1 -1
  11. package/lib/internal/interfaces/recursive-visitors.d.ts +1 -0
  12. package/lib/internal/interfaces/registry-type.d.ts +0 -6
  13. package/lib/internal/visitors/binary-expression.d.ts +3 -0
  14. package/lib/internal/visitors/call-expression.d.ts +3 -0
  15. package/lib/internal/visitors/import-expression.d.ts +6 -0
  16. package/lib/internal/visitors/new-expression.d.ts +1 -1
  17. package/lib/internal/visitors/property-lookup-cache.d.ts +21 -0
  18. package/lib/internal/visitors/prototype-pollution-guard.d.ts +46 -0
  19. package/lib/internal/visitors/public-api.d.ts +1 -0
  20. package/lib/internal/visitors/utils.d.ts +1 -4
  21. package/package.json +3 -5
  22. package/esm2022/index.mjs +0 -2
  23. package/esm2022/lib/actual/services/base-eval.mjs +0 -50
  24. package/esm2022/lib/actual/services/compiler.service.mjs +0 -168
  25. package/esm2022/lib/actual/services/discovery.service.mjs +0 -56
  26. package/esm2022/lib/actual/services/eval.service.mjs +0 -134
  27. package/esm2022/lib/actual/services/index.mjs +0 -2
  28. package/esm2022/lib/actual/services/parser.service.mjs +0 -101
  29. package/esm2022/lib/actual/services/public-api.mjs +0 -5
  30. package/esm2022/lib/internal/classes/common/base-registry.mjs +0 -128
  31. package/esm2022/lib/internal/classes/common/cache.mjs +0 -132
  32. package/esm2022/lib/internal/classes/common/case-insensitive-registry.mjs +0 -147
  33. package/esm2022/lib/internal/classes/common/context.mjs +0 -94
  34. package/esm2022/lib/internal/classes/common/index.mjs +0 -2
  35. package/esm2022/lib/internal/classes/common/public-api.mjs +0 -10
  36. package/esm2022/lib/internal/classes/common/queue.mjs +0 -42
  37. package/esm2022/lib/internal/classes/common/registry.mjs +0 -119
  38. package/esm2022/lib/internal/classes/common/scope-registry.mjs +0 -116
  39. package/esm2022/lib/internal/classes/common/scope.mjs +0 -55
  40. package/esm2022/lib/internal/classes/common/stack.mjs +0 -59
  41. package/esm2022/lib/internal/classes/eval/eval-context.mjs +0 -201
  42. package/esm2022/lib/internal/classes/eval/eval-lookup.mjs +0 -2
  43. package/esm2022/lib/internal/classes/eval/eval-options.mjs +0 -42
  44. package/esm2022/lib/internal/classes/eval/eval-result.mjs +0 -141
  45. package/esm2022/lib/internal/classes/eval/eval-scope.mjs +0 -83
  46. package/esm2022/lib/internal/classes/eval/eval-state.mjs +0 -59
  47. package/esm2022/lib/internal/classes/eval/eval-trace.mjs +0 -22
  48. package/esm2022/lib/internal/classes/eval/index.mjs +0 -2
  49. package/esm2022/lib/internal/classes/eval/parser-options.mjs +0 -8
  50. package/esm2022/lib/internal/classes/eval/public-api.mjs +0 -7
  51. package/esm2022/lib/internal/functions/compile.mjs +0 -41
  52. package/esm2022/lib/internal/functions/evaluate.mjs +0 -42
  53. package/esm2022/lib/internal/functions/extract.mjs +0 -20
  54. package/esm2022/lib/internal/functions/index.mjs +0 -2
  55. package/esm2022/lib/internal/functions/parse.mjs +0 -31
  56. package/esm2022/lib/internal/functions/public-api.mjs +0 -5
  57. package/esm2022/lib/internal/interfaces/cache-type.mjs +0 -2
  58. package/esm2022/lib/internal/interfaces/index.mjs +0 -2
  59. package/esm2022/lib/internal/interfaces/parser-types.mjs +0 -2
  60. package/esm2022/lib/internal/interfaces/public-api.mjs +0 -3
  61. package/esm2022/lib/internal/interfaces/queue-type.mjs +0 -2
  62. package/esm2022/lib/internal/interfaces/recursive-visitors.mjs +0 -6
  63. package/esm2022/lib/internal/interfaces/registry-type.mjs +0 -2
  64. package/esm2022/lib/internal/interfaces/scope-type.mjs +0 -2
  65. package/esm2022/lib/internal/interfaces/stack-type.mjs +0 -2
  66. package/esm2022/lib/internal/public-api.mjs +0 -3
  67. package/esm2022/lib/internal/visitors/after-visitor.mjs +0 -10
  68. package/esm2022/lib/internal/visitors/array-expression.mjs +0 -29
  69. package/esm2022/lib/internal/visitors/arrow-function-expression.mjs +0 -18
  70. package/esm2022/lib/internal/visitors/assignment-expression.mjs +0 -52
  71. package/esm2022/lib/internal/visitors/await-expression.mjs +0 -14
  72. package/esm2022/lib/internal/visitors/before-visitor.mjs +0 -10
  73. package/esm2022/lib/internal/visitors/binary-expression.mjs +0 -37
  74. package/esm2022/lib/internal/visitors/call-expression.mjs +0 -36
  75. package/esm2022/lib/internal/visitors/conditional-expression.mjs +0 -18
  76. package/esm2022/lib/internal/visitors/identifier.mjs +0 -33
  77. package/esm2022/lib/internal/visitors/index.mjs +0 -2
  78. package/esm2022/lib/internal/visitors/literal.mjs +0 -10
  79. package/esm2022/lib/internal/visitors/logical-expression.mjs +0 -26
  80. package/esm2022/lib/internal/visitors/member-expression.mjs +0 -50
  81. package/esm2022/lib/internal/visitors/new-expression.mjs +0 -21
  82. package/esm2022/lib/internal/visitors/object-expression.mjs +0 -53
  83. package/esm2022/lib/internal/visitors/pattern.mjs +0 -132
  84. package/esm2022/lib/internal/visitors/public-api.mjs +0 -25
  85. package/esm2022/lib/internal/visitors/recursive-visitors.mjs +0 -28
  86. package/esm2022/lib/internal/visitors/tagged-template-expression.mjs +0 -20
  87. package/esm2022/lib/internal/visitors/template-literal.mjs +0 -21
  88. package/esm2022/lib/internal/visitors/this-expression.mjs +0 -10
  89. package/esm2022/lib/internal/visitors/unary-expression.mjs +0 -19
  90. package/esm2022/lib/internal/visitors/update-expression.mjs +0 -32
  91. package/esm2022/lib/internal/visitors/utils.mjs +0 -59
  92. package/esm2022/lib/internal/visitors/visitor-result.mjs +0 -23
  93. package/esm2022/public-api.mjs +0 -6
  94. package/esm2022/zvenigora-ng-eval-core.mjs +0 -5
  95. package/lib/internal/classes/common/scope-registry.d.ts +0 -83
  96. package/lib/internal/classes/common/scope.d.ts +0 -30
@@ -1,7 +1,7 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { Injectable } from '@angular/core';
3
3
  import { sha256 } from 'js-sha256';
4
- import { defaultOptions as defaultOptions$1, parse as parse$1, version } from 'acorn';
4
+ import { defaultOptions, parse as parse$1, version } from 'acorn';
5
5
  import * as walk from 'acorn-walk';
6
6
 
7
7
  /**
@@ -244,7 +244,11 @@ class CaseInsensitiveRegistry {
244
244
  const values = this.registry.values();
245
245
  const entries = new Array;
246
246
  for (let i = 0; i < this.registry.size; i++) {
247
- entries.push([keys.next().value, values.next().value]);
247
+ const keyResult = keys.next();
248
+ const valueResult = values.next();
249
+ if (!keyResult.done && !valueResult.done) {
250
+ entries.push([keyResult.value, valueResult.value]);
251
+ }
248
252
  }
249
253
  return entries.values();
250
254
  }
@@ -396,121 +400,6 @@ class Registry {
396
400
  }
397
401
  }
398
402
 
399
- const defaultOptions = {
400
- caseInsensitive: false,
401
- namespace: '',
402
- global: false,
403
- thisArg: undefined
404
- };
405
- /**
406
- * Represents a registry that stores key-value pairs within a specific scope.
407
- * @template TKey The type of the keys in the registry.
408
- * @template TValue The type of the values in the registry.
409
- */
410
- class ScopeRegistry {
411
- /**
412
- * Creates a new instance of ScopeRegistry.
413
- * @param entries Optional. An array of key-value pairs to initialize the registry.
414
- * @param options Optional. Options for the registry.
415
- */
416
- constructor(entries, options = defaultOptions) {
417
- this.type = 'ScopeRegistry';
418
- /**
419
- * Options for the registry.
420
- */
421
- this.options = defaultOptions;
422
- this.options = { ...defaultOptions, ...options };
423
- this._registry = new Registry(entries, options);
424
- }
425
- /**
426
- * Creates a new ScopeRegistry instance from an object.
427
- * @param object The object containing key-value pairs.
428
- * @param options Optional. Options for the registry.
429
- * @returns A new ScopeRegistry instance.
430
- */
431
- static fromObject(object, options = defaultOptions) {
432
- const registry = Registry.fromObject(object, options);
433
- return registry;
434
- }
435
- /**
436
- * Gets the value associated with the specified key.
437
- * @param key The key to retrieve the value for.
438
- * @returns The value associated with the key, or undefined if the key does not exist.
439
- */
440
- get(key) {
441
- return this._registry.get(key);
442
- }
443
- /**
444
- * Sets the value for the specified key.
445
- * @param key The key to set the value for.
446
- * @param value The value to set.
447
- */
448
- set(key, value) {
449
- this._registry.set(key, value);
450
- }
451
- /**
452
- * Checks if the registry contains the specified key.
453
- * @param key The key to check.
454
- * @returns True if the key exists in the registry, false otherwise.
455
- */
456
- has(key) {
457
- return this._registry.has(key);
458
- }
459
- /**
460
- * Deletes the key-value pair associated with the specified key.
461
- * @param key The key to delete.
462
- * @returns True if the key-value pair was deleted, false if the key does not exist.
463
- */
464
- delete(key) {
465
- return this._registry.delete(key);
466
- }
467
- /**
468
- * Clears all key-value pairs from the registry.
469
- */
470
- clear() {
471
- this._registry.clear();
472
- }
473
- /**
474
- * Gets the number of key-value pairs in the registry.
475
- */
476
- get size() {
477
- return this._registry.size;
478
- }
479
- /**
480
- * Gets an iterator for the keys in the registry.
481
- */
482
- get keys() {
483
- return this._registry.keys;
484
- }
485
- /**
486
- * Gets an iterator for the values in the registry.
487
- */
488
- get values() {
489
- return this._registry.values;
490
- }
491
- /**
492
- * Gets an iterator for the key-value pairs in the registry.
493
- */
494
- get entries() {
495
- return this._registry.entries;
496
- }
497
- /**
498
- * Executes a provided function once for each key-value pair in the registry.
499
- * @param callbackfn The function to execute for each key-value pair.
500
- * @param thisArg Optional. The value to use as `this` when executing the callback function.
501
- */
502
- forEach(callbackfn, thisArg) {
503
- this._registry.forEach(callbackfn, thisArg);
504
- }
505
- /**
506
- * Gets an iterator for the key-value pairs in the registry.
507
- * @returns An iterator for the key-value pairs in the registry.
508
- */
509
- [Symbol.iterator]() {
510
- return this._registry.entries;
511
- }
512
- }
513
-
514
403
  /**
515
404
  * Represents a generic queue data structure.
516
405
  * @template T The type of elements stored in the queue.
@@ -554,7 +443,7 @@ class Queue {
554
443
  }
555
444
 
556
445
  /**
557
- * Represents a stack data structure.
446
+ * Represents a stack data structure with proper memory management.
558
447
  * @template T The type of elements in the stack.
559
448
  */
560
449
  class Stack {
@@ -564,11 +453,21 @@ class Stack {
564
453
  */
565
454
  constructor(_stack = []) {
566
455
  this._stack = _stack;
456
+ this._disposed = false;
457
+ }
458
+ /**
459
+ * Check if the stack has been disposed
460
+ */
461
+ checkDisposed() {
462
+ if (this._disposed) {
463
+ throw new Error('Stack has been disposed and cannot be used');
464
+ }
567
465
  }
568
466
  /**
569
467
  * Gets the number of elements in the stack.
570
468
  */
571
469
  get length() {
470
+ this.checkDisposed();
572
471
  return this._stack.length;
573
472
  }
574
473
  /**
@@ -576,6 +475,7 @@ class Stack {
576
475
  * @returns The top element of the stack.
577
476
  */
578
477
  peek() {
478
+ this.checkDisposed();
579
479
  return this._stack[this._stack.length - 1];
580
480
  }
581
481
  /**
@@ -583,6 +483,7 @@ class Stack {
583
483
  * @returns The top element of the stack, or undefined if the stack is empty.
584
484
  */
585
485
  pop() {
486
+ this.checkDisposed();
586
487
  return this._stack.pop();
587
488
  }
588
489
  /**
@@ -591,12 +492,14 @@ class Stack {
591
492
  * @returns The new length of the stack.
592
493
  */
593
494
  push(value) {
495
+ this.checkDisposed();
594
496
  return this._stack.push(value);
595
497
  }
596
498
  /**
597
499
  * Swaps the positions of the top two elements in the stack.
598
500
  */
599
501
  swap() {
502
+ this.checkDisposed();
600
503
  const length = this._stack.length;
601
504
  const temp = this._stack[length - 1];
602
505
  this._stack[length - 1] = this._stack[length - 2];
@@ -608,62 +511,37 @@ class Stack {
608
511
  * @returns An array containing the elements of the stack in reverse order.
609
512
  */
610
513
  asArray() {
514
+ this.checkDisposed();
611
515
  return [...this._stack].reverse();
612
516
  }
613
- }
614
-
615
- /**
616
- * Represents a scope that holds key-value pairs.
617
- * @template TKey The type of the keys in the scope.
618
- * @template TValue The type of the values in the scope.
619
- */
620
- class Scope {
621
517
  /**
622
- * Gets the registries in the scope.
518
+ * Clears all elements from the stack
623
519
  */
624
- get registries() {
625
- return this._registries;
626
- }
627
- /**
628
- * Creates a new scope.
629
- * @param registries Optional array of registries to initialize the scope with.
630
- */
631
- constructor(registries) {
632
- this._registries = [];
633
- if (registries) {
634
- this._registries = registries;
520
+ clear() {
521
+ this.checkDisposed();
522
+ // Clear all references to help with garbage collection
523
+ if (this._stack) {
524
+ this._stack.length = 0;
635
525
  }
636
526
  }
637
527
  /**
638
- * Adds a registry to the scope.
639
- * @param registry The registry to add.
528
+ * Properly dispose of the stack and clean up memory
640
529
  */
641
- add(registry) {
642
- this._registries.push(registry);
530
+ dispose() {
531
+ if (!this._disposed) {
532
+ this._disposed = true;
533
+ // Clear the stack array and nullify reference
534
+ if (this._stack) {
535
+ this._stack.length = 0;
536
+ this._stack = undefined;
537
+ }
538
+ }
643
539
  }
644
540
  /**
645
- * Gets the value associated with the specified key in the scope.
646
- * @param key The key to search for.
647
- * @param namespace Optional namespace to filter the search by.
648
- * @returns An array containing the key and value if found, otherwise undefined.
541
+ * Check if the stack has been disposed
649
542
  */
650
- get(key, namespace) {
651
- const registries = this._registries.filter((registry) => {
652
- if (registry.options.global) {
653
- return true;
654
- }
655
- if (namespace && registry.options.namespace !== namespace) {
656
- return false;
657
- }
658
- return true;
659
- });
660
- for (const registry of registries) {
661
- if (registry.registry.has(key)) {
662
- const value = registry.registry.get(key);
663
- return [key, value];
664
- }
665
- }
666
- return undefined;
543
+ isDisposed() {
544
+ return this._disposed;
667
545
  }
668
546
  }
669
547
 
@@ -993,7 +871,7 @@ class EvalContext {
993
871
  this._priorScopes = [];
994
872
  this._scopes = new Stack();
995
873
  this._options = options;
996
- this._lookups = new Registry();
874
+ this._lookups = [];
997
875
  }
998
876
  /**
999
877
  * Converts the given context to an instance of EvalContext.
@@ -1032,7 +910,7 @@ class EvalContext {
1032
910
  return value;
1033
911
  }
1034
912
  }
1035
- for (const lookup of Array.from(this._lookups.values)) {
913
+ for (const lookup of this._lookups) {
1036
914
  const value = lookup(key, this, this._options);
1037
915
  if (value !== undefined) {
1038
916
  return value;
@@ -1059,7 +937,7 @@ class EvalContext {
1059
937
  return scope;
1060
938
  }
1061
939
  }
1062
- for (const lookup of Array.from(this._lookups.values)) {
940
+ for (const lookup of this._lookups) {
1063
941
  const value = lookup(key, this, this._options);
1064
942
  if (value !== undefined) {
1065
943
  return lookup;
@@ -1366,7 +1244,7 @@ class EvalState {
1366
1244
  }
1367
1245
 
1368
1246
  const defaultParserOptions = {
1369
- ...defaultOptions$1,
1247
+ ...defaultOptions,
1370
1248
  ecmaVersion: 2020,
1371
1249
  extractExpressions: false,
1372
1250
  cacheSize: 100
@@ -1456,43 +1334,518 @@ const literalVisitor = (node, st) => {
1456
1334
  afterVisitor(node, st);
1457
1335
  };
1458
1336
 
1337
+ // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
1338
+ /**
1339
+ * Converts value to primitive for comparison operations
1340
+ */
1341
+ const toPrimitive = (value, hint) => {
1342
+ if (value === null || value === undefined)
1343
+ return value;
1344
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||
1345
+ typeof value === 'symbol' || typeof value === 'bigint')
1346
+ return value;
1347
+ // For objects, call valueOf/toString based on hint
1348
+ if (typeof value === 'object') {
1349
+ if (hint === 'number') {
1350
+ const valueOf = value.valueOf;
1351
+ if (typeof valueOf === 'function') {
1352
+ const result = valueOf.call(value);
1353
+ if (typeof result !== 'object')
1354
+ return result;
1355
+ }
1356
+ const toString = value.toString;
1357
+ if (typeof toString === 'function') {
1358
+ return toString.call(value);
1359
+ }
1360
+ }
1361
+ else {
1362
+ const toString = value.toString;
1363
+ if (typeof toString === 'function') {
1364
+ const result = toString.call(value);
1365
+ if (typeof result === 'string')
1366
+ return result;
1367
+ }
1368
+ const valueOf = value.valueOf;
1369
+ if (typeof valueOf === 'function') {
1370
+ const result = valueOf.call(value);
1371
+ if (typeof result !== 'object')
1372
+ return result;
1373
+ }
1374
+ }
1375
+ }
1376
+ return String(value);
1377
+ };
1378
+ /**
1379
+ * Safely evaluates binary operations with proper type coercion
1380
+ */
1381
+ const evaluateBinaryOperation = (operator, left, right) => {
1382
+ switch (operator) {
1383
+ case '+': {
1384
+ // Handle string concatenation and numeric addition according to JavaScript rules
1385
+ const leftPrim = toPrimitive(left);
1386
+ const rightPrim = toPrimitive(right);
1387
+ if (typeof leftPrim === 'string' || typeof rightPrim === 'string') {
1388
+ return String(leftPrim) + String(rightPrim);
1389
+ }
1390
+ return Number(leftPrim) + Number(rightPrim);
1391
+ }
1392
+ case '-':
1393
+ return Number(toPrimitive(left, 'number')) - Number(toPrimitive(right, 'number'));
1394
+ case '*':
1395
+ return Number(toPrimitive(left, 'number')) * Number(toPrimitive(right, 'number'));
1396
+ case '/':
1397
+ return Number(toPrimitive(left, 'number')) / Number(toPrimitive(right, 'number'));
1398
+ case '%':
1399
+ return Number(toPrimitive(left, 'number')) % Number(toPrimitive(right, 'number'));
1400
+ case '**':
1401
+ return Number(toPrimitive(left, 'number')) ** Number(toPrimitive(right, 'number'));
1402
+ // Bitwise operations - convert to 32-bit integers
1403
+ case '<<':
1404
+ return (Number(toPrimitive(left, 'number')) | 0) << (Number(toPrimitive(right, 'number')) | 0);
1405
+ case '>>':
1406
+ return (Number(toPrimitive(left, 'number')) | 0) >> (Number(toPrimitive(right, 'number')) | 0);
1407
+ case '>>>':
1408
+ return (Number(toPrimitive(left, 'number')) >>> 0) >>> (Number(toPrimitive(right, 'number')) | 0);
1409
+ case '&':
1410
+ return (Number(toPrimitive(left, 'number')) | 0) & (Number(toPrimitive(right, 'number')) | 0);
1411
+ case '^':
1412
+ return (Number(toPrimitive(left, 'number')) | 0) ^ (Number(toPrimitive(right, 'number')) | 0);
1413
+ case '|':
1414
+ return (Number(toPrimitive(left, 'number')) | 0) | (Number(toPrimitive(right, 'number')) | 0);
1415
+ // Comparison operations - follow JavaScript's abstract comparison rules
1416
+ case '==':
1417
+ return left == right;
1418
+ case '!=':
1419
+ return left != right;
1420
+ case '===':
1421
+ return left === right;
1422
+ case '!==':
1423
+ return left !== right;
1424
+ case '<': {
1425
+ const leftComp = toPrimitive(left, 'number');
1426
+ const rightComp = toPrimitive(right, 'number');
1427
+ // If both are strings, do string comparison
1428
+ if (typeof leftComp === 'string' && typeof rightComp === 'string') {
1429
+ return leftComp < rightComp;
1430
+ }
1431
+ return Number(leftComp) < Number(rightComp);
1432
+ }
1433
+ case '<=': {
1434
+ const leftLE = toPrimitive(left, 'number');
1435
+ const rightLE = toPrimitive(right, 'number');
1436
+ if (typeof leftLE === 'string' && typeof rightLE === 'string') {
1437
+ return leftLE <= rightLE;
1438
+ }
1439
+ return Number(leftLE) <= Number(rightLE);
1440
+ }
1441
+ case '>': {
1442
+ const leftGT = toPrimitive(left, 'number');
1443
+ const rightGT = toPrimitive(right, 'number');
1444
+ if (typeof leftGT === 'string' && typeof rightGT === 'string') {
1445
+ return leftGT > rightGT;
1446
+ }
1447
+ return Number(leftGT) > Number(rightGT);
1448
+ }
1449
+ case '>=': {
1450
+ const leftGE = toPrimitive(left, 'number');
1451
+ const rightGE = toPrimitive(right, 'number');
1452
+ if (typeof leftGE === 'string' && typeof rightGE === 'string') {
1453
+ return leftGE >= rightGE;
1454
+ }
1455
+ return Number(leftGE) >= Number(rightGE);
1456
+ }
1457
+ // Special operations
1458
+ case 'in': {
1459
+ if (typeof left === 'string' || typeof left === 'number' || typeof left === 'symbol') {
1460
+ if (right == null) {
1461
+ throw new Error(`Cannot use 'in' operator with null or undefined right operand`);
1462
+ }
1463
+ return left in right;
1464
+ }
1465
+ throw new Error(`Invalid left operand for 'in' operator: ${typeof left}`);
1466
+ }
1467
+ case 'instanceof': {
1468
+ if (typeof right === 'function') {
1469
+ return left instanceof right;
1470
+ }
1471
+ throw new Error(`Right operand of 'instanceof' is not a constructor`);
1472
+ }
1473
+ case '??':
1474
+ return left ?? right;
1475
+ default:
1476
+ throw new Error(`Unsupported binary operator: ${operator}`);
1477
+ }
1478
+ };
1479
+ /**
1480
+ * Safely evaluates binary expressions with proper type handling
1481
+ */
1459
1482
  const binaryExpressionVisitor = (node, st, callback) => {
1460
1483
  beforeVisitor(node, st);
1484
+ // Disable visitor result caching for now due to context sensitivity issues
1485
+ // const cachedResult = getCachedVisitorResult(node, st.context);
1486
+ // if (cachedResult !== undefined) {
1487
+ // pushVisitorResult(node, st, cachedResult);
1488
+ // afterVisitor(node, st);
1489
+ // return;
1490
+ // }
1461
1491
  callback(node.left, st);
1462
1492
  const left = popVisitorResult(node, st);
1463
1493
  callback(node.right, st);
1464
1494
  const right = popVisitorResult(node, st);
1465
- const value = node.operator === '+' ? left + right :
1466
- node.operator === '-' ? left - right :
1467
- node.operator === '*' ? left * right :
1468
- node.operator === '/' ? left / right :
1469
- node.operator === '%' ? left % right :
1470
- node.operator === '**' ? left ** right :
1471
- node.operator === '<<' ? left << right :
1472
- node.operator === '>>' ? left >> right :
1473
- node.operator === '>>>' ? left >>> right :
1474
- node.operator === '&' ? left & right :
1475
- node.operator === '^' ? left ^ right :
1476
- node.operator === '|' ? left | right :
1477
- node.operator === '==' ? left == right :
1478
- node.operator === '!=' ? left != right :
1479
- node.operator === '===' ? left === right :
1480
- node.operator === '!==' ? left !== right :
1481
- node.operator === '<' ? left < right :
1482
- node.operator === '<=' ? left <= right :
1483
- node.operator === '>' ? left > right :
1484
- node.operator === '>=' ? left >= right :
1485
- node.operator === 'in' ? left in right :
1486
- node.operator === 'instanceof' ? left instanceof right :
1487
- node.operator === '??' ? left ?? right :
1488
- undefined;
1495
+ const value = evaluateBinaryOperation(node.operator, left, right);
1496
+ // Disable visitor result caching for now
1497
+ // setCachedVisitorResult(node, st.context, value);
1489
1498
  pushVisitorResult(node, st, value);
1490
1499
  afterVisitor(node, st);
1491
1500
  };
1492
1501
 
1502
+ /**
1503
+ * Prototype Pollution Prevention Utilities
1504
+ *
1505
+ * This module provides safeguards against prototype pollution attacks
1506
+ * by controlling access to dangerous property names and ensuring safe
1507
+ * object operations.
1508
+ */
1509
+ /**
1510
+ * Set of property names that are dangerous for prototype pollution attacks
1511
+ */
1512
+ const DANGEROUS_PROPERTY_NAMES = new Set([
1513
+ '__proto__',
1514
+ 'constructor',
1515
+ 'prototype',
1516
+ '__defineGetter__',
1517
+ '__defineSetter__',
1518
+ '__lookupGetter__',
1519
+ '__lookupSetter__',
1520
+ 'hasOwnProperty',
1521
+ 'isPrototypeOf',
1522
+ 'propertyIsEnumerable',
1523
+ 'toString',
1524
+ 'valueOf',
1525
+ 'toLocaleString'
1526
+ ]);
1527
+ /**
1528
+ * Set of constructor names that should be blocked from modification
1529
+ */
1530
+ const DANGEROUS_CONSTRUCTORS$1 = new Set([
1531
+ 'Object',
1532
+ 'Function',
1533
+ 'Array',
1534
+ 'String',
1535
+ 'Number',
1536
+ 'Boolean',
1537
+ 'Date',
1538
+ 'RegExp',
1539
+ 'Error',
1540
+ 'Promise'
1541
+ ]);
1542
+ /**
1543
+ * Checks if a property name is dangerous for prototype pollution
1544
+ * @param key The property name to check
1545
+ * @returns true if the property is dangerous, false otherwise
1546
+ */
1547
+ const isDangerousProperty = (key) => {
1548
+ if (typeof key === 'string') {
1549
+ return DANGEROUS_PROPERTY_NAMES.has(key);
1550
+ }
1551
+ return false;
1552
+ };
1553
+ /**
1554
+ * Checks if an object is a dangerous constructor that shouldn't be modified
1555
+ * @param obj The object to check
1556
+ * @returns true if the object is a dangerous constructor, false otherwise
1557
+ */
1558
+ const isDangerousConstructor = (obj) => {
1559
+ if (typeof obj === 'function' && obj.name) {
1560
+ return DANGEROUS_CONSTRUCTORS$1.has(obj.name);
1561
+ }
1562
+ return false;
1563
+ };
1564
+ /**
1565
+ * Safely sets a property on an object with prototype pollution protection
1566
+ * @param target The target object
1567
+ * @param key The property key
1568
+ * @param value The property value
1569
+ * @throws Error if the operation would cause prototype pollution
1570
+ */
1571
+ const safeSetProperty = (target, key, value) => {
1572
+ if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
1573
+ throw new Error(`Cannot set property on non-object: ${typeof target}`);
1574
+ }
1575
+ if (isDangerousProperty(key)) {
1576
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1577
+ }
1578
+ // Additional protection: don't allow setting properties on built-in prototypes
1579
+ if (isDangerousConstructor(target)) {
1580
+ throw new Error(`Modification of built-in constructor "${target.name}" is blocked for security reasons`);
1581
+ }
1582
+ // Check if we're trying to modify prototype chain
1583
+ if (target === Object.prototype ||
1584
+ target === Function.prototype ||
1585
+ target === Array.prototype ||
1586
+ target === String.prototype ||
1587
+ target === Number.prototype ||
1588
+ target === Boolean.prototype) {
1589
+ throw new Error(`Modification of built-in prototype is blocked for security reasons`);
1590
+ }
1591
+ // Convert key to PropertyKey for safe operations
1592
+ let propertyKey;
1593
+ if (typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol') {
1594
+ propertyKey = key;
1595
+ }
1596
+ else {
1597
+ // For other types, try to convert to string
1598
+ propertyKey = String(key);
1599
+ }
1600
+ // Use Object.defineProperty for safer assignment
1601
+ const descriptor = {
1602
+ value,
1603
+ writable: true,
1604
+ enumerable: true,
1605
+ configurable: true
1606
+ };
1607
+ try {
1608
+ Object.defineProperty(target, propertyKey, descriptor);
1609
+ }
1610
+ catch (error) {
1611
+ throw new Error(`Failed to set property "${String(key)}": ${error instanceof Error ? error.message : String(error)}`);
1612
+ }
1613
+ };
1614
+ /**
1615
+ * Safely gets a property from an object with prototype pollution protection
1616
+ * @param target The target object
1617
+ * @param key The property key
1618
+ * @returns The property value or undefined
1619
+ */
1620
+ const safeGetProperty = (target, key) => {
1621
+ if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
1622
+ return undefined;
1623
+ }
1624
+ if (isDangerousProperty(key)) {
1625
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1626
+ }
1627
+ // Convert key to PropertyKey for safe operations
1628
+ let propertyKey;
1629
+ if (typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol') {
1630
+ propertyKey = key;
1631
+ }
1632
+ else {
1633
+ // For other types, try to convert to string
1634
+ propertyKey = String(key);
1635
+ }
1636
+ // Direct property access using bracket notation (safer than complex prototype walking)
1637
+ try {
1638
+ return target[propertyKey];
1639
+ }
1640
+ catch {
1641
+ // If property access fails, return undefined
1642
+ return undefined;
1643
+ }
1644
+ };
1645
+ /**
1646
+ * Creates a safe object without dangerous prototype pollution vectors
1647
+ * @param entries Key-value pairs to populate the object
1648
+ * @returns A new safe object
1649
+ */
1650
+ const createSafeObject = (entries = []) => {
1651
+ // Create object with normal prototype for compatibility, but validate contents
1652
+ const obj = {};
1653
+ for (const [key, value] of entries) {
1654
+ if (isDangerousProperty(key)) {
1655
+ throw new Error(`Cannot create object with dangerous property "${String(key)}"`);
1656
+ }
1657
+ // Safely set the property
1658
+ if (typeof key === 'string' || typeof key === 'number') {
1659
+ obj[key] = value;
1660
+ }
1661
+ else if (typeof key === 'symbol') {
1662
+ obj[key] = value;
1663
+ }
1664
+ }
1665
+ return obj;
1666
+ };
1667
+ /**
1668
+ * Validates that an object is safe from prototype pollution
1669
+ * @param obj The object to validate
1670
+ * @throws Error if the object contains dangerous properties
1671
+ */
1672
+ const validateSafeObject = (obj) => {
1673
+ if (!obj || typeof obj !== 'object') {
1674
+ return;
1675
+ }
1676
+ const keys = Object.getOwnPropertyNames(obj);
1677
+ for (const key of keys) {
1678
+ if (isDangerousProperty(key)) {
1679
+ throw new Error(`Object contains dangerous property "${key}" that could lead to prototype pollution`);
1680
+ }
1681
+ }
1682
+ // Also check symbol properties
1683
+ const symbols = Object.getOwnPropertySymbols(obj);
1684
+ for (const symbol of symbols) {
1685
+ const description = symbol.description;
1686
+ if (description && isDangerousProperty(description)) {
1687
+ throw new Error(`Object contains dangerous symbol property "${description}" that could lead to prototype pollution`);
1688
+ }
1689
+ }
1690
+ };
1691
+
1692
+ /**
1693
+ * Property Lookup Cache
1694
+ *
1695
+ * Provides efficient caching for case-insensitive property lookups
1696
+ * to avoid repeated O(n) searches through object property lists.
1697
+ */
1698
+ /**
1699
+ * Cache for property lookup results to optimize case-insensitive property access
1700
+ */
1701
+ class PropertyLookupCache {
1702
+ constructor(maxSize = 1000, expirationTimeMs = 5 * 60 * 1000) {
1703
+ this._cache = new Map();
1704
+ this._maxSize = maxSize;
1705
+ this._expirationTime = expirationTimeMs;
1706
+ }
1707
+ /**
1708
+ * Generates a simple hash for an object based on its own property names
1709
+ */
1710
+ generateObjectHash(obj) {
1711
+ try {
1712
+ const keys = Object.getOwnPropertyNames(obj);
1713
+ return keys.length.toString() + '_' + keys.slice(0, 5).join('_');
1714
+ }
1715
+ catch {
1716
+ return 'unknown_hash';
1717
+ }
1718
+ }
1719
+ /**
1720
+ * Generates a cache key for a property lookup
1721
+ */
1722
+ generateCacheKey(objectHash, searchKey) {
1723
+ return `${objectHash}:${searchKey.toLowerCase()}`;
1724
+ }
1725
+ /**
1726
+ * Checks if a cache entry is still valid
1727
+ */
1728
+ isEntryValid(entry, objectHash) {
1729
+ const now = Date.now();
1730
+ return (entry.objectHash === objectHash &&
1731
+ (now - entry.lastAccessed) < this._expirationTime);
1732
+ }
1733
+ /**
1734
+ * Cleans up expired entries and maintains cache size
1735
+ */
1736
+ cleanup() {
1737
+ const now = Date.now();
1738
+ const entries = Array.from(this._cache.entries());
1739
+ // Remove expired entries
1740
+ for (const [key, entry] of entries) {
1741
+ if ((now - entry.lastAccessed) >= this._expirationTime) {
1742
+ this._cache.delete(key);
1743
+ }
1744
+ }
1745
+ // If still too large, remove oldest entries
1746
+ if (this._cache.size > this._maxSize) {
1747
+ const sortedEntries = Array.from(this._cache.entries())
1748
+ .sort(([, a], [, b]) => a.lastAccessed - b.lastAccessed);
1749
+ const entriesToRemove = sortedEntries.slice(0, this._cache.size - this._maxSize);
1750
+ for (const [key] of entriesToRemove) {
1751
+ this._cache.delete(key);
1752
+ }
1753
+ }
1754
+ }
1755
+ /**
1756
+ * Gets a cached property lookup result
1757
+ */
1758
+ get(obj, searchKey) {
1759
+ const objectHash = this.generateObjectHash(obj);
1760
+ const cacheKey = this.generateCacheKey(objectHash, searchKey);
1761
+ const entry = this._cache.get(cacheKey);
1762
+ if (entry && this.isEntryValid(entry, objectHash)) {
1763
+ // Update access time
1764
+ entry.lastAccessed = Date.now();
1765
+ return entry.foundKey;
1766
+ }
1767
+ return undefined; // Cache miss
1768
+ }
1769
+ /**
1770
+ * Sets a cached property lookup result
1771
+ */
1772
+ set(obj, searchKey, foundKey) {
1773
+ // Perform cleanup periodically
1774
+ if (this._cache.size > this._maxSize * 0.8) {
1775
+ this.cleanup();
1776
+ }
1777
+ const objectHash = this.generateObjectHash(obj);
1778
+ const cacheKey = this.generateCacheKey(objectHash, searchKey);
1779
+ this._cache.set(cacheKey, {
1780
+ foundKey,
1781
+ lastAccessed: Date.now(),
1782
+ objectHash
1783
+ });
1784
+ }
1785
+ /**
1786
+ * Clears the entire cache
1787
+ */
1788
+ clear() {
1789
+ this._cache.clear();
1790
+ }
1791
+ /**
1792
+ * Gets current cache size
1793
+ */
1794
+ get size() {
1795
+ return this._cache.size;
1796
+ }
1797
+ }
1798
+ // Global property lookup cache instance
1799
+ const propertyLookupCache = new PropertyLookupCache();
1800
+ /**
1801
+ * Performs optimized case-insensitive property lookup with caching
1802
+ */
1803
+ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1804
+ // Try to get from cache first
1805
+ const cachedResult = propertyLookupCache.get(obj, searchKey);
1806
+ if (cachedResult !== undefined) {
1807
+ return cachedResult;
1808
+ }
1809
+ // Cache miss - perform actual lookup
1810
+ let foundKey = null;
1811
+ if (obj && typeof obj === 'object') {
1812
+ const ownKeys = Object.getOwnPropertyNames(obj);
1813
+ const matchingKey = ownKeys.find(k => equalIgnoreCase(k, searchKey));
1814
+ foundKey = matchingKey || null;
1815
+ }
1816
+ // Cache the result
1817
+ propertyLookupCache.set(obj, searchKey, foundKey);
1818
+ return foundKey;
1819
+ }
1820
+ /**
1821
+ * Clears the property lookup cache (for testing or memory management)
1822
+ */
1823
+ function clearPropertyLookupCache() {
1824
+ propertyLookupCache.clear();
1825
+ }
1826
+ /**
1827
+ * Gets current property lookup cache statistics
1828
+ */
1829
+ function getPropertyLookupCacheStats() {
1830
+ return {
1831
+ size: propertyLookupCache.size,
1832
+ maxSize: 1000 // This should match the maxSize in constructor
1833
+ };
1834
+ }
1835
+
1836
+ // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
1493
1837
  const memberExpressionVisitor = (node, st, callback) => {
1494
1838
  beforeVisitor(node, st);
1839
+ // Disable visitor result caching for now due to context sensitivity issues
1840
+ // const cachedResult = getCachedVisitorResult(node, st.context);
1841
+ // if (cachedResult !== undefined) {
1842
+ // pushVisitorResult(node, st, cachedResult);
1843
+ // afterVisitor(node, st);
1844
+ // return;
1845
+ // }
1495
1846
  const [, , value] = evaluateMember(node, st, callback);
1847
+ // Disable visitor result caching for now
1848
+ // setCachedVisitorResult(node, st.context, value);
1496
1849
  pushVisitorResult(node, st, value);
1497
1850
  afterVisitor(node, st);
1498
1851
  };
@@ -1503,36 +1856,110 @@ const evaluateMember = (node, st, callback) => {
1503
1856
  const object = (node.optional ? (obj || {}) : obj);
1504
1857
  // Get the property
1505
1858
  let key;
1506
- if (node.property.type === 'Identifier') {
1859
+ if (!node.computed && node.property.type === 'Identifier') {
1860
+ // Dot notation: obj.prop
1507
1861
  key = node.property.name;
1508
1862
  }
1509
1863
  else if (node.property.type === 'Literal') {
1864
+ // Computed literal: obj["literal"]
1510
1865
  key = node.property.value;
1511
1866
  }
1512
1867
  else {
1868
+ // Computed expression: obj[key], obj[expression]
1513
1869
  callback(node.property, st);
1514
1870
  key = popVisitorResult(node, st);
1515
1871
  }
1516
- // Get the value
1872
+ // Get the value with context-aware or prototype pollution protection
1517
1873
  if (object === st.context) {
1518
- const value = st.context.get(key);
1519
- const thisValue = st.context.getThis(key);
1520
- return [thisValue ?? object, key, value];
1874
+ // For context objects, preserve case-insensitive behavior
1875
+ const contextKey = st.options?.caseInsensitive && typeof key === 'string'
1876
+ ? st.context.getKey(key)
1877
+ : key;
1878
+ const value = st.context.get(contextKey);
1879
+ const thisValue = st.context.getThis(contextKey);
1880
+ return [thisValue ?? object, contextKey, value];
1521
1881
  }
1522
1882
  else if (object instanceof EvalScope) {
1883
+ // For scope objects, preserve original behavior (no getKey method)
1523
1884
  const value = object.get(key);
1524
1885
  const thisValue = object;
1525
1886
  return [thisValue ?? object, key, value];
1526
1887
  }
1527
1888
  else {
1528
- const caseInsesitive = !!(st.options?.caseInsensitive);
1529
- const pair = getKeyValue(object, key, caseInsesitive);
1530
- if (pair) {
1531
- const [key, value] = pair;
1532
- return [object, key, value];
1889
+ // For regular objects, we need both case-insensitive lookup AND prototype pollution protection
1890
+ let value;
1891
+ // Check if this is a primitive type (string, number, boolean) - these are safe for method access
1892
+ const isPrimitive = (typeof object === 'string' || typeof object === 'number' || typeof object === 'boolean');
1893
+ if (st.options?.caseInsensitive && typeof key === 'string') {
1894
+ // Use case-insensitive lookup but with prototype pollution protection
1895
+ // For primitives, skip dangerous property checks as their methods are safe
1896
+ if (!isPrimitive && isDangerousProperty(key)) {
1897
+ throw new Error(`Access to dangerous property "${key}" is blocked for security reasons`);
1898
+ }
1899
+ // Try case-insensitive lookup on own properties first
1900
+ const obj = object;
1901
+ let foundKey = undefined;
1902
+ if (obj && typeof obj === 'object') {
1903
+ // Create wrapper function for cache compatibility
1904
+ const compareIgnoreCase = (a, b) => {
1905
+ const result = equalIgnoreCase(a, b);
1906
+ return result === true;
1907
+ };
1908
+ // Use cached case-insensitive property lookup for own properties (optimization)
1909
+ const cachedFoundKey = getCachedCaseInsensitiveProperty(obj, key, compareIgnoreCase);
1910
+ if (cachedFoundKey !== undefined) {
1911
+ // Cache hit: cachedFoundKey is either the found key (string) or null (no match)
1912
+ foundKey = cachedFoundKey;
1913
+ }
1914
+ // If cache miss or not found in own properties, check if the original key exists (including prototype methods)
1915
+ if (cachedFoundKey === undefined || !foundKey) {
1916
+ try {
1917
+ // Test if property exists in prototype chain (this includes native methods like array.find)
1918
+ const testValue = obj[key];
1919
+ if (testValue !== undefined) {
1920
+ foundKey = key;
1921
+ }
1922
+ else {
1923
+ // Look for case variations in prototype methods for arrays, objects, etc.
1924
+ // This is more expensive but necessary for case-insensitive prototype method access
1925
+ const prototype = Object.getPrototypeOf(obj);
1926
+ if (prototype) {
1927
+ const prototypeKeys = Object.getOwnPropertyNames(prototype);
1928
+ foundKey = prototypeKeys.find(k => typeof k === 'string' && equalIgnoreCase(k, key));
1929
+ }
1930
+ }
1931
+ }
1932
+ catch {
1933
+ // If access fails, foundKey remains undefined
1934
+ }
1935
+ }
1936
+ // Check if the found key is dangerous (but only for non-primitives)
1937
+ if (!isPrimitive && foundKey && isDangerousProperty(foundKey)) {
1938
+ throw new Error(`Access to dangerous property "${foundKey}" is blocked for security reasons`);
1939
+ }
1940
+ }
1941
+ // Get the value using the found key or use safeGetProperty fallback for non-primitives
1942
+ if (isPrimitive) {
1943
+ // For primitives, direct access is safe
1944
+ value = foundKey ? obj[foundKey] : obj[key];
1945
+ }
1946
+ else {
1947
+ // For objects, use safe property access
1948
+ value = foundKey ? obj[foundKey] : safeGetProperty(object, key);
1949
+ }
1950
+ }
1951
+ else {
1952
+ // Use safe property access for prototype pollution protection (but not for primitives)
1953
+ if (isPrimitive) {
1954
+ // For primitives, direct access is safe
1955
+ value = object[key];
1956
+ }
1957
+ else {
1958
+ value = safeGetProperty(object, key);
1959
+ }
1533
1960
  }
1961
+ return [object, key, value];
1534
1962
  }
1535
- return [object, key, undefined];
1536
1963
  };
1537
1964
 
1538
1965
  const arrayExpressionVisitor = (node, st, callback) => {
@@ -1542,40 +1969,164 @@ const arrayExpressionVisitor = (node, st, callback) => {
1542
1969
  afterVisitor(node, st);
1543
1970
  };
1544
1971
  const evaluateArray = (node, items, st, callback) => {
1545
- const elements = [];
1546
- for (const element of items) {
1972
+ // Pre-allocate array with known length for better performance
1973
+ const itemCount = items.length;
1974
+ const elements = new Array(itemCount);
1975
+ let actualLength = 0;
1976
+ for (let i = 0; i < itemCount; i++) {
1977
+ const element = items[i];
1547
1978
  if (element === null || typeof element === 'undefined') {
1548
- elements.push(element);
1979
+ elements[actualLength++] = element;
1549
1980
  }
1550
1981
  else if (element.type === 'SpreadElement') {
1551
1982
  callback(element, st);
1552
1983
  const values = popVisitorResult(node, st);
1553
- elements.push(...values);
1984
+ // Expand the array if needed for spread elements
1985
+ if (values && Array.isArray(values)) {
1986
+ for (const value of values) {
1987
+ elements[actualLength++] = value;
1988
+ }
1989
+ }
1554
1990
  }
1555
1991
  else {
1556
1992
  callback(element, st);
1557
1993
  const value = popVisitorResult(node, st);
1558
- elements.push(value);
1994
+ elements[actualLength++] = value;
1559
1995
  }
1560
1996
  }
1997
+ // Trim array to actual size if it changed due to spread elements
1998
+ if (actualLength !== itemCount) {
1999
+ elements.length = actualLength;
2000
+ }
1561
2001
  return elements;
1562
2002
  };
1563
2003
 
2004
+ /**
2005
+ * Security: List of dangerous functions that should not be callable
2006
+ */
2007
+ const DANGEROUS_FUNCTIONS = new Set([
2008
+ 'Function',
2009
+ 'eval',
2010
+ 'setTimeout',
2011
+ 'setInterval',
2012
+ 'setImmediate',
2013
+ 'require',
2014
+ 'import',
2015
+ 'importScripts',
2016
+ 'XMLHttpRequest',
2017
+ 'fetch',
2018
+ 'WebSocket',
2019
+ 'Worker',
2020
+ 'SharedWorker',
2021
+ 'ServiceWorker',
2022
+ ]);
2023
+ /**
2024
+ * Security: List of dangerous patterns in function code
2025
+ * Only the most dangerous patterns that could lead to code injection
2026
+ */
2027
+ const DANGEROUS_PATTERNS = [
2028
+ /\beval\s*\(/i,
2029
+ /\bFunction\s*\(/, // Look for Function constructor (capital F only)
2030
+ /new\s+Function\s*\(/i,
2031
+ /\.__proto__\b/,
2032
+ /\.prototype\s*\.\s*constructor\b/,
2033
+ /\bglobalThis\b/,
2034
+ ];
2035
+ /**
2036
+ * Security: Check if a function name is dangerous
2037
+ */
2038
+ const isDangerousFunctionName = (fnName) => {
2039
+ return DANGEROUS_FUNCTIONS.has(fnName);
2040
+ };
2041
+ /**
2042
+ * Security: Check if function code contains dangerous patterns
2043
+ * Only check user-defined functions, not native ones
2044
+ */
2045
+ const hasDangerousPatterns = (fnString) => {
2046
+ // If it's a native function ([native code]), allow it
2047
+ if (fnString.includes('[native code]')) {
2048
+ return false;
2049
+ }
2050
+ // For user-defined functions, only check for truly dangerous patterns
2051
+ // that could lead to code injection or security bypass
2052
+ const result = DANGEROUS_PATTERNS.some(pattern => pattern.test(fnString));
2053
+ return result;
2054
+ };
2055
+ /**
2056
+ * Security: Check if a function is safe to call
2057
+ */
2058
+ const isFunctionSafe = (fn, fnName) => {
2059
+ if (typeof fn !== 'function') {
2060
+ return false;
2061
+ }
2062
+ // Check if it's a dangerous function by name
2063
+ if (fnName && isDangerousFunctionName(fnName)) {
2064
+ return false;
2065
+ }
2066
+ // Special check for Function constructor
2067
+ if (fn === Function) {
2068
+ return false;
2069
+ }
2070
+ try {
2071
+ // Check function string for dangerous patterns
2072
+ const fnString = fn.toString();
2073
+ if (hasDangerousPatterns(fnString)) {
2074
+ return false;
2075
+ }
2076
+ }
2077
+ catch {
2078
+ // If we can't get the function string, be cautious
2079
+ return false;
2080
+ }
2081
+ return true;
2082
+ };
2083
+ /**
2084
+ * Safely calls a function with proper error handling and security checks
2085
+ */
2086
+ const safeCall = (caller, thisArg, args, optional = false, fnName) => {
2087
+ if (!caller) {
2088
+ if (optional) {
2089
+ return undefined;
2090
+ }
2091
+ throw new Error(`Cannot call undefined or null function`);
2092
+ }
2093
+ if (typeof caller !== 'function') {
2094
+ throw new Error(`Value is not a function: ${typeof caller}`);
2095
+ }
2096
+ if (!isFunctionSafe(caller, fnName)) {
2097
+ throw new Error(`Function call blocked for security reasons: ${fnName || 'anonymous'}`);
2098
+ }
2099
+ try {
2100
+ return caller.apply(thisArg, args);
2101
+ }
2102
+ catch (error) {
2103
+ if (error instanceof Error) {
2104
+ throw new Error(`Function call error: ${error.message}`);
2105
+ }
2106
+ throw error;
2107
+ }
2108
+ };
2109
+ /**
2110
+ * Enhanced call expression visitor with security checks
2111
+ */
1564
2112
  const callExpressionVisitor = (node, st, callback) => {
1565
2113
  beforeVisitor(node, st);
1566
2114
  const args = evaluateArray(node, node.arguments, st, callback);
1567
2115
  if (node.callee.type === 'MemberExpression') {
1568
- const [object, , fn] = evaluateMember(node.callee, st, callback);
1569
- const caller = fn;
1570
- const value = !caller && node.callee.optional
1571
- ? undefined : caller.apply(object, args);
2116
+ const [object, propertyName, fn] = evaluateMember(node.callee, st, callback);
2117
+ const functionName = typeof propertyName === 'string' ? propertyName : undefined;
2118
+ const value = safeCall(fn, object, args, node.callee.optional, functionName);
1572
2119
  pushVisitorResult(node, st, value);
1573
2120
  }
1574
2121
  else {
1575
2122
  callback(node.callee, st);
1576
2123
  const caller = popVisitorResult(node, st);
1577
- const value = !caller && node.optional
1578
- ? undefined : caller.apply(st.context, args);
2124
+ // Try to get function name for security checks
2125
+ let functionName;
2126
+ if (node.callee.type === 'Identifier') {
2127
+ functionName = node.callee.name;
2128
+ }
2129
+ const value = safeCall(caller, st.context, args, node.optional, functionName);
1579
2130
  pushVisitorResult(node, st, value);
1580
2131
  }
1581
2132
  afterVisitor(node, st);
@@ -1588,16 +2139,84 @@ const evaluateCall = (node, st, callback) => {
1588
2139
  const value = popVisitorResult(node, st);
1589
2140
  return value;
1590
2141
  });
1591
- const value = caller.apply(st.context, args);
2142
+ // Get function name for security checks
2143
+ let functionName;
2144
+ if (node.callee.type === 'Identifier') {
2145
+ functionName = node.callee.name;
2146
+ }
2147
+ const value = safeCall(caller, st.context, args, false, functionName);
1592
2148
  return value;
1593
2149
  };
1594
2150
 
2151
+ /**
2152
+ * ImportExpression visitor - blocks all dynamic imports for security
2153
+ */
2154
+ const importExpressionVisitor = (node, st) => {
2155
+ beforeVisitor(node, st);
2156
+ // Block all dynamic imports for security reasons
2157
+ throw new Error('Function call blocked for security reasons: import');
2158
+ afterVisitor(node, st);
2159
+ };
2160
+
2161
+ // Default timeout for await expressions (30 seconds)
2162
+ const DEFAULT_AWAIT_TIMEOUT = 30000;
2163
+ /**
2164
+ * Creates a timeout promise that rejects after the specified timeout
2165
+ */
2166
+ const createTimeoutPromise = (timeout) => {
2167
+ return new Promise((_, reject) => {
2168
+ setTimeout(() => {
2169
+ reject(new Error(`Await expression timed out after ${timeout}ms`));
2170
+ }, timeout);
2171
+ });
2172
+ };
2173
+ /**
2174
+ * Safely wraps a value in a promise if it's not already a promise
2175
+ */
2176
+ const ensurePromise = (value) => {
2177
+ if (value && typeof value === 'object' && 'then' in value) {
2178
+ return value;
2179
+ }
2180
+ return Promise.resolve(value);
2181
+ };
1595
2182
  const awaitVisitor = (node, st, callback) => {
1596
2183
  beforeVisitor(node, st);
1597
- const promise = new Promise((resolve) => {
1598
- callback(node.argument, st);
1599
- const value = popVisitorResult(node, st);
1600
- resolve(value);
2184
+ const promise = new Promise((resolve, reject) => {
2185
+ try {
2186
+ callback(node.argument, st);
2187
+ const value = popVisitorResult(node, st);
2188
+ // Convert value to promise if it's not already one
2189
+ const valuePromise = ensurePromise(value);
2190
+ // Get timeout from context or use default
2191
+ const contextObj = st.context?.original;
2192
+ const timeout = (contextObj && typeof contextObj['__awaitTimeout'] === 'number'
2193
+ ? contextObj['__awaitTimeout']
2194
+ : DEFAULT_AWAIT_TIMEOUT);
2195
+ // Race between the actual promise and timeout
2196
+ Promise.race([
2197
+ valuePromise,
2198
+ createTimeoutPromise(timeout)
2199
+ ])
2200
+ .then(resolve)
2201
+ .catch((error) => {
2202
+ // Enhance error information with context
2203
+ const enhancedError = error instanceof Error
2204
+ ? error
2205
+ : new Error(`Await expression failed: ${String(error)}`);
2206
+ // Add source location information if available
2207
+ if (node.start !== undefined && node.end !== undefined) {
2208
+ enhancedError.message += ` at position ${node.start}-${node.end}`;
2209
+ }
2210
+ reject(enhancedError);
2211
+ });
2212
+ }
2213
+ catch (synchronousError) {
2214
+ // Handle synchronous errors immediately
2215
+ const enhancedError = synchronousError instanceof Error
2216
+ ? synchronousError
2217
+ : new Error(`Await expression failed synchronously: ${String(synchronousError)}`);
2218
+ reject(enhancedError);
2219
+ }
1601
2220
  });
1602
2221
  pushVisitorResult(node, st, promise);
1603
2222
  afterVisitor(node, st);
@@ -1638,21 +2257,42 @@ const logicalExpressionVisitor = (node, st, callback) => {
1638
2257
  beforeVisitor(node, st);
1639
2258
  callback(node.left, st);
1640
2259
  const left = popVisitorResult(node, st);
2260
+ // For && operator: if left is falsy, return left (don't evaluate right)
1641
2261
  if (node.operator === '&&' && !left) {
1642
2262
  pushVisitorResult(node, st, left);
1643
2263
  afterVisitor(node, st);
1644
2264
  return;
1645
2265
  }
1646
- else if (node.operator === '||' && left) {
1647
- pushVisitorResult(node, st, true);
2266
+ // For || operator: if left is truthy, return left (don't evaluate right)
2267
+ if (node.operator === '||' && left) {
2268
+ pushVisitorResult(node, st, left);
1648
2269
  afterVisitor(node, st);
1649
2270
  return;
1650
2271
  }
2272
+ // For ?? operator: if left is not null/undefined, return left (don't evaluate right)
2273
+ if (node.operator === '??' && left !== null && left !== undefined) {
2274
+ pushVisitorResult(node, st, left);
2275
+ afterVisitor(node, st);
2276
+ return;
2277
+ }
2278
+ // Evaluate right operand
1651
2279
  callback(node.right, st);
1652
2280
  const right = popVisitorResult(node, st);
1653
- const value = node.operator === '&&' ? left && right :
1654
- node.operator === '||' ? left || right :
1655
- undefined;
2281
+ // Return the appropriate value based on operator
2282
+ let value;
2283
+ switch (node.operator) {
2284
+ case '&&':
2285
+ value = left && right;
2286
+ break;
2287
+ case '||':
2288
+ value = left || right;
2289
+ break;
2290
+ case '??':
2291
+ value = left ?? right;
2292
+ break;
2293
+ default:
2294
+ throw new Error(`Unsupported logical operator: ${node.operator}`);
2295
+ }
1656
2296
  pushVisitorResult(node, st, value);
1657
2297
  afterVisitor(node, st);
1658
2298
  };
@@ -1664,21 +2304,94 @@ const thisExpressionVisitor = (node, st) => {
1664
2304
  afterVisitor(node, st);
1665
2305
  };
1666
2306
 
2307
+ /**
2308
+ * Security: List of dangerous constructors that should not be instantiated
2309
+ */
2310
+ const DANGEROUS_CONSTRUCTORS = new Set([
2311
+ 'Function',
2312
+ 'GeneratorFunction',
2313
+ 'AsyncFunction',
2314
+ 'AsyncGeneratorFunction',
2315
+ 'XMLHttpRequest',
2316
+ 'WebSocket',
2317
+ 'Worker',
2318
+ 'SharedWorker',
2319
+ 'ServiceWorker',
2320
+ 'Proxy',
2321
+ ]);
2322
+ /**
2323
+ * Security: Check if a constructor is safe to use
2324
+ */
2325
+ const isConstructorSafe = (constructor, constructorName) => {
2326
+ if (typeof constructor !== 'function') {
2327
+ return false;
2328
+ }
2329
+ // Check if it's a dangerous constructor by name
2330
+ if (constructorName && DANGEROUS_CONSTRUCTORS.has(constructorName)) {
2331
+ return false;
2332
+ }
2333
+ // Special check for Function constructor and its variants
2334
+ if (constructor === Function ||
2335
+ constructor === (async function () { }).constructor ||
2336
+ constructor === (function* () { }).constructor ||
2337
+ constructor === (async function* () { }).constructor) {
2338
+ return false;
2339
+ }
2340
+ try {
2341
+ // Check constructor string for dangerous patterns
2342
+ const constructorString = constructor.toString();
2343
+ if (constructorString.includes('eval') ||
2344
+ constructorString.includes('Function(') ||
2345
+ constructorString.includes('constructor(')) {
2346
+ return false;
2347
+ }
2348
+ }
2349
+ catch {
2350
+ // If we can't get the constructor string, be cautious
2351
+ return false;
2352
+ }
2353
+ return true;
2354
+ };
2355
+ /**
2356
+ * Safely creates a new instance with proper security checks
2357
+ */
2358
+ const safeNew = (constructor, args, constructorName) => {
2359
+ if (!constructor) {
2360
+ throw new Error('Cannot instantiate undefined or null constructor');
2361
+ }
2362
+ if (typeof constructor !== 'function') {
2363
+ throw new Error(`Value is not a constructor: ${typeof constructor}`);
2364
+ }
2365
+ if (!isConstructorSafe(constructor, constructorName)) {
2366
+ throw new Error(`Constructor blocked for security reasons: ${constructorName || 'anonymous'}`);
2367
+ }
2368
+ try {
2369
+ return Reflect.construct(constructor, args);
2370
+ }
2371
+ catch (error) {
2372
+ if (error instanceof Error) {
2373
+ throw new Error(`Constructor error: ${error.message}`);
2374
+ }
2375
+ throw error;
2376
+ }
2377
+ };
1667
2378
  const newExpressionVisitor = (node, st, callback) => {
1668
2379
  beforeVisitor(node, st);
1669
2380
  const args = evaluateArray(node, node.arguments, st, callback);
1670
2381
  callback(node.callee, st);
1671
2382
  const constructor = popVisitorResult(node, st);
1672
- const value = newFunc(constructor, ...args);
2383
+ // Try to get constructor name for security checks
2384
+ let constructorName;
2385
+ if (node.callee.type === 'Identifier') {
2386
+ constructorName = node.callee.name;
2387
+ }
2388
+ const value = safeNew(constructor, args, constructorName);
1673
2389
  pushVisitorResult(node, st, value);
1674
2390
  afterVisitor(node, st);
1675
2391
  };
1676
- // based on Reflect.construct()
1677
- // https://stackoverflow.com/questions/10428603/simulate-the-new-operator-in-javascript
1678
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct
2392
+ // Legacy function - now with security checks
1679
2393
  const newFunc = (constructor, ...args) => {
1680
- const obj = Reflect.construct(constructor, args);
1681
- return obj;
2394
+ return safeNew(constructor, args);
1682
2395
  };
1683
2396
 
1684
2397
  const templateLiteralVisitor = (node, st, callback) => {
@@ -1718,22 +2431,41 @@ const taggedTemplateExpressionVisitor = (node, st, callback) => {
1718
2431
 
1719
2432
  const objectExpressionVisitor = (node, st, callback) => {
1720
2433
  beforeVisitor(node, st);
1721
- const map = new Map();
1722
- for (const property of node.properties) {
2434
+ // Pre-allocate entries array for better performance
2435
+ const propertyCount = node.properties.length;
2436
+ const entries = [];
2437
+ for (let i = 0; i < propertyCount; i++) {
2438
+ const property = node.properties[i];
1723
2439
  if (property.type === 'SpreadElement') {
1724
2440
  callback(property.argument, st);
1725
2441
  const value = popVisitorResult(property, st);
1726
- for (const [key, val] of Object.entries(value)) {
1727
- map.set(key, val);
2442
+ // Validate spread object for safety
2443
+ try {
2444
+ validateSafeObject(value);
2445
+ }
2446
+ catch (error) {
2447
+ throw new Error(`Spread operation blocked: ${error instanceof Error ? error.message : String(error)}`);
2448
+ }
2449
+ // Use Object.entries() once and cache the result
2450
+ const spreadEntries = Object.entries(value);
2451
+ for (let j = 0; j < spreadEntries.length; j++) {
2452
+ const [key, val] = spreadEntries[j];
2453
+ entries.push([key, val]);
1728
2454
  }
1729
2455
  }
1730
2456
  else {
1731
2457
  const pair = evalProperty(property, st, callback);
1732
- map.set(pair.key, pair.value);
2458
+ entries.push([pair.key, pair.value]);
1733
2459
  }
1734
2460
  }
1735
- const obj = Object.fromEntries(map);
1736
- pushVisitorResult(node, st, obj);
2461
+ // Create safe object with prototype pollution protection
2462
+ try {
2463
+ const obj = createSafeObject(entries);
2464
+ pushVisitorResult(node, st, obj);
2465
+ }
2466
+ catch (error) {
2467
+ throw new Error(`Object creation blocked: ${error instanceof Error ? error.message : String(error)}`);
2468
+ }
1737
2469
  afterVisitor(node, st);
1738
2470
  };
1739
2471
  const evalProperty = (property, st, callback) => {
@@ -1776,6 +2508,7 @@ const getDefaultVisitors = () => {
1776
2508
  visitors['Identifier'] = identifierVisitor;
1777
2509
  visitors['Literal'] = literalVisitor;
1778
2510
  visitors['CallExpression'] = callExpressionVisitor;
2511
+ visitors['ImportExpression'] = importExpressionVisitor;
1779
2512
  visitors['AwaitExpression'] = awaitVisitor;
1780
2513
  visitors['ConditionalExpression'] = conditionalExpressionVisitor;
1781
2514
  visitors['MemberExpression'] = memberExpressionVisitor;
@@ -1835,7 +2568,8 @@ const assignmentExpressionVisitor = (node, st, callback) => {
1835
2568
  else if (node.left.type === 'MemberExpression') {
1836
2569
  const [object, key,] = evaluateMember(node.left, st, callback);
1837
2570
  const value = func(left, right);
1838
- object[key] = value;
2571
+ // Use safe property assignment to prevent prototype pollution
2572
+ safeSetProperty(object, key, value);
1839
2573
  pushVisitorResult(node, st, value);
1840
2574
  }
1841
2575
  afterVisitor(node, st);
@@ -1860,10 +2594,10 @@ const updateExpressionVisitor = (node, st, callback) => {
1860
2594
  pushVisitorResult(node, st, node.prefix ? newValue : value);
1861
2595
  }
1862
2596
  else if (node.argument.type === 'MemberExpression') {
1863
- callback(node.argument, st);
1864
- const [, property, value] = evaluateMember(node.argument, st, callback);
2597
+ const [object, property, value] = evaluateMember(node.argument, st, callback);
1865
2598
  const newValue = updateOperators[node.operator](value);
1866
- st.context?.set(property, newValue);
2599
+ // Use safe property assignment to prevent prototype pollution
2600
+ safeSetProperty(object, property, newValue);
1867
2601
  pushVisitorResult(node, st, node.prefix ? newValue : value);
1868
2602
  }
1869
2603
  afterVisitor(node, st);
@@ -1925,18 +2659,93 @@ const evaluate = (node, state) => {
1925
2659
  }
1926
2660
  return undefined;
1927
2661
  };
2662
+ /**
2663
+ * Converts a rejection value to a proper Error object
2664
+ */
2665
+ const ensureError = (rejection) => {
2666
+ if (rejection instanceof Error) {
2667
+ return rejection;
2668
+ }
2669
+ if (typeof rejection === 'string') {
2670
+ return new Error(rejection);
2671
+ }
2672
+ if (rejection === null) {
2673
+ return new Error('Promise rejected with null');
2674
+ }
2675
+ if (rejection === undefined) {
2676
+ return new Error('Promise rejected with undefined');
2677
+ }
2678
+ if (typeof rejection === 'object') {
2679
+ return new Error(`Promise rejected with object: ${JSON.stringify(rejection)}`);
2680
+ }
2681
+ return new Error(`Promise rejected with value: ${String(rejection)}`);
2682
+ };
2683
+ /**
2684
+ * Recursively awaits all promises in a value structure
2685
+ */
2686
+ const awaitAllPromises = async (value) => {
2687
+ if (!value || typeof value !== 'object') {
2688
+ return value;
2689
+ }
2690
+ // If it's a promise, await it and handle rejections
2691
+ if ('then' in value) {
2692
+ try {
2693
+ return await value;
2694
+ }
2695
+ catch (rejection) {
2696
+ throw ensureError(rejection);
2697
+ }
2698
+ }
2699
+ // If it's an array, recursively await all elements
2700
+ if (Array.isArray(value)) {
2701
+ return Promise.all(value.map(item => awaitAllPromises(item)));
2702
+ }
2703
+ // If it's an object, recursively await all properties
2704
+ if (value.constructor === Object) {
2705
+ const result = {};
2706
+ const promises = Object.entries(value).map(async ([key, val]) => {
2707
+ result[key] = await awaitAllPromises(val);
2708
+ });
2709
+ await Promise.all(promises);
2710
+ return result;
2711
+ }
2712
+ return value;
2713
+ };
1928
2714
  /**
1929
2715
  * Asynchronously evaluates the given abstract syntax tree (AST) using the provided evaluation state.
1930
2716
  * @param ast The abstract syntax tree to evaluate.
1931
2717
  * @param state The evaluation state.
1932
2718
  * @returns A promise that resolves to the evaluated value or undefined.
1933
2719
  */
1934
- const evaluateAsync = (ast, state) => {
1935
- const promise = new Promise((resolve) => {
1936
- const value = evaluate(ast, state);
1937
- resolve(value);
1938
- });
1939
- return promise;
2720
+ const evaluateAsync = async (ast, state) => {
2721
+ if (!ast) {
2722
+ return undefined;
2723
+ }
2724
+ state.result.start();
2725
+ try {
2726
+ const visitors = getDefaultVisitors();
2727
+ walk.recursive(ast, state, visitors);
2728
+ let value = popVisitorResult(ast, state);
2729
+ // Enhanced promise handling - recursively await all promises
2730
+ try {
2731
+ value = await awaitAllPromises(value);
2732
+ }
2733
+ catch (promiseError) {
2734
+ // Ensure proper error handling for promise rejections
2735
+ const error = ensureError(promiseError);
2736
+ state.result.stop();
2737
+ state.result.setFailure(error);
2738
+ throw error;
2739
+ }
2740
+ state.result.stop();
2741
+ state.result.setSuccess(value);
2742
+ return value;
2743
+ }
2744
+ catch (error) {
2745
+ state.result.stop();
2746
+ state.result.setFailure(error);
2747
+ throw error;
2748
+ }
1940
2749
  };
1941
2750
 
1942
2751
  /**
@@ -2192,7 +3001,7 @@ class EvalScope {
2192
3001
  * @returns The value of the specified key, or undefined if the key is not found.
2193
3002
  */
2194
3003
  get(key) {
2195
- const { caseInsensitive, namespace } = this._options;
3004
+ const { caseInsensitive, namespace, global } = this._options;
2196
3005
  const { context } = this;
2197
3006
  if (typeof key === 'string' && namespace) {
2198
3007
  const found = caseInsensitive
@@ -2202,8 +3011,11 @@ class EvalScope {
2202
3011
  return this.context;
2203
3012
  }
2204
3013
  }
2205
- const value = getContextValue(context, key);
2206
- return value;
3014
+ if (global) {
3015
+ const value = getContextValue(context, key);
3016
+ return value;
3017
+ }
3018
+ return undefined;
2207
3019
  }
2208
3020
  /**
2209
3021
  * Sets the value of the specified key.
@@ -2275,6 +3087,7 @@ class BaseEval {
2275
3087
  /**
2276
3088
  * @description
2277
3089
  * Service for parsing expressions and returning ES6/ES2020 AST.
3090
+ * Implements OnDestroy for proper memory cleanup.
2278
3091
  */
2279
3092
  class ParserService {
2280
3093
  /**
@@ -2294,12 +3107,46 @@ class ParserService {
2294
3107
  * Constructs a new instance of the ParserService class.
2295
3108
  */
2296
3109
  constructor() {
3110
+ this._isDestroyed = false;
2297
3111
  this.parserOptions = {
2298
3112
  ...defaultParserOptions,
2299
3113
  extractExpressions: true
2300
3114
  };
2301
3115
  if (this.parserOptions.cacheSize) {
2302
3116
  this._cache = new Cache(this.parserOptions.cacheSize);
3117
+ // Set up periodic cache cleanup to prevent memory leaks
3118
+ this.setupCacheCleanup();
3119
+ }
3120
+ }
3121
+ /**
3122
+ * Setup periodic cache cleanup to prevent memory leaks
3123
+ */
3124
+ setupCacheCleanup() {
3125
+ if (this._cache && typeof setInterval !== 'undefined') {
3126
+ // Clean up cache every 5 minutes to prevent unbounded growth
3127
+ this._cacheCleanupInterval = setInterval(() => {
3128
+ if (!this._isDestroyed && this._cache) {
3129
+ // Keep cache size within bounds by clearing if it gets too large
3130
+ if (this._cache.size > this._cache.maxCacheSize * 0.8) {
3131
+ this._cache.clear();
3132
+ console.debug('Parser cache cleared to prevent memory leaks');
3133
+ }
3134
+ }
3135
+ }, 5 * 60 * 1000); // 5 minutes
3136
+ }
3137
+ }
3138
+ /**
3139
+ * Clean up resources to prevent memory leaks
3140
+ */
3141
+ ngOnDestroy() {
3142
+ this._isDestroyed = true;
3143
+ if (this._cacheCleanupInterval) {
3144
+ clearInterval(this._cacheCleanupInterval);
3145
+ this._cacheCleanupInterval = undefined;
3146
+ }
3147
+ if (this._cache) {
3148
+ this._cache.clear();
3149
+ this._cache = undefined;
2303
3150
  }
2304
3151
  }
2305
3152
  /**
@@ -2324,6 +3171,9 @@ class ParserService {
2324
3171
  * @returns The parsed AST (Abstract Syntax Tree).
2325
3172
  */
2326
3173
  parse(expr, options) {
3174
+ if (this._isDestroyed) {
3175
+ throw new Error('ParserService has been destroyed and cannot be used');
3176
+ }
2327
3177
  if (expr) {
2328
3178
  try {
2329
3179
  const parserOptions = { ...this.parserOptions, ...options };
@@ -2357,10 +3207,10 @@ class ParserService {
2357
3207
  }
2358
3208
  return undefined;
2359
3209
  }
2360
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: ParserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2361
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: ParserService, providedIn: 'root' }); }
3210
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: ParserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
3211
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: ParserService, providedIn: 'root' }); }
2362
3212
  }
2363
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: ParserService, decorators: [{
3213
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: ParserService, decorators: [{
2364
3214
  type: Injectable,
2365
3215
  args: [{
2366
3216
  providedIn: 'root'
@@ -2368,7 +3218,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImpor
2368
3218
  }], ctorParameters: () => [] });
2369
3219
 
2370
3220
  /**
2371
- * Service for evaluating and parsing expressions.
3221
+ * Service for evaluating and parsing expressions with proper memory management.
2372
3222
  */
2373
3223
  class EvalService extends BaseEval {
2374
3224
  /**
@@ -2378,8 +3228,72 @@ class EvalService extends BaseEval {
2378
3228
  constructor(parserService) {
2379
3229
  super(parserService);
2380
3230
  this.parserService = parserService;
3231
+ this._isDestroyed = false;
3232
+ this._activeContexts = new Set();
3233
+ this._activeStates = new Set();
2381
3234
  this.parserOptions = defaultParserOptions;
2382
3235
  }
3236
+ /**
3237
+ * Override createState to track active contexts and states for cleanup
3238
+ */
3239
+ createState(context, options) {
3240
+ if (this._isDestroyed) {
3241
+ throw new Error('EvalService has been destroyed and cannot be used');
3242
+ }
3243
+ const state = super.createState(context, options);
3244
+ // Track active states for cleanup
3245
+ this._activeStates.add(state);
3246
+ // Track active contexts
3247
+ if (context && typeof context === 'object') {
3248
+ // Check if it's a Registry-based context (has type property)
3249
+ if ('type' in context) {
3250
+ this._activeContexts.add(context);
3251
+ }
3252
+ // For EvalContext, check if it has a nested context using bracket notation
3253
+ if ('context' in context) {
3254
+ const nestedContext = context['context'];
3255
+ if (nestedContext && typeof nestedContext === 'object' && 'type' in nestedContext) {
3256
+ this._activeContexts.add(nestedContext);
3257
+ }
3258
+ }
3259
+ }
3260
+ return state;
3261
+ }
3262
+ /**
3263
+ * Clean up resources to prevent memory leaks
3264
+ */
3265
+ ngOnDestroy() {
3266
+ this._isDestroyed = true;
3267
+ // Clean up all active states
3268
+ for (const state of this._activeStates) {
3269
+ try {
3270
+ // Clear the stack in the result
3271
+ if (state.result?.stack) {
3272
+ state.result.stack.clear();
3273
+ }
3274
+ // Clear context if it has a clear method
3275
+ if (state.context && typeof state.context === 'object' && 'clear' in state.context && typeof state.context.clear === 'function') {
3276
+ state.context.clear();
3277
+ }
3278
+ }
3279
+ catch (error) {
3280
+ console.warn('Error cleaning up EvalState:', error);
3281
+ }
3282
+ }
3283
+ this._activeStates.clear();
3284
+ // Clean up all active contexts
3285
+ for (const context of this._activeContexts) {
3286
+ try {
3287
+ if (context && typeof context.clear === 'function') {
3288
+ context.clear();
3289
+ }
3290
+ }
3291
+ catch (error) {
3292
+ console.warn('Error cleaning up Context:', error);
3293
+ }
3294
+ }
3295
+ this._activeContexts.clear();
3296
+ }
2383
3297
  /**
2384
3298
  * Evaluates the given expression.
2385
3299
  * @param expression The expression to evaluate.
@@ -2484,10 +3398,10 @@ class EvalService extends BaseEval {
2484
3398
  }
2485
3399
  }
2486
3400
  }
2487
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: EvalService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
2488
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: EvalService, providedIn: 'root' }); }
3401
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: EvalService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3402
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: EvalService, providedIn: 'root' }); }
2489
3403
  }
2490
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: EvalService, decorators: [{
3404
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: EvalService, decorators: [{
2491
3405
  type: Injectable,
2492
3406
  args: [{
2493
3407
  providedIn: 'root'
@@ -2496,25 +3410,138 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImpor
2496
3410
 
2497
3411
  /**
2498
3412
  * CompilerService class that extends BaseEval.
2499
- * Provides methods for compiling and evaluating expressions.
3413
+ * Provides methods for compiling and evaluating expressions with performance caching.
2500
3414
  */
2501
3415
  class CompilerService extends BaseEval {
2502
3416
  constructor(parserService, evalService) {
2503
3417
  super(parserService);
2504
3418
  this.parserService = parserService;
2505
3419
  this.evalService = evalService;
3420
+ // Compilation cache with LRU eviction
3421
+ this._compilationCache = new Map();
3422
+ this._maxCacheSize = 200;
3423
+ this._cacheTTL = 10 * 60 * 1000; // 10 minutes
3424
+ this._accessOrder = new Set();
3425
+ this._isDestroyed = false;
2506
3426
  this.parserOptions = defaultParserOptions;
3427
+ this.setupCacheCleanup();
2507
3428
  }
2508
3429
  /**
2509
- * Compiles the given expression into a state callback function.
3430
+ * OnDestroy lifecycle hook for cleanup
3431
+ */
3432
+ ngOnDestroy() {
3433
+ this._isDestroyed = true;
3434
+ if (this._cacheCleanupInterval) {
3435
+ clearInterval(this._cacheCleanupInterval);
3436
+ }
3437
+ this._compilationCache.clear();
3438
+ this._accessOrder.clear();
3439
+ }
3440
+ /**
3441
+ * Setup periodic cache cleanup to prevent memory leaks and stale entries
3442
+ */
3443
+ setupCacheCleanup() {
3444
+ if (typeof setInterval !== 'undefined') {
3445
+ this._cacheCleanupInterval = setInterval(() => {
3446
+ if (!this._isDestroyed) {
3447
+ this.cleanupCache();
3448
+ }
3449
+ }, 5 * 60 * 1000); // Clean every 5 minutes
3450
+ }
3451
+ }
3452
+ /**
3453
+ * Clean expired entries and enforce cache size limits
3454
+ */
3455
+ cleanupCache() {
3456
+ const now = performance.now();
3457
+ const toDelete = [];
3458
+ // Remove expired entries
3459
+ for (const [key, cached] of this._compilationCache) {
3460
+ if (now - cached.timestamp > this._cacheTTL) {
3461
+ toDelete.push(key);
3462
+ }
3463
+ }
3464
+ // Remove expired entries
3465
+ toDelete.forEach(key => {
3466
+ this._compilationCache.delete(key);
3467
+ this._accessOrder.delete(key);
3468
+ });
3469
+ // Enforce cache size limit using LRU
3470
+ while (this._compilationCache.size > this._maxCacheSize) {
3471
+ const oldestKey = Array.from(this._accessOrder)[0];
3472
+ if (oldestKey) {
3473
+ this._compilationCache.delete(oldestKey);
3474
+ this._accessOrder.delete(oldestKey);
3475
+ }
3476
+ else {
3477
+ break;
3478
+ }
3479
+ }
3480
+ }
3481
+ /**
3482
+ * Generate cache key for expression
3483
+ */
3484
+ generateCacheKey(expression) {
3485
+ if (typeof expression === 'string') {
3486
+ return `str:${expression}`;
3487
+ }
3488
+ else if (expression && typeof expression === 'object') {
3489
+ // Use a simplified hash for AST nodes to avoid deep serialization overhead
3490
+ return `ast:${expression.type}:${JSON.stringify({
3491
+ type: expression.type,
3492
+ start: expression.start,
3493
+ end: expression.end
3494
+ })}:${expression.toString()}`;
3495
+ }
3496
+ return 'undefined';
3497
+ }
3498
+ /**
3499
+ * Update access order for LRU cache
3500
+ */
3501
+ updateAccessOrder(key) {
3502
+ this._accessOrder.delete(key);
3503
+ this._accessOrder.add(key);
3504
+ }
3505
+ /**
3506
+ * Compiles the given expression into a state callback function with caching.
2510
3507
  * @param expression - The expression to compile.
2511
3508
  * @returns The compiled state callback function.
2512
3509
  * @throws Error if there is an error during compilation.
2513
3510
  */
2514
3511
  compile(expression) {
2515
3512
  try {
3513
+ const cacheKey = this.generateCacheKey(expression);
3514
+ // Check cache first
3515
+ const cached = this._compilationCache.get(cacheKey);
3516
+ if (cached?.sync) {
3517
+ // Update access order for LRU
3518
+ this.updateAccessOrder(cacheKey);
3519
+ cached.accessCount++;
3520
+ // Check if entry is still fresh
3521
+ const age = performance.now() - cached.timestamp;
3522
+ if (age < this._cacheTTL) {
3523
+ return cached.sync;
3524
+ }
3525
+ }
3526
+ // Compile fresh
2516
3527
  const ast = this.parse(expression);
2517
3528
  const fn = compile(ast);
3529
+ if (fn) {
3530
+ // Cache the result
3531
+ const existingCache = this._compilationCache.get(cacheKey) || {
3532
+ timestamp: performance.now(),
3533
+ accessCount: 0
3534
+ };
3535
+ existingCache.sync = fn;
3536
+ existingCache.timestamp = performance.now();
3537
+ existingCache.accessCount++;
3538
+ this._compilationCache.set(cacheKey, existingCache);
3539
+ this.updateAccessOrder(cacheKey);
3540
+ // Cleanup if cache is getting too large
3541
+ if (this._compilationCache.size > this._maxCacheSize * 1.2) {
3542
+ this.cleanupCache();
3543
+ }
3544
+ }
2518
3545
  return fn;
2519
3546
  }
2520
3547
  catch (error) {
@@ -2576,15 +3603,45 @@ class CompilerService extends BaseEval {
2576
3603
  return undefined;
2577
3604
  }
2578
3605
  /**
2579
- * Compiles the given expression into an asynchronous state callback function.
3606
+ * Compiles the given expression into an asynchronous state callback function with caching.
2580
3607
  * @param expression - The expression to compile.
2581
3608
  * @returns The compiled asynchronous state callback function.
2582
3609
  * @throws Error if there is an error during compilation.
2583
3610
  */
2584
3611
  compileAsync(expression) {
2585
3612
  try {
3613
+ const cacheKey = this.generateCacheKey(expression);
3614
+ // Check cache first
3615
+ const cached = this._compilationCache.get(cacheKey);
3616
+ if (cached?.async) {
3617
+ // Update access order for LRU
3618
+ this.updateAccessOrder(cacheKey);
3619
+ cached.accessCount++;
3620
+ // Check if entry is still fresh
3621
+ const age = performance.now() - cached.timestamp;
3622
+ if (age < this._cacheTTL) {
3623
+ return cached.async;
3624
+ }
3625
+ }
3626
+ // Compile fresh
2586
3627
  const ast = this.parse(expression);
2587
3628
  const fn = compileAsync(ast);
3629
+ if (fn) {
3630
+ // Cache the result
3631
+ const existingCache = this._compilationCache.get(cacheKey) || {
3632
+ timestamp: performance.now(),
3633
+ accessCount: 0
3634
+ };
3635
+ existingCache.async = fn;
3636
+ existingCache.timestamp = performance.now();
3637
+ existingCache.accessCount++;
3638
+ this._compilationCache.set(cacheKey, existingCache);
3639
+ this.updateAccessOrder(cacheKey);
3640
+ // Cleanup if cache is getting too large
3641
+ if (this._compilationCache.size > this._maxCacheSize * 1.2) {
3642
+ this.cleanupCache();
3643
+ }
3644
+ }
2588
3645
  return fn;
2589
3646
  }
2590
3647
  catch (error) {
@@ -2643,10 +3700,10 @@ class CompilerService extends BaseEval {
2643
3700
  }
2644
3701
  return undefined;
2645
3702
  }
2646
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: CompilerService, deps: [{ token: ParserService }, { token: EvalService }], target: i0.ɵɵFactoryTarget.Injectable }); }
2647
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: CompilerService, providedIn: 'root' }); }
3703
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: CompilerService, deps: [{ token: ParserService }, { token: EvalService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3704
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: CompilerService, providedIn: 'root' }); }
2648
3705
  }
2649
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: CompilerService, decorators: [{
3706
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: CompilerService, decorators: [{
2650
3707
  type: Injectable,
2651
3708
  args: [{
2652
3709
  providedIn: 'root'
@@ -2692,10 +3749,10 @@ class DiscoveryService extends BaseEval {
2692
3749
  }
2693
3750
  }
2694
3751
  }
2695
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: DiscoveryService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
2696
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: DiscoveryService, providedIn: 'root' }); }
3752
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DiscoveryService, deps: [{ token: ParserService }], target: i0.ɵɵFactoryTarget.Injectable }); }
3753
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DiscoveryService, providedIn: 'root' }); }
2697
3754
  }
2698
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: DiscoveryService, decorators: [{
3755
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DiscoveryService, decorators: [{
2699
3756
  type: Injectable,
2700
3757
  args: [{
2701
3758
  providedIn: 'root'
@@ -2706,5 +3763,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImpor
2706
3763
  * Generated bundle index. Do not edit.
2707
3764
  */
2708
3765
 
2709
- export { BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EvalContext, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Scope, ScopeRegistry, Stack, call, callAsync, compile, compileAsync, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
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 };
2710
3767
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map