-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
599 lines (541 loc) · 21.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
import { ArrowExpression } from '@jsep-plugin/arrow';
import { AssignmentExpression, UpdateExpression } from '@jsep-plugin/assignment';
import { AwaitExpression } from '@jsep-plugin/async-await';
import { NewExpression } from '@jsep-plugin/new';
import { ObjectExpression, Property } from '@jsep-plugin/object';
import { SpreadElement } from '@jsep-plugin/spread';
import { TaggedTemplateExpression, TemplateLiteral } from '@jsep-plugin/template';
import jsep from 'jsep';
/**
* Evaluation code from JSEP project, under MIT License.
* Copyright (c) 2013 Stephen Oney, http://jsep.from.so/
*/
export declare type Context = Record<string, unknown>;
export declare type operand = any;
export declare type unaryCallback = (a: operand) => operand;
export declare type binaryCallback = (a: operand, b: operand) => operand;
export declare type assignCallback = (obj: Record<string, operand>, key: string, val: operand) => operand;
export declare type evaluatorCallback<T extends AnyExpression> = (this: ExpressionEval, node: T, context?: Context) => unknown;
export type AnyExpression = jsep.Expression;
export type JseEvalPlugin = Partial<jsep.IPlugin> & {
initEval?: (this: typeof ExpressionEval, jseEval: typeof ExpressionEval) => void;
}
export default class ExpressionEval {
static jsep = jsep;
static parse = jsep;
static evaluate = ExpressionEval.eval;
static evaluators: Record<string, evaluatorCallback<AnyExpression>> = {
'ArrayExpression': ExpressionEval.prototype.evalArrayExpression,
'LogicalExpression': ExpressionEval.prototype.evalBinaryExpression,
'BinaryExpression': ExpressionEval.prototype.evalBinaryExpression,
'CallExpression': ExpressionEval.prototype.evalCallExpression,
'Compound': ExpressionEval.prototype.evalCompoundExpression,
'ConditionalExpression': ExpressionEval.prototype.evalConditionalExpression,
'Identifier': ExpressionEval.prototype.evalIdentifier,
'Literal': ExpressionEval.evalLiteral,
'OptionalMemberExpression': ExpressionEval.prototype.evalMemberExpression, // acorn uses this
'MemberExpression': ExpressionEval.prototype.evalMemberExpression,
'ThisExpression': ExpressionEval.prototype.evalThisExpression,
'UnaryExpression': ExpressionEval.prototype.evalUnaryExpression,
'ArrowFunctionExpression': ExpressionEval.prototype.evalArrowFunctionExpression,
'AssignmentExpression': ExpressionEval.prototype.evalAssignmentExpression,
'UpdateExpression': ExpressionEval.prototype.evalUpdateExpression,
'AwaitExpression': ExpressionEval.prototype.evalAwaitExpression,
'NewExpression': ExpressionEval.prototype.evalNewExpression,
'ObjectExpression': ExpressionEval.prototype.evalObjectExpression,
'SpreadElement': ExpressionEval.prototype.evalSpreadElement,
'TaggedTemplateExpression': ExpressionEval.prototype.evalTaggedTemplateExpression,
'TemplateLiteral': ExpressionEval.prototype.evalTemplateLiteral,
};
// Default operator precedence from https://github.com/EricSmekens/jsep/blob/master/src/jsep.js#L55
static DEFAULT_PRECEDENCE: Record<string, number> = {
'||': 1,
'&&': 2,
'|': 3,
'^': 4,
'&': 5,
'==': 6,
'!=': 6,
'===': 6,
'!==': 6,
'<': 7,
'>': 7,
'<=': 7,
'>=': 7,
'<<': 8,
'>>': 8,
'>>>': 8,
'+': 9,
'-': 9,
'*': 10,
'/': 10,
'%': 10
};
static binops: Record<string, binaryCallback> = {
'||': function (a, b) { return a || b; },
'&&': function (a, b) { return a && b; },
'|': function (a, b) { return a | b; },
'^': function (a, b) { return a ^ b; },
'&': function (a, b) { return a & b; },
'==': function (a, b) { return a == b; }, // jshint ignore:line
'!=': function (a, b) { return a != b; }, // jshint ignore:line
'===': function (a, b) { return a === b; },
'!==': function (a, b) { return a !== b; },
'<': function (a, b) { return a < b; },
'>': function (a, b) { return a > b; },
'<=': function (a, b) { return a <= b; },
'>=': function (a, b) { return a >= b; },
'<<': function (a, b) { return a << b; },
'>>': function (a, b) { return a >> b; },
'>>>': function (a, b) { return a >>> b; },
'+': function (a, b) { return a + b; },
'-': function (a, b) { return a - b; },
'*': function (a, b) { return a * b; },
'/': function (a, b) { return a / b; },
'%': function (a, b) { return a % b; }
};
static unops: Record<string, unaryCallback> = {
'-': function (a) { return -a; },
'+': function (a) { return +a; },
'~': function (a) { return ~a; },
'!': function (a) { return !a; },
};
static assignOps: Record<string, assignCallback> = {
'=': function(obj, key, val) { return obj[key] = val; },
'*=': function(obj, key, val) { return obj[key] *= val; },
'**=': function(obj, key, val) { return obj[key] **= val; },
'/=': function(obj, key, val) { return obj[key] /= val; },
'%=': function(obj, key, val) { return obj[key] %= val; },
'+=': function(obj, key, val) { return obj[key] += val; },
'-=': function(obj, key, val) { return obj[key] -= val; },
'<<=': function(obj, key, val) { return obj[key] <<= val; },
'>>=': function(obj, key, val) { return obj[key] >>= val; },
'>>>=': function(obj, key, val) { return obj[key] >>>= val; },
'&=': function(obj, key, val) { return obj[key] &= val; },
'^=': function(obj, key, val) { return obj[key] ^= val; },
'|=': function(obj, key, val) { return obj[key] |= val; },
};
// inject Custom Unary Operators (and override existing ones)
static addUnaryOp(operator: string, _function: unaryCallback): void {
jsep.addUnaryOp(operator);
ExpressionEval.unops[operator] = _function;
}
// inject Custom Binary Operators (and override existing ones)
static addBinaryOp(
operator: string,
precedence_or_fn: number | binaryCallback,
_ra_or_callback?: boolean | binaryCallback,
_function?: binaryCallback)
: void {
let precedence, ra, cb;
if (typeof precedence_or_fn === 'function') {
cb = precedence_or_fn;
} else {
precedence = precedence_or_fn;
if (typeof _ra_or_callback === 'function') {
cb = _ra_or_callback;
} else {
ra = _ra_or_callback;
cb = _function;
}
}
jsep.addBinaryOp(operator, precedence || 1, ra);
ExpressionEval.binops[operator] = cb;
}
// inject custom node evaluators (and override existing ones)
static addEvaluator<T extends AnyExpression>(nodeType: string, evaluator: evaluatorCallback<T>): void {
ExpressionEval.evaluators[nodeType] = evaluator;
}
static registerPlugin(...plugins: Array<JseEvalPlugin>) {
plugins.forEach((p) => {
if (p.init) {
ExpressionEval.parse.plugins.register(p as jsep.IPlugin);
}
if (p.initEval) {
p.initEval.call(ExpressionEval, ExpressionEval);
}
});
}
// main evaluator method
static eval(ast: jsep.Expression, context?: Context): unknown {
return (new ExpressionEval(context)).eval(ast);
}
static async evalAsync(ast: jsep.Expression, context?: Context): Promise<unknown> {
return (new ExpressionEval(context, true)).eval(ast);
}
// compile an expression and return an evaluator
static compile(expression: string): (context?: Context) => unknown {
return ExpressionEval.eval.bind(null, ExpressionEval.jsep(expression));
}
static compileAsync(expression: string): (context?: Context) => Promise<unknown> {
return ExpressionEval.evalAsync.bind(null, ExpressionEval.jsep(expression));
}
// compile and evaluate
static evalExpr(expression: string, context?: Context): unknown {
return ExpressionEval.compile(expression)(context);
}
static evalExprAsync(expression: string, context?: Context): unknown {
return ExpressionEval.compileAsync(expression)(context);
}
context?: Context;
isAsync?: boolean;
constructor(context?: Context, isAsync?: boolean) {
this.context = context;
this.isAsync = isAsync;
}
public eval(node: unknown, cb = v => v): unknown {
const evaluator = ExpressionEval.evaluators[(node as jsep.Expression).type]
|| ExpressionEval.evaluators.default;
if (!evaluator) {
throw new Error(`unknown node type: ${JSON.stringify(node, null, 2)}`);
}
return this.evalSyncAsync(evaluator.bind(this)(node, this.context), (v) => {
(node as any)._value = v;
return cb(v);
});
}
/*
* `evalSyncAsync` is a helper to wrap sync/async calls into one so that
* we don't have to duplicate all of our node type parsers.
* It's basically like old node callback (hell?), but it works because:
* for sync:
* an expression like `[1].map(v => v + 1)` returns the result
* after running the callback
* for async:
* an expression like `const a = (await x) + 1` is equivalent to
* `Promise.resolve(x).then(res => res + 1)`
*
* Note: For optimization, there are a few places where it makes sense
* to directly check `this.isAsync` to use Promise.all(),
* `promisesOrResults = expressions.map(v => this.eval(v))`
* could result in an array of results (sync) or promises (async)
*/
evalSyncAsync(val: unknown, cb: (unknown) => unknown): Promise<unknown> | unknown {
if (this.isAsync) {
return Promise.resolve(val).then(cb);
}
return cb(val);
}
private evalArrayExpression(node: jsep.ArrayExpression) {
return this.evalArray(node.elements);
}
protected evalArray(list: jsep.Expression[]): unknown[] {
const mapped = list.map(v => this.eval(v));
const toFullArray = (res) => res
.reduce((arr, v, i) => {
if ((list[i] as AnyExpression).type === 'SpreadElement') {
return [...arr, ...v];
}
arr.push(v);
return arr;
}, []);
return this.isAsync
? Promise.all(mapped).then(toFullArray)
: toFullArray(mapped);
}
private evalBinaryExpression(node: jsep.BinaryExpression) {
if (node.operator === '||') {
return this.eval(node.left, left => left || this.eval(node.right));
} else if (node.operator === '&&') {
return this.eval(node.left, left => left && this.eval(node.right));
}
const leftRight = [
this.eval(node.left),
this.eval(node.right)
];
const op = ([left, right]) => ExpressionEval
.binops[node.operator](left, right);
return this.isAsync
? Promise.all(leftRight).then(op)
: op(leftRight as [operand, operand]);
}
private evalCompoundExpression(node: jsep.Compound) {
return this.isAsync
? node.body.reduce((p: Promise<any>, node) => p.then(() => this.eval(node)), Promise.resolve())
: node.body.map(v => this.eval(v))[node.body.length - 1]
}
private evalCallExpression(node: jsep.CallExpression) {
return this.evalSyncAsync(this.evalCall(node.callee), ([fn, caller]) => this
.evalSyncAsync(this.evalArray(node.arguments), args => fn
.apply(caller === node.callee ? this.context : caller, args)));
}
protected evalCall(callee: jsep.Expression): unknown {
if (callee.type === 'MemberExpression') {
return this.evalSyncAsync(
this.evaluateMember(callee as jsep.MemberExpression),
([caller, fn]) => ExpressionEval.validateFnAndCall(fn, caller, callee as AnyExpression)
);
}
return this.eval(callee, fn => ExpressionEval.validateFnAndCall(fn, callee as AnyExpression));
}
private evalConditionalExpression(node: jsep.ConditionalExpression) {
return this.eval(node.test, v => v
? this.eval(node.consequent)
: this.eval(node.alternate));
}
private evalIdentifier(node: jsep.Identifier) {
return this.context[node.name];
}
private static evalLiteral(node: jsep.Literal) {
return node.value;
}
private evalMemberExpression(node: jsep.MemberExpression) {
return this.evalSyncAsync(this.evaluateMember(node), ([, val]) => val);
}
private evaluateMember(node: jsep.MemberExpression) {
return this.eval(node.object, (object) => this
.evalSyncAsync(
node.computed
? this.eval(node.property)
: (node.property as jsep.Identifier).name,
(key: string) => {
if (/^__proto__|prototype|constructor$/.test(key)) {
throw Error(`Access to member "${key}" disallowed.`);
}
return [object, (node.optional ? (object || {}) : object)[key], key];
})
);
}
private evalThisExpression() {
return this.context;
}
private evalUnaryExpression(node: jsep.UnaryExpression) {
return this.eval(node.argument, arg => ExpressionEval
.unops[node.operator](arg));
}
private evalArrowFunctionExpression(node: ArrowExpression) {
if (this.isAsync !== node.async) {
return ExpressionEval[node.async ? 'evalAsync' : 'eval'](node as any, this.context);
}
return (...arrowArgs) => {
const arrowContext = this.evalArrowContext(node, arrowArgs);
return ExpressionEval[node.async ? 'evalAsync' : 'eval'](node.body, arrowContext);
};
}
private evalArrowContext(node: ArrowExpression, arrowArgs): Context {
const arrowContext = { ...this.context };
((node.params as AnyExpression[]) || []).forEach((param, i) => {
// default value:
if (param.type === 'AssignmentExpression') {
if (arrowArgs[i] === undefined) {
arrowArgs[i] = this.eval(param.right);
}
param = param.left as AnyExpression;
}
if (param.type === 'Identifier') {
arrowContext[(param as jsep.Identifier).name] = arrowArgs[i];
} else if (param.type === 'ArrayExpression') {
// array destructuring
(param.elements as AnyExpression[]).forEach((el, j) => {
let val = arrowArgs[i][j];
if (el.type === 'AssignmentExpression') {
if (val === undefined) {
// default value
val = this.eval(el.right);
}
el = el.left as AnyExpression;
}
if (el.type === 'Identifier') {
arrowContext[(el as jsep.Identifier).name] = val;
} else {
throw new Error('Unexpected arrow function argument');
}
});
} else if (param.type === 'ObjectExpression') {
// object destructuring
const keys = [];
(param.properties as AnyExpression[]).forEach((prop) => {
let p = prop;
if (p.type === 'AssignmentExpression') {
p = p.left as AnyExpression;
}
let key;
if (p.type === 'Property') {
key = (<jsep.Expression>p.key).type === 'Identifier'
? (p.key as jsep.Identifier).name
: this.eval(p.key).toString();
} else if (p.type === 'Identifier') {
key = p.name;
} else if (p.type === 'SpreadElement' && (<jsep.Expression>p.argument).type === 'Identifier') {
key = (p.argument as jsep.Identifier).name;
} else {
throw new Error('Unexpected arrow function argument');
}
let val = arrowArgs[i][key];
if (p.type === 'SpreadElement') {
// all remaining object properties. Copy arg obj, then delete from our copy
val = { ...arrowArgs[i] };
keys.forEach((k) => {
delete val[k];
});
} else if (val === undefined && prop.type === 'AssignmentExpression') {
// default value
val = this.eval(prop.right);
}
arrowContext[key] = val;
keys.push(key);
});
} else if (param.type === 'SpreadElement' && (<jsep.Expression>param.argument).type === 'Identifier') {
const key = (param.argument as jsep.Identifier).name;
arrowContext[key] = arrowArgs.slice(i);
} else {
throw new Error('Unexpected arrow function argument');
}
});
return arrowContext;
}
private evalAssignmentExpression(node: AssignmentExpression) {
return this.evalSyncAsync(
this.getContextAndKey(node.left as AnyExpression),
([destObj, destKey]) => this.eval(node.right, right => ExpressionEval
.assignOps[node.operator](destObj, destKey, right))
);
}
private evalUpdateExpression(node: UpdateExpression) {
return this.evalSyncAsync(
this.getContextAndKey(node.argument as AnyExpression),
([destObj, destKey]) => ExpressionEval
.evalUpdateOperation(node, destObj, destKey)
);
}
private evalAwaitExpression(node: AwaitExpression) {
return ExpressionEval.evalAsync(node.argument, this.context);
}
private static evalUpdateOperation(node: UpdateExpression, destObj, destKey) {
if (node.prefix) {
return node.operator === '++'
? ++destObj[destKey]
: --destObj[destKey];
}
return node.operator === '++'
? destObj[destKey]++
: destObj[destKey]--;
}
private getContextAndKey(node: AnyExpression) {
if (node.type === 'MemberExpression') {
return this.evalSyncAsync(
this.evaluateMember(<jsep.MemberExpression>node),
([obj, , key]) => [obj, key]
);
} else if (node.type === 'Identifier') {
return [this.context, node.name];
} else if (node.type === 'ConditionalExpression') {
return this.eval(node.test, test => this
.getContextAndKey((test
? node.consequent
: node.alternate) as AnyExpression));
} else {
throw new Error('Invalid Member Key');
}
}
private evalNewExpression(node: NewExpression) {
return this.evalSyncAsync(
this.evalCall(node.callee),
([ctor]) => this.evalSyncAsync(
this.evalArray(node.arguments),
args => ExpressionEval.construct(ctor, args, node)));
}
private evalObjectExpression(node: ObjectExpression) {
const obj = {};
const arr = node.properties.map((prop: Property | SpreadElement) => {
if (prop.type === 'SpreadElement') {
// always synchronous in this case
Object.assign(obj, ExpressionEval.eval(prop.argument, this.context));
} else if (prop.type === 'Property') {
return this.evalSyncAsync(
prop.key.type === 'Identifier'
? (<jsep.Identifier>prop.key).name
: this.eval(prop.key),
key => this.eval(
prop.shorthand ? prop.key : prop.value,
val => { obj[key] = val; }
)
);
}
});
return this.isAsync
? Promise.all(arr).then(() => obj)
: obj;
}
private evalSpreadElement(node: SpreadElement) {
return this.eval(node.argument);
}
private evalTaggedTemplateExpression(node: TaggedTemplateExpression) {
const fnAndArgs = [
this.evalCall(node.tag),
this.evalSyncAsync(
this.evalArray(node.quasi.expressions),
exprs => [
node.quasi.quasis.map(q => q.value.cooked),
...exprs,
]
),
];
const apply = ([[fn, caller], args]) => fn.apply(caller, args);
return this.isAsync
? Promise.all(fnAndArgs).then(apply)
: apply(fnAndArgs as [[() => unknown, AnyExpression], unknown]);
}
private evalTemplateLiteral(node: TemplateLiteral) {
return this.evalSyncAsync(
this.evalArray(node.expressions),
expressions => node.quasis.reduce((str, q, i) => {
str += q.value.cooked;
if (!q.tail) {
str += expressions[i];
}
return str;
}, '')
);
}
protected static construct(
ctor: () => unknown,
args: unknown[],
node: jsep.CallExpression | jsep.Expression
): unknown {
try {
return new (Function.prototype.bind.apply(ctor, [null].concat(args)))();
} catch (e) {
throw new Error(`${ExpressionEval.nodeFunctionName(node.callee as AnyExpression)} is not a constructor`);
}
}
protected static validateFnAndCall(
fn: () => unknown,
callee?: AnyExpression,
caller?: AnyExpression,
): [() => unknown, AnyExpression] {
if (typeof fn !== 'function') {
if (!fn && caller && caller.optional) {
return [() => undefined, callee];
}
const name = ExpressionEval.nodeFunctionName(caller || callee);
throw new Error(`'${name}' is not a function`);
}
return [fn, callee];
}
protected static nodeFunctionName(callee: AnyExpression): string {
return callee
&& ((callee as jsep.Identifier).name
|| ((callee as jsep.MemberExpression).property
&& ((callee as jsep.MemberExpression).property as jsep.Identifier).name));
}
}
/** NOTE: exporting named + default.
* For CJS, these match the static members of the default export, so they still work.
*/
export { default as jsep, default as parse } from 'jsep';
export const DEFAULT_PRECEDENCE = ExpressionEval.DEFAULT_PRECEDENCE;
export const evaluators = ExpressionEval.evaluators;
export const binops = ExpressionEval.binops;
export const unops = ExpressionEval.unops;
export const assignOps = ExpressionEval.assignOps;
export const addUnaryOp = ExpressionEval.addUnaryOp;
export const addBinaryOp = ExpressionEval.addBinaryOp;
export const addEvaluator = ExpressionEval.addEvaluator;
export const registerPlugin = ExpressionEval.registerPlugin;
export const evaluate = ExpressionEval.eval;
export const evalAsync = ExpressionEval.evalAsync;
export const compile = ExpressionEval.compile;
export const compileAsync = ExpressionEval.compileAsync;
export const evalExpr = ExpressionEval.evalExpr;
export const evalExprAsync = ExpressionEval.evalExprAsync;