ecma-evaluator 1.0.0 → 2.0.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.
@@ -1,4 +1,145 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_acorn__ from "acorn";
1
+ import { parse as external_acorn_parse } from "acorn";
2
+ import globals from "globals";
3
+ var mutableMethods = [
4
+ "Array.prototype.push",
5
+ "Array.prototype.pop",
6
+ "Array.prototype.shift",
7
+ "Array.prototype.unshift",
8
+ "Array.prototype.splice",
9
+ "Array.prototype.reverse",
10
+ "Array.prototype.sort",
11
+ "Array.prototype.fill",
12
+ "Array.prototype.copyWithin",
13
+ "Object.defineProperty",
14
+ "Object.defineProperties",
15
+ "Object.preventExtensions",
16
+ "Object.seal",
17
+ "Object.freeze",
18
+ "Object.setPrototypeOf",
19
+ "Object.assign",
20
+ "Reflect.set",
21
+ "Reflect.defineProperty",
22
+ "Reflect.deleteProperty",
23
+ "Reflect.setPrototypeOf",
24
+ "Reflect.preventExtensions",
25
+ "Set.prototype.add",
26
+ "Set.prototype.delete",
27
+ "Set.prototype.clear",
28
+ "WeakSet.prototype.add",
29
+ "WeakSet.prototype.delete",
30
+ "Map.prototype.set",
31
+ "Map.prototype.delete",
32
+ "Map.prototype.clear",
33
+ "WeakMap.prototype.set",
34
+ "WeakMap.prototype.delete",
35
+ "Date.prototype.setTime",
36
+ "Date.prototype.setMilliseconds",
37
+ "Date.prototype.setUTCSeconds",
38
+ "Date.prototype.setSeconds",
39
+ "Date.prototype.setMinutes",
40
+ "Date.prototype.setHours",
41
+ "Date.prototype.setDate",
42
+ "Date.prototype.setMonth",
43
+ "Date.prototype.setFullYear",
44
+ "Date.prototype.setYear",
45
+ "Date.prototype.setUTCMilliseconds",
46
+ "Date.prototype.setUTCMinutes",
47
+ "Date.prototype.setUTCHours",
48
+ "Date.prototype.setUTCDate",
49
+ "Date.prototype.setUTCMonth",
50
+ "Date.prototype.setUTCFullYear",
51
+ "RegExp.prototype.compile",
52
+ "Int8Array.prototype.set",
53
+ "Uint8Array.prototype.set",
54
+ "Uint8ClampedArray.prototype.set",
55
+ "Int16Array.prototype.set",
56
+ "Uint16Array.prototype.set",
57
+ "Int32Array.prototype.set",
58
+ "Uint32Array.prototype.set",
59
+ "Float32Array.prototype.set",
60
+ "Float64Array.prototype.set",
61
+ "BigInt64Array.prototype.set",
62
+ "BigUint64Array.prototype.set",
63
+ "Int8Array.prototype.fill",
64
+ "Uint8Array.prototype.fill",
65
+ "Uint8ClampedArray.prototype.fill",
66
+ "Int16Array.prototype.fill",
67
+ "Uint16Array.prototype.fill",
68
+ "Int32Array.prototype.fill",
69
+ "Uint32Array.prototype.fill",
70
+ "Float32Array.prototype.fill",
71
+ "Float64Array.prototype.fill",
72
+ "BigInt64Array.prototype.fill",
73
+ "BigUint64Array.prototype.fill",
74
+ "Int8Array.prototype.reverse",
75
+ "Uint8Array.prototype.reverse",
76
+ "Uint8ClampedArray.prototype.reverse",
77
+ "Int16Array.prototype.reverse",
78
+ "Uint16Array.prototype.reverse",
79
+ "Int32Array.prototype.reverse",
80
+ "Uint32Array.prototype.reverse",
81
+ "Float32Array.prototype.reverse",
82
+ "Float64Array.prototype.reverse",
83
+ "BigInt64Array.prototype.reverse",
84
+ "BigUint64Array.prototype.reverse",
85
+ "Int8Array.prototype.sort",
86
+ "Uint8Array.prototype.sort",
87
+ "Uint8ClampedArray.prototype.sort",
88
+ "Int16Array.prototype.sort",
89
+ "Uint16Array.prototype.sort",
90
+ "Int32Array.prototype.sort",
91
+ "Uint32Array.prototype.sort",
92
+ "Float32Array.prototype.sort",
93
+ "Float64Array.prototype.sort",
94
+ "BigInt64Array.prototype.sort",
95
+ "BigUint64Array.prototype.sort",
96
+ "Int8Array.prototype.copyWithin",
97
+ "Uint8Array.prototype.copyWithin",
98
+ "Uint8ClampedArray.prototype.copyWithin",
99
+ "Int16Array.prototype.copyWithin",
100
+ "Uint16Array.prototype.copyWithin",
101
+ "Int32Array.prototype.copyWithin",
102
+ "Uint32Array.prototype.copyWithin",
103
+ "Float32Array.prototype.copyWithin",
104
+ "Float64Array.prototype.copyWithin",
105
+ "BigInt64Array.prototype.copyWithin",
106
+ "BigUint64Array.prototype.copyWithin",
107
+ "ArrayBuffer.prototype.transfer",
108
+ "ArrayBuffer.prototype.transferToFixedLength",
109
+ "SharedArrayBuffer.prototype.grow",
110
+ "DataView.prototype.setInt8",
111
+ "DataView.prototype.setUint8",
112
+ "DataView.prototype.setInt16",
113
+ "DataView.prototype.setUint16",
114
+ "DataView.prototype.setInt32",
115
+ "DataView.prototype.setUint32",
116
+ "DataView.prototype.setFloat32",
117
+ "DataView.prototype.setFloat64",
118
+ "DataView.prototype.setBigInt64",
119
+ "DataView.prototype.setBigUint64",
120
+ "Promise.prototype.catch",
121
+ "Promise.prototype.finally",
122
+ "Generator.prototype.next",
123
+ "Generator.prototype.return",
124
+ "Generator.prototype.throw",
125
+ "AsyncGenerator.prototype.next",
126
+ "AsyncGenerator.prototype.return",
127
+ "AsyncGenerator.prototype.throw",
128
+ "Iterator.prototype.next",
129
+ "WeakRef.prototype.deref",
130
+ "FinalizationRegistry.prototype.register",
131
+ "FinalizationRegistry.prototype.unregister",
132
+ "URLSearchParams.prototype.append",
133
+ "URLSearchParams.prototype.delete",
134
+ "URLSearchParams.prototype.set",
135
+ "URLSearchParams.prototype.sort",
136
+ "FormData.prototype.append",
137
+ "FormData.prototype.delete",
138
+ "FormData.prototype.set",
139
+ "Headers.prototype.append",
140
+ "Headers.prototype.delete",
141
+ "Headers.prototype.set"
142
+ ];
2
143
  function _array_like_to_array(arr, len) {
3
144
  if (null == len || len > arr.length) len = arr.length;
4
145
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
@@ -40,62 +181,19 @@ function _create_class(Constructor, protoProps, staticProps) {
40
181
  if (staticProps) _defineProperties(Constructor, staticProps);
41
182
  return Constructor;
42
183
  }
43
- function _define_property(obj, key, value) {
44
- if (key in obj) Object.defineProperty(obj, key, {
45
- value: value,
46
- enumerable: true,
47
- configurable: true,
48
- writable: true
49
- });
50
- else obj[key] = value;
51
- return obj;
184
+ function _instanceof(left, right) {
185
+ if (null != right && "undefined" != typeof Symbol && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);
186
+ return left instanceof right;
52
187
  }
53
188
  function _iterable_to_array(iter) {
54
189
  if ("undefined" != typeof Symbol && null != iter[Symbol.iterator] || null != iter["@@iterator"]) return Array.from(iter);
55
190
  }
56
- function _iterable_to_array_limit(arr, i) {
57
- var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
58
- if (null == _i) return;
59
- var _arr = [];
60
- var _n = true;
61
- var _d = false;
62
- var _s, _e;
63
- try {
64
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
65
- _arr.push(_s.value);
66
- if (i && _arr.length === i) break;
67
- }
68
- } catch (err) {
69
- _d = true;
70
- _e = err;
71
- } finally{
72
- try {
73
- if (!_n && null != _i["return"]) _i["return"]();
74
- } finally{
75
- if (_d) throw _e;
76
- }
77
- }
78
- return _arr;
79
- }
80
191
  function _non_iterable_rest() {
81
192
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
82
193
  }
83
194
  function _non_iterable_spread() {
84
195
  throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
85
196
  }
86
- function _object_spread(target) {
87
- for(var i = 1; i < arguments.length; i++){
88
- var source = null != arguments[i] ? arguments[i] : {};
89
- var ownKeys = Object.keys(source);
90
- if ("function" == typeof Object.getOwnPropertySymbols) ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
91
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
92
- }));
93
- ownKeys.forEach(function(key) {
94
- _define_property(target, key, source[key]);
95
- });
96
- }
97
- return target;
98
- }
99
197
  function _set_prototype_of(o, p) {
100
198
  _set_prototype_of = Object.setPrototypeOf || function(o, p) {
101
199
  o.__proto__ = p;
@@ -103,8 +201,8 @@ function _set_prototype_of(o, p) {
103
201
  };
104
202
  return _set_prototype_of(o, p);
105
203
  }
106
- function _sliced_to_array(arr, i) {
107
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
204
+ function _to_array(arr) {
205
+ return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
108
206
  }
109
207
  function _to_consumable_array(arr) {
110
208
  return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
@@ -128,132 +226,178 @@ function _is_native_reflect_construct() {
128
226
  return !!result;
129
227
  })();
130
228
  }
131
- var typeArrayConstructors = [
132
- Int8Array,
133
- Uint8Array,
134
- Uint8ClampedArray,
135
- Int16Array,
136
- Uint16Array,
137
- Int32Array,
138
- Uint32Array,
139
- Float32Array,
140
- Float64Array,
141
- globalThis.BigInt64Array,
142
- globalThis.BigUint64Array
143
- ].filter(Boolean);
144
- var mutableMethods = new Set([
145
- Array.prototype.push,
146
- Array.prototype.pop,
147
- Array.prototype.shift,
148
- Array.prototype.unshift,
149
- Array.prototype.splice,
150
- Array.prototype.reverse,
151
- Array.prototype.sort,
152
- Array.prototype.fill,
153
- Array.prototype.copyWithin,
154
- ArrayBuffer.prototype.slice,
155
- DataView.prototype.setInt8,
156
- DataView.prototype.setUint8,
157
- DataView.prototype.setInt16,
158
- DataView.prototype.setUint16,
159
- DataView.prototype.setInt32,
160
- DataView.prototype.setUint32,
161
- DataView.prototype.setFloat32,
162
- DataView.prototype.setFloat64
163
- ].concat(_to_consumable_array(typeArrayConstructors.flatMap(function(TypedArray) {
164
- return [
165
- TypedArray.prototype.set,
166
- TypedArray.prototype.fill,
167
- TypedArray.prototype.copyWithin,
168
- TypedArray.prototype.reverse,
169
- TypedArray.prototype.sort
170
- ];
171
- })), [
172
- Object.freeze,
173
- Object.defineProperty,
174
- Object.defineProperties,
175
- Object.preventExtensions,
176
- Object.setPrototypeOf,
177
- Object.assign,
178
- Set.prototype.add,
179
- Set.prototype["delete"],
180
- Set.prototype.clear,
181
- WeakSet.prototype.add,
182
- WeakSet.prototype["delete"],
183
- Map.prototype.set,
184
- Map.prototype["delete"],
185
- Map.prototype.clear,
186
- WeakMap.prototype.set,
187
- WeakMap.prototype["delete"],
188
- Date.prototype.setMilliseconds,
189
- Date.prototype.setMinutes,
190
- Date.prototype.setHours,
191
- Date.prototype.setDate,
192
- Date.prototype.setFullYear,
193
- Date.prototype.setUTCMinutes,
194
- Date.prototype.setUTCHours,
195
- Date.prototype.setUTCDate,
196
- Date.prototype.setUTCFullYear,
197
- Date.prototype.setTime
198
- ]));
229
+ var ERROR_MESSAGES = {
230
+ DELETE_NOT_SUPPORTED: "Delete operator is not allow",
231
+ MUTABLE_METHOD: "Mutable method is not allowed",
232
+ NEW_FUNCTION_NOT_ALLOWED: "Cannot use new with Function constructor",
233
+ NOT_A_FUNCTION: "is not a function",
234
+ PROPERTY_READ_ERROR: "Cannot read property",
235
+ VARIABLE_NOT_DEFINED: "is not defined",
236
+ FUNCTION_CONSTRUCTOR_NOT_ALLOWED: "Function constructor is not allowed",
237
+ THIS_NOT_ALLOWED: "'this' keyword is not allowed",
238
+ NOT_A_VALID_SYNTAX: "is not a valid syntax"
239
+ };
240
+ var BINARY_OPERATION_MAP = {
241
+ "+": function(a, b) {
242
+ return a + b;
243
+ },
244
+ "-": function(a, b) {
245
+ return a - b;
246
+ },
247
+ "*": function(a, b) {
248
+ return a * b;
249
+ },
250
+ "**": function(a, b) {
251
+ return Math.pow(a, b);
252
+ },
253
+ "==": function(a, b) {
254
+ return a == b;
255
+ },
256
+ "===": function(a, b) {
257
+ return a === b;
258
+ },
259
+ "!=": function(a, b) {
260
+ return a != b;
261
+ },
262
+ "!==": function(a, b) {
263
+ return a !== b;
264
+ },
265
+ ">": function(a, b) {
266
+ return a > b;
267
+ },
268
+ ">=": function(a, b) {
269
+ return a >= b;
270
+ },
271
+ "<": function(a, b) {
272
+ return a < b;
273
+ },
274
+ "<=": function(a, b) {
275
+ return a <= b;
276
+ },
277
+ "%": function(a, b) {
278
+ return a % b;
279
+ },
280
+ "/": function(a, b) {
281
+ return a / b;
282
+ },
283
+ "|": function(a, b) {
284
+ return a | b;
285
+ },
286
+ "&": function(a, b) {
287
+ return a & b;
288
+ },
289
+ "^": function(a, b) {
290
+ return a ^ b;
291
+ },
292
+ "<<": function(a, b) {
293
+ return a << b;
294
+ },
295
+ ">>": function(a, b) {
296
+ return a >> b;
297
+ },
298
+ ">>>": function(a, b) {
299
+ return a >>> b;
300
+ },
301
+ in: function(a, b) {
302
+ return a in b;
303
+ },
304
+ instanceof: function(a, b) {
305
+ return _instanceof(a, b);
306
+ }
307
+ };
308
+ function createGlobalScope() {
309
+ var scope = Object.create(null);
310
+ var builtin = globals.builtin;
311
+ Object.keys(builtin).forEach(function(key) {
312
+ if (key in globalThis && "eval" !== key && "globalThis" !== key) {
313
+ var isWritable = builtin[key];
314
+ Object.defineProperty(scope, key, {
315
+ value: globalThis[key],
316
+ writable: isWritable,
317
+ enumerable: false,
318
+ configurable: false
319
+ });
320
+ }
321
+ });
322
+ Object.defineProperty(scope, "globalThis", {
323
+ value: scope,
324
+ writable: false,
325
+ enumerable: false,
326
+ configurable: false
327
+ });
328
+ return scope;
329
+ }
330
+ var getMutableMethods = function() {
331
+ var MUTABLE_METHODS = null;
332
+ return function() {
333
+ if (MUTABLE_METHODS) return MUTABLE_METHODS;
334
+ var set = new Set();
335
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
336
+ try {
337
+ for(var _iterator = mutableMethods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
338
+ var path = _step.value;
339
+ var _path_split = _to_array(path.split(".")), object = _path_split[0], properties = _path_split.slice(1);
340
+ var current = globalThis[object];
341
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = void 0;
342
+ try {
343
+ for(var _iterator1 = properties[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
344
+ var prop = _step1.value;
345
+ if (current && Object.hasOwn(current, prop)) current = current[prop];
346
+ else {
347
+ current = null;
348
+ break;
349
+ }
350
+ }
351
+ } catch (err) {
352
+ _didIteratorError1 = true;
353
+ _iteratorError1 = err;
354
+ } finally{
355
+ try {
356
+ if (!_iteratorNormalCompletion1 && null != _iterator1.return) _iterator1.return();
357
+ } finally{
358
+ if (_didIteratorError1) throw _iteratorError1;
359
+ }
360
+ }
361
+ if ("function" == typeof current) set.add(current);
362
+ }
363
+ } catch (err) {
364
+ _didIteratorError = true;
365
+ _iteratorError = err;
366
+ } finally{
367
+ try {
368
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
369
+ } finally{
370
+ if (_didIteratorError) throw _iteratorError;
371
+ }
372
+ }
373
+ MUTABLE_METHODS = set;
374
+ return MUTABLE_METHODS;
375
+ };
376
+ }();
199
377
  var Evaluator_Evaluator = /*#__PURE__*/ function() {
200
378
  "use strict";
201
379
  function Evaluator() {
202
380
  var variables = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
203
381
  _class_call_check(this, Evaluator);
204
- var globalScope = Object.assign(Object.create(null), _object_spread({
205
- Infinity: 1 / 0,
206
- null: null,
207
- undefined: void 0,
208
- NaN: Number.NaN,
209
- isNaN: Number.isNaN,
210
- isFinite: Number.isFinite,
211
- parseFloat: Number.parseFloat,
212
- parseInt: Number.parseInt,
213
- encodeURI: globalThis.encodeURI,
214
- encodeURIComponent: globalThis.encodeURIComponent,
215
- decodeURI: globalThis.decodeURI,
216
- decodeURIComponent: globalThis.decodeURIComponent,
217
- Number: Number,
218
- String: String,
219
- Boolean: Boolean,
220
- BigInt: globalThis.BigInt,
221
- Symbol: globalThis.Symbol,
222
- Object: Object,
223
- Array: Array,
224
- Set: Set,
225
- WeakSet: WeakSet,
226
- Map: Map,
227
- WeakMap: WeakMap,
228
- Math: Math,
229
- JSON: JSON,
230
- Date: Date,
231
- RegExp: RegExp,
232
- Error: Error,
233
- EvalError: EvalError,
234
- RangeError: RangeError,
235
- ReferenceError: ReferenceError,
236
- SyntaxError: SyntaxError,
237
- TypeError: TypeError,
238
- URIError: URIError,
239
- Promise: Promise
240
- }, typeArrayConstructors.reduce(function(acc, obj) {
241
- acc[obj.name] = obj;
242
- return acc;
243
- }, {})));
244
382
  this.scopes = [
245
383
  variables,
246
- globalScope
384
+ createGlobalScope()
247
385
  ];
386
+ this.source = void 0;
248
387
  }
249
388
  _create_class(Evaluator, [
250
389
  {
251
390
  key: "evaluate",
252
391
  value: function(expression) {
253
- var ast = __WEBPACK_EXTERNAL_MODULE_acorn__.parse(expression, {
392
+ this.source = expression;
393
+ var ast = external_acorn_parse(expression, {
254
394
  ecmaVersion: "latest"
255
395
  });
256
- return this.execute(ast.body);
396
+ try {
397
+ return this.execute(ast.body);
398
+ } finally{
399
+ this.source = void 0;
400
+ }
257
401
  }
258
402
  },
259
403
  {
@@ -271,7 +415,7 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
271
415
  _iteratorError = err;
272
416
  } finally{
273
417
  try {
274
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
418
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
275
419
  } finally{
276
420
  if (_didIteratorError) throw _iteratorError;
277
421
  }
@@ -302,6 +446,10 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
302
446
  return this.handleObjectExpression(node);
303
447
  case "ArrayExpression":
304
448
  return this.handleArrayExpression(node);
449
+ case "SpreadElement":
450
+ return this.handleSpreadElement(node);
451
+ case "ObjectExpression":
452
+ return this.handleObjectExpression(node);
305
453
  case "ArrowFunctionExpression":
306
454
  return this.handleArrowFunctionExpression(node);
307
455
  case "CallExpression":
@@ -310,71 +458,33 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
310
458
  return this.visit(node.test) ? this.visit(node.consequent) : this.visit(node.alternate);
311
459
  case "NewExpression":
312
460
  if ("Identifier" !== node.callee.type) throw new Error("Unsupported callee type '".concat(node.callee.type, "' in new expression"));
313
- if ("Function" === node.callee.name) throw new Error("Cannot use new with Function constructor");
461
+ if ("Function" === node.callee.name) throw new Error(ERROR_MESSAGES.NEW_FUNCTION_NOT_ALLOWED);
314
462
  var Constructor = this.visit(node.callee);
315
- var args = node["arguments"].map(function(arg) {
463
+ var args = node.arguments.length ? node.arguments.map(function(arg) {
316
464
  return _this.visit(arg);
317
- });
465
+ }) : [];
318
466
  return _construct(Constructor, _to_consumable_array(args));
319
467
  case "ChainExpression":
320
468
  return this.visit(node.expression);
321
469
  case "TemplateLiteral":
322
470
  return this.handleTemplateLiteral(node);
471
+ case "ThisExpression":
472
+ throw new Error(ERROR_MESSAGES.THIS_NOT_ALLOWED);
323
473
  default:
324
- throw new Error("Unsupported node type: ".concat(node.type));
474
+ var content = this.source.slice(node.start, node.end);
475
+ if (content.length > 20) content = content.slice(0, 17) + "...";
476
+ throw new Error("'".concat(content, "'") + " " + ERROR_MESSAGES.NOT_A_VALID_SYNTAX);
325
477
  }
326
478
  }
327
479
  },
328
480
  {
329
481
  key: "handleBinaryExpression",
330
482
  value: function(node) {
331
- switch(node.operator){
332
- case "+":
333
- return this.visit(node.left) + this.visit(node.right);
334
- case "-":
335
- return this.visit(node.left) - this.visit(node.right);
336
- case "*":
337
- return this.visit(node.left) * this.visit(node.right);
338
- case "**":
339
- return Math.pow(this.visit(node.left), this.visit(node.right));
340
- case "/":
341
- var left = this.visit(node.left);
342
- var right = this.visit(node.right);
343
- if (0 === right) throw new Error("Division by zero");
344
- return left / right;
345
- case "==":
346
- return this.visit(node.left) == this.visit(node.right);
347
- case "===":
348
- return this.visit(node.left) === this.visit(node.right);
349
- case "!=":
350
- return this.visit(node.left) != this.visit(node.right);
351
- case "!==":
352
- return this.visit(node.left) !== this.visit(node.right);
353
- case ">":
354
- return this.visit(node.left) > this.visit(node.right);
355
- case ">=":
356
- return this.visit(node.left) >= this.visit(node.right);
357
- case "<":
358
- return this.visit(node.left) < this.visit(node.right);
359
- case "<=":
360
- return this.visit(node.left) <= this.visit(node.right);
361
- case "%":
362
- return this.visit(node.left) % this.visit(node.right);
363
- case "&":
364
- return this.visit(node.left) & this.visit(node.right);
365
- case "|":
366
- return this.visit(node.left) | this.visit(node.right);
367
- case "^":
368
- return this.visit(node.left) ^ this.visit(node.right);
369
- case "<<":
370
- return this.visit(node.left) << this.visit(node.right);
371
- case ">>":
372
- return this.visit(node.left) >> this.visit(node.right);
373
- case ">>>":
374
- return this.visit(node.left) >>> this.visit(node.right);
375
- default:
376
- throw new Error("Unsupported operator: ".concat(node.operator));
377
- }
483
+ var op = node.operator;
484
+ var left = this.visit(node.left);
485
+ var right = this.visit(node.right);
486
+ if (BINARY_OPERATION_MAP.hasOwnProperty(op)) return BINARY_OPERATION_MAP[op](left, right);
487
+ throw new Error("Unsupported operator: ".concat(node.operator));
378
488
  }
379
489
  },
380
490
  {
@@ -382,12 +492,14 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
382
492
  value: function(node) {
383
493
  switch(node.operator){
384
494
  case "&&":
385
- return this.visit(node.left) && this.visit(node.right);
495
+ var left = this.visit(node.left);
496
+ return left ? this.visit(node.right) : left;
386
497
  case "||":
387
- return this.visit(node.left) || this.visit(node.right);
498
+ var left1 = this.visit(node.left);
499
+ return left1 ? left1 : this.visit(node.right);
388
500
  case "??":
389
- var left = this.visit(node.left);
390
- return null != left ? left : this.visit(node.right);
501
+ var left2 = this.visit(node.left);
502
+ return null != left2 ? left2 : this.visit(node.right);
391
503
  default:
392
504
  throw new Error("Unsupported logical operator: ".concat(node.operator));
393
505
  }
@@ -410,7 +522,7 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
410
522
  case "void":
411
523
  return void this.visit(node.argument);
412
524
  case "delete":
413
- throw new Error("Delete operator is mutable and not supported");
525
+ throw new Error(ERROR_MESSAGES.DELETE_NOT_SUPPORTED);
414
526
  default:
415
527
  throw new Error("Unsupported unary operator: ".concat(node.operator));
416
528
  }
@@ -431,28 +543,25 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
431
543
  _iteratorError = err;
432
544
  } finally{
433
545
  try {
434
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
546
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
435
547
  } finally{
436
548
  if (_didIteratorError) throw _iteratorError;
437
549
  }
438
550
  }
439
- throw new ReferenceError("".concat(name, " is not defined"));
551
+ throw new ReferenceError("".concat(name, " ").concat(ERROR_MESSAGES.VARIABLE_NOT_DEFINED));
440
552
  }
441
553
  },
442
554
  {
443
555
  key: "handleMemberExpression",
444
556
  value: function(node) {
445
557
  var object = this.visit(node.object);
446
- var property = "Identifier" !== node.property.type || node.computed ? this.visit(node.property) : node.property.name;
558
+ var isStaticProperty = "Identifier" === node.property.type && !node.computed;
559
+ var property = isStaticProperty ? node.property.name : this.visit(node.property);
447
560
  if (null == object) {
448
561
  if (node.optional) return;
449
- throw new TypeError("Cannot read property '".concat(property, "' of ").concat(object));
562
+ throw new TypeError("".concat(ERROR_MESSAGES.PROPERTY_READ_ERROR, " '").concat(property, "' of ").concat(object));
450
563
  }
451
- if (Object.hasOwn(object, property)) return object[property];
452
- var prototypeValue = object[property];
453
- if (mutableMethods.has(prototypeValue)) throw new Error("Cannot call mutable prototype method: ".concat(property));
454
- if ("function" == typeof prototypeValue) return prototypeValue.bind(object);
455
- return prototypeValue;
564
+ return object[property];
456
565
  }
457
566
  },
458
567
  {
@@ -463,6 +572,10 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
463
572
  try {
464
573
  for(var _iterator = node.properties[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
465
574
  var prop = _step.value;
575
+ if ("SpreadElement" === prop.type) {
576
+ Object.assign(obj, this.visit(prop.argument));
577
+ continue;
578
+ }
466
579
  var key = prop.key.name || prop.key.value;
467
580
  var value = this.visit(prop.value);
468
581
  obj[key] = value;
@@ -472,7 +585,7 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
472
585
  _iteratorError = err;
473
586
  } finally{
474
587
  try {
475
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
588
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
476
589
  } finally{
477
590
  if (_didIteratorError) throw _iteratorError;
478
591
  }
@@ -483,10 +596,22 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
483
596
  {
484
597
  key: "handleArrayExpression",
485
598
  value: function(node) {
486
- var _this = this;
487
- return node.elements.map(function(element) {
488
- return _this.visit(element);
489
- });
599
+ var result = [];
600
+ for(var i = 0; i < node.elements.length; i++){
601
+ var element = node.elements.at(i);
602
+ var value = this.visit(element);
603
+ if ("SpreadElement" === element.type) {
604
+ var _result;
605
+ (_result = result).push.apply(_result, _to_consumable_array(value));
606
+ } else result.push(value);
607
+ }
608
+ return result;
609
+ }
610
+ },
611
+ {
612
+ key: "handleSpreadElement",
613
+ value: function(node) {
614
+ return this.visit(node.argument);
490
615
  }
491
616
  },
492
617
  {
@@ -496,22 +621,8 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
496
621
  return function() {
497
622
  for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
498
623
  var newScope = {};
499
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
500
- try {
501
- for(var _iterator = node.params.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
502
- var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], param = _step_value[1];
503
- newScope[param.name] = args[index];
504
- }
505
- } catch (err) {
506
- _didIteratorError = true;
507
- _iteratorError = err;
508
- } finally{
509
- try {
510
- if (!_iteratorNormalCompletion && null != _iterator["return"]) _iterator["return"]();
511
- } finally{
512
- if (_didIteratorError) throw _iteratorError;
513
- }
514
- }
624
+ var paramCount = node.params.length;
625
+ for(var i = 0; i < paramCount; i++)newScope[node.params[i].name] = args[i];
515
626
  _this.scopes.unshift(newScope);
516
627
  var result = _this.visit(node.body);
517
628
  _this.scopes.shift();
@@ -523,73 +634,269 @@ var Evaluator_Evaluator = /*#__PURE__*/ function() {
523
634
  key: "handleCallExpression",
524
635
  value: function(node) {
525
636
  var _this = this;
526
- var calledString = this.getNodeString(node.callee);
637
+ if ("MemberExpression" === node.callee.type) {
638
+ var object = this.visit(node.callee.object);
639
+ if (getMutableMethods().has(object)) throw new Error(ERROR_MESSAGES.MUTABLE_METHOD);
640
+ }
641
+ var calledString = getNodeString(node.callee);
527
642
  var func = this.visit(node.callee);
528
643
  if ("function" != typeof func) {
529
644
  var isOptional = node.optional || node.callee.optional;
530
645
  if (null == func && isOptional) return;
531
- throw new TypeError("".concat(calledString, " is not a function"));
646
+ throw new TypeError("".concat(calledString, " ").concat(ERROR_MESSAGES.NOT_A_FUNCTION));
532
647
  }
533
- var args = node["arguments"].map(function(arg) {
534
- return _this.visit(arg);
535
- });
536
- return func.apply(void 0, _to_consumable_array(args));
648
+ if (func === Function) throw new Error(ERROR_MESSAGES.FUNCTION_CONSTRUCTOR_NOT_ALLOWED);
649
+ var args = function() {
650
+ if (0 === node.arguments.length) return [];
651
+ var result = [];
652
+ for(var i = 0; i < node.arguments.length; i++){
653
+ var element = node.arguments.at(i);
654
+ var value = _this.visit(element);
655
+ if ("SpreadElement" === element.type) {
656
+ var _result;
657
+ (_result = result).push.apply(_result, _to_consumable_array(value));
658
+ } else result.push(value);
659
+ }
660
+ return result;
661
+ }();
662
+ if (getMutableMethods().has(func)) throw new Error(ERROR_MESSAGES.MUTABLE_METHOD);
663
+ var target = "MemberExpression" === node.callee.type ? this.visit(node.callee.object) : null;
664
+ return func.apply(target, args);
537
665
  }
538
666
  },
539
667
  {
540
668
  key: "handleTemplateLiteral",
541
669
  value: function(node) {
542
- var _this = this;
543
- return node.quasis.concat(node.expressions).filter(Boolean).sort(function(a, b) {
544
- return a.start - b.start;
545
- }).map(function(node) {
546
- if ("TemplateElement" === node.type) return node.value.raw;
547
- return _this.visit(node);
548
- }).join("");
670
+ var result = "";
671
+ var expressionCount = node.expressions.length;
672
+ for(var i = 0; i < node.quasis.length; i++){
673
+ result += node.quasis[i].value.raw;
674
+ if (i < expressionCount) result += this.visit(node.expressions[i]);
675
+ }
676
+ return result;
549
677
  }
550
- },
678
+ }
679
+ ], [
551
680
  {
552
- key: "getNodeString",
553
- value: function(node) {
554
- switch(node.type){
555
- case "Identifier":
556
- return node.name;
557
- case "Literal":
558
- return node.raw;
559
- case "ArrayExpression":
560
- return "(array)";
561
- case "ObjectExpression":
562
- return "(object)";
563
- case "MemberExpression":
564
- var accessor = this.getNodeString(node.object);
565
- if (node.computed) accessor += "[".concat(this.getNodeString(node.property), "]");
566
- else accessor += ".".concat(this.getNodeString(node.property));
567
- return accessor;
568
- default:
569
- return null;
570
- }
681
+ key: "evaluate",
682
+ value: function(expression, context) {
683
+ var evaluator = new Evaluator(context);
684
+ return evaluator.evaluate(expression);
571
685
  }
572
686
  }
573
687
  ]);
574
688
  return Evaluator;
575
689
  }();
576
- var TEMPLATE_EXPRESSION_REGEX = /\$\{\{((?:[^{}]|{[^{}]*})+)\}\}/g;
577
- function evaluatorExpression(expression, context) {
578
- var evaluator = new Evaluator_Evaluator(context);
579
- return evaluator.evaluate(expression);
690
+ function getNodeString(node) {
691
+ switch(node.type){
692
+ case "Identifier":
693
+ return node.name;
694
+ case "Literal":
695
+ return node.raw;
696
+ case "ArrayExpression":
697
+ return "[".concat(node.elements.map(function(child) {
698
+ return getNodeString(child);
699
+ }).join(","), "]");
700
+ case "ObjectExpression":
701
+ if (0 === node.properties.length) return "{}";
702
+ return "{(intermediate value)}";
703
+ case "MemberExpression":
704
+ var objectStr = getNodeString(node.object);
705
+ var propertyStr = getNodeString(node.property);
706
+ if (node.computed) return "".concat(objectStr, "[").concat(propertyStr, "]");
707
+ return "".concat(objectStr, ".").concat(propertyStr);
708
+ default:
709
+ return null;
710
+ }
711
+ }
712
+ function TemplateParser_class_call_check(instance, Constructor) {
713
+ if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
714
+ }
715
+ function TemplateParser_defineProperties(target, props) {
716
+ for(var i = 0; i < props.length; i++){
717
+ var descriptor = props[i];
718
+ descriptor.enumerable = descriptor.enumerable || false;
719
+ descriptor.configurable = true;
720
+ if ("value" in descriptor) descriptor.writable = true;
721
+ Object.defineProperty(target, descriptor.key, descriptor);
722
+ }
580
723
  }
581
- function evaluatorTemplate(template, context) {
582
- var evaluator = new Evaluator_Evaluator(context);
583
- return template.replace(TEMPLATE_EXPRESSION_REGEX, function(match, expression) {
724
+ function TemplateParser_create_class(Constructor, protoProps, staticProps) {
725
+ if (protoProps) TemplateParser_defineProperties(Constructor.prototype, protoProps);
726
+ if (staticProps) TemplateParser_defineProperties(Constructor, staticProps);
727
+ return Constructor;
728
+ }
729
+ var TemplateParser_TemplateParser = /*#__PURE__*/ function() {
730
+ "use strict";
731
+ function TemplateParser() {
732
+ var options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
733
+ TemplateParser_class_call_check(this, TemplateParser);
734
+ this.exprStart = options.expressionStart || "{{";
735
+ this.exprEnd = options.expressionEnd || "}}";
736
+ this.startLen = this.exprStart.length;
737
+ this.endLen = this.exprEnd.length;
738
+ this.preserveWhitespace = true === options.preserveWhitespace;
739
+ }
740
+ TemplateParser_create_class(TemplateParser, [
741
+ {
742
+ key: "parse",
743
+ value: function(template) {
744
+ if ("string" != typeof template) throw new TypeError("模板必须是字符串");
745
+ var tokens = [];
746
+ var length = template.length;
747
+ var state = "TEXT";
748
+ var buffer = "";
749
+ var exprStartPos = 0;
750
+ var pos = 0;
751
+ while(pos < length){
752
+ var char = template[pos];
753
+ var nextChar = template[pos + 1];
754
+ switch(state){
755
+ case "TEXT":
756
+ if (this._isMatch(pos, template, this.exprStart)) {
757
+ if (buffer.length > 0) {
758
+ tokens.push({
759
+ type: "text",
760
+ value: buffer,
761
+ start: pos - buffer.length,
762
+ end: pos
763
+ });
764
+ buffer = "";
765
+ }
766
+ state = "EXPR";
767
+ exprStartPos = pos;
768
+ pos += this.startLen;
769
+ continue;
770
+ }
771
+ buffer += char;
772
+ break;
773
+ case "EXPR":
774
+ if ("'" === char) state = "STRING_SQ";
775
+ else if ('"' === char) state = "STRING_DQ";
776
+ else if ("`" === char) state = "TEMPLATE";
777
+ else if ("\\" === char) state = "'" === nextChar ? "ESCAPE_SQ" : '"' === nextChar ? "ESCAPE_DQ" : "`" === nextChar ? "ESCAPE_TEMPLATE" : "ESCAPE_EXPR";
778
+ else if (this._isMatch(pos, template, this.exprEnd)) {
779
+ var exprValue = this.preserveWhitespace ? buffer : buffer.trim();
780
+ if (exprValue.length > 0) tokens.push({
781
+ type: "expression",
782
+ value: exprValue,
783
+ start: exprStartPos,
784
+ end: pos + this.endLen,
785
+ contentStart: exprStartPos + this.startLen,
786
+ contentEnd: pos
787
+ });
788
+ buffer = "";
789
+ state = "TEXT";
790
+ pos += this.endLen;
791
+ continue;
792
+ }
793
+ buffer += char;
794
+ break;
795
+ case "STRING_SQ":
796
+ if ("\\" === char) state = "ESCAPE_SQ";
797
+ else if ("'" === char) state = "EXPR";
798
+ buffer += char;
799
+ break;
800
+ case "STRING_DQ":
801
+ if ("\\" === char) state = "ESCAPE_DQ";
802
+ else if ('"' === char) state = "EXPR";
803
+ buffer += char;
804
+ break;
805
+ case "TEMPLATE":
806
+ if ("\\" === char) state = "ESCAPE_TEMPLATE";
807
+ else if ("`" === char) state = "EXPR";
808
+ buffer += char;
809
+ break;
810
+ case "ESCAPE_SQ":
811
+ buffer += char;
812
+ state = "STRING_SQ";
813
+ break;
814
+ case "ESCAPE_DQ":
815
+ buffer += char;
816
+ state = "STRING_DQ";
817
+ break;
818
+ case "ESCAPE_TEMPLATE":
819
+ buffer += char;
820
+ state = "TEMPLATE";
821
+ break;
822
+ case "ESCAPE_EXPR":
823
+ buffer += char;
824
+ state = "EXPR";
825
+ break;
826
+ }
827
+ pos++;
828
+ }
829
+ if (buffer.length > 0) if ("TEXT" === state) tokens.push({
830
+ type: "text",
831
+ value: buffer,
832
+ start: pos - buffer.length,
833
+ end: pos
834
+ });
835
+ else {
836
+ var incompleteExpr = this.exprStart + buffer;
837
+ tokens.push({
838
+ type: "text",
839
+ value: incompleteExpr,
840
+ start: exprStartPos,
841
+ end: pos
842
+ });
843
+ console.warn("警告:在位置 ".concat(exprStartPos, " 开始的表达式未正确结束"));
844
+ }
845
+ return tokens;
846
+ }
847
+ },
848
+ {
849
+ key: "_isMatch",
850
+ value: function(pos, template, sequence) {
851
+ if (pos + sequence.length > template.length) return false;
852
+ for(var i = 0; i < sequence.length; i++)if (template[pos + i] !== sequence[i]) return false;
853
+ return true;
854
+ }
855
+ }
856
+ ], [
857
+ {
858
+ key: "parse",
859
+ value: function(template, options) {
860
+ var parser = new TemplateParser(options);
861
+ return parser.parse(template);
862
+ }
863
+ }
864
+ ]);
865
+ return TemplateParser;
866
+ }();
867
+ function src_instanceof(left, right) {
868
+ if (null != right && "undefined" != typeof Symbol && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);
869
+ return left instanceof right;
870
+ }
871
+ function evalExpression(expression, context) {
872
+ return Evaluator_Evaluator.evaluate(expression, context);
873
+ }
874
+ function evalTemplate(template, context, templateParserOptions) {
875
+ var result = "";
876
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
877
+ try {
878
+ for(var _iterator = TemplateParser_TemplateParser.parse(template, templateParserOptions)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
879
+ var token = _step.value;
880
+ if ("text" === token.type) result += token.value;
881
+ else if ("expression" === token.type) try {
882
+ result += Evaluator_Evaluator.evaluate(token.value, context);
883
+ } catch (error) {
884
+ if (src_instanceof(error, ReferenceError) && error.message.endsWith("is not defined")) result += "undefined";
885
+ else throw error;
886
+ }
887
+ }
888
+ } catch (err) {
889
+ _didIteratorError = true;
890
+ _iteratorError = err;
891
+ } finally{
584
892
  try {
585
- var value = evaluator.evaluate(expression.trim());
586
- return String(value);
587
- } catch (error) {
588
- if (error instanceof ReferenceError && error.message.endsWith("is not defined")) return "";
589
- throw error;
893
+ if (!_iteratorNormalCompletion && null != _iterator.return) _iterator.return();
894
+ } finally{
895
+ if (_didIteratorError) throw _iteratorError;
590
896
  }
591
- });
897
+ }
898
+ return result;
592
899
  }
593
- export { evaluatorExpression, evaluatorTemplate };
900
+ export { Evaluator_Evaluator as Evaluator, evalExpression, evalTemplate };
594
901
 
595
902
  //# sourceMappingURL=index.mjs.map