-
Notifications
You must be signed in to change notification settings - Fork 0
/
jep.js
executable file
·297 lines (262 loc) · 7.24 KB
/
jep.js
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
/**
* Javascript Expression Parser (JEP)
* https://github.com/cnlon/jep
*
* Come from Vue.js v1.0.24
* https://github.com/vuejs/vue
*/
var Cache = require('zen-lru')
var defaultAllowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,parseInt,parseFloat'
// keywords that don't make sense inside expressions
var improperKeywordsRE =
new RegExp(
'^('
+ ('break,case,class,catch,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,let,return,super,switch,throw,try,var,while,with,yield,enum,await,implements,package,protected,static,interface,private,public').replace(/,/g, '\\b|')
+ '\\b)'
)
var wsRE = /\s/g
var newlineRE = /\n/g
var saveRE = /[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`)|new |typeof |void /g
var restoreRE = /"(\d+)"/g
var pathTestRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/
var identRE = /[^\w$\.](?:[A-Za-z_$][\w$]*)/g
var booleanLiteralRE = /^(?:true|false)$/
/**
* Save / Rewrite / Restore
*
* When rewriting paths found in an expression, it is
* possible for the same letter sequences to be found in
* strings and Object literal property keys. Therefore we
* remove and store these parts in a temporary array, and
* restore them after the path rewrite.
*/
var saved = []
/**
* Save replacer
*
* The save regex can match two possible cases:
* 1. An opening object literal
* 2. A string
* If matched as a plain string, we need to escape its
* newlines, since the string needs to be preserved when
* generating the function body.
*
* @param {String} str
* @param {String} isString - str if matched as a string
* @return {String} - placeholder with index
*/
function save (str, isString) {
var i = saved.length
saved[i] = isString
? str.replace(newlineRE, '\\n')
: str
return '"' + i + '"'
}
/**
* Restore replacer
*
* @param {String} str
* @param {String} i - matched save index
* @return {String}
*/
function restore (str, i) {
return saved[i]
}
/**
* Check if an expression is a simple path.
*
* @param {String} expression
* @return {Boolean}
*/
function isSimplePath (expression) {
return pathTestRE.test(expression)
// don't treat true/false as paths
&& !booleanLiteralRE.test(expression)
}
/**
* @param {String} keywords
* @return {RegExp}
*/
function parseKeywordsToRE (keywords) {
return new RegExp(
'^(?:'
+ keywords
.replace(wsRE, '')
.replace(/\$/g, '\\$')
.replace(/,/g, '\\b|')
+ '\\b)'
)
}
/**
* @param {Object} options
* - {Number} cache, default 1000
* limited for Cache
* - {Array} params, default ['$']
* first one is for scope and you can add more params
* @constructor
*/
function JEP (options) {
options = options || {}
var cache = options.cache || 1000
var scope = options.scope || '$'
var scopes = options.scopes
var params = options.params
if (!params) {
if (scopes) {
params = Object.keys(scopes)
params.unshift(scope)
} else {
params = [scope]
}
}
this._cache = new Cache(cache)
this._funcParams = params.join(',').replace(wsRE, '')
this._funcBefore = 'function(' + this._funcParams + '){return '
this._funcAfter = '}'
this.scope = scope
if (scopes) {
var keys = Object.keys(scopes)
for (var i = 0, l = keys.length, key, keywords; i < l; i++) {
key = keys[i]
keywords = scopes[key]
scopes[key] = parseKeywordsToRE(
Object.prototype.toString.call(keywords) === '[object Array]'
? keywords.join(',')
: keywords
)
}
this._scopeREs = scopes
}
var paramsPrefix
if (params.length > 1) {
params = params.slice(1)
paramsPrefix = params.join(',')
this._paramsPrefixRE = parseKeywordsToRE(paramsPrefix)
}
var allowedKeywords = paramsPrefix
? (paramsPrefix + ',' + defaultAllowedKeywords)
: defaultAllowedKeywords
this._allowedKeywordsRE = parseKeywordsToRE(allowedKeywords)
}
JEP.prototype._addScope = function (expression) {
if (this._paramsPrefixRE && this._paramsPrefixRE.test(expression)) {
return expression
}
if (this._scopeREs) {
var keys = Object.keys(this._scopeREs)
for (var i = 0, l = keys.length, re; i < l; i++) {
re = this._scopeREs[keys[i]]
if (re.test(expression)) {
return keys[i] + '.' + expression
}
}
}
return this.scope + '.' + expression
}
/**
* Rewrite an expression, prefixing all path accessors with
* `scope.` and return the new expression.
*
* @param {String} expression
* @return {String}
*/
JEP.prototype.compile = function (expression) {
if (process.env.NODE_ENV === 'development') {
if (improperKeywordsRE.test(expression)) {
console.warn('Avoid using reserved keywords in expression: ' + expression)
}
}
// reset state
saved.length = 0
// save strings and object literal keys
var body = expression
.replace(saveRE, save)
.replace(wsRE, '')
// rewrite all paths
// pad 1 space here becaue the regex matches 1 extra char
var self = this
var c, path
return (' ' + body)
.replace(identRE, function (raw) {
c = raw.charAt(0)
path = raw.slice(1)
if (self._allowedKeywordsRE.test(path)) {
return raw
} else {
path = path.indexOf('"') > -1
? path.replace(restoreRE, restore)
: path
return c + self._addScope(path)
}
})
.replace(restoreRE, restore)
.slice(1)
}
/**
* Parse source to expression.
*
* @param {String} source
* @return {String}
*/
JEP.prototype.parse = function (source) {
if (!(source && (source = source.trim()))) {
return ''
}
// try cache
var hit = this._cache.get(source)
if (hit) {
return hit
}
var result = isSimplePath(source) && source.indexOf('[') < 0
? this._addScope(source)
: this.compile(source)
this._cache.set(source, result)
return result
}
/**
* Build expression to function. Requires eval.
*
* @param {String} expression
* @return {Function|undefined}
*/
JEP.prototype.build = function (expression) {
try {
/* eslint-disable no-new-func */
return new Function(this._funcParams, 'return ' + expression)
/* eslint-enable no-new-func */
} catch (e) {
if (process.env.NODE_ENV === 'development') {
console.warn('Invalid expression. Generated function body: ' + expression)
}
}
}
/**
* Build expression to function string.
*
* @param {String} expression
* @return {String}
*/
JEP.prototype.buildToString = function (expression) {
return this._funcBefore + expression + this._funcAfter
}
/**
* Parse source to expression and build it to function.
*
* @param {String} source
* @return {Function|undefined}
*/
JEP.prototype.make = function (source) {
var expression = this.parse(source)
return this.build(expression)
}
/**
* Parse source to expression and build it to function string.
*
* @param {String} source
* @return {String}
*/
JEP.prototype.makeToString = function (source) {
var expression = this.parse(source)
return this.buildToString(expression)
}
module.exports = JEP