group-show-rule-eval.js
4.85 KB
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
/**
* childrenShowRules.result 求值(小程序无 new Function)
* 内置安全解析器(不使用 eval/new Function):支持 valN 比较、数组包含、!、&&、|| 与括号
*/
function tokenize(expr = '') {
const tokens = []
let index = 0
while (index < expr.length) {
const char = expr[index]
if (/\s/.test(char)) {
index += 1
continue
}
const pair = expr.slice(index, index + 2)
if (['&&', '||', '==', '!='].indexOf(pair) >= 0) {
tokens.push({ type: 'operator', value: pair })
index += 2
continue
}
if (char === '!' || char === '(' || char === ')') {
tokens.push({ type: 'operator', value: char })
index += 1
continue
}
if (char === "'" || char === '"') {
const quote = char
let value = ''
index += 1
let closed = false
while (index < expr.length) {
const current = expr[index]
if (current === quote) {
closed = true
index += 1
break
}
if (current === '\\' && index + 1 < expr.length) {
const escaped = expr[index + 1]
const escapeMap = { n: '\n', r: '\r', t: '\t' }
value += escapeMap[escaped] ?? escaped
index += 2
continue
}
value += current
index += 1
}
if (!closed) throw new Error('unterminated string')
tokens.push({ type: 'string', value })
continue
}
const identifier = expr.slice(index).match(/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/)
if (identifier) {
tokens.push({ type: 'identifier', value: identifier[0] })
index += identifier[0].length
continue
}
throw new Error(`unsupported token at ${index}`)
}
return tokens
}
function parseExpression(tokens = [], ctx = {}) {
let index = 0
const peek = () => tokens[index]
const take = () => tokens[index++]
const match = value => {
if (peek()?.value !== value) return false
index += 1
return true
}
const expect = value => {
if (!match(value)) throw new Error(`expected ${value}`)
}
const expectType = type => {
const token = take()
if (!token || token.type !== type) throw new Error(`expected ${type}`)
return token.value
}
const resolveVal = name => {
if (!/^val\d+$/.test(name)) throw new Error(`unsupported variable ${name}`)
return ctx[name]
}
let parseOr
const parsePrimary = () => {
if (match('(')) {
const value = parseOr()
expect(')')
return value
}
const identifier = expectType('identifier')
if (identifier === 'Array.isArray') {
expect('(')
const variable = expectType('identifier')
expect(')')
return Array.isArray(resolveVal(variable))
}
if (/^val\d+\.includes$/.test(identifier)) {
const variable = identifier.slice(0, identifier.indexOf('.'))
expect('(')
const expected = expectType('string')
expect(')')
const actual = resolveVal(variable)
return Array.isArray(actual) && actual.indexOf(expected) >= 0
}
if (/^val\d+$/.test(identifier)) {
if (peek()?.value !== '==' && peek()?.value !== '!=') {
return Boolean(resolveVal(identifier))
}
const operator = take()?.value
if (operator !== '==' && operator !== '!=') {
throw new Error(`unsupported comparison ${operator}`)
}
const expectedToken = take()
if (!expectedToken) throw new Error('missing comparison value')
const actual = resolveVal(identifier)
if (expectedToken.type === 'identifier' && expectedToken.value === 'null') {
return operator === '!='
? actual != null && actual !== ''
: actual == null || actual === ''
}
if (expectedToken.type !== 'string') throw new Error('unsupported comparison value')
return operator === '=='
? actual == expectedToken.value
: actual != expectedToken.value
}
throw new Error(`unsupported expression ${identifier}`)
}
const parseUnary = () => match('!') ? !parseUnary() : parsePrimary()
const parseAnd = () => {
let value = parseUnary()
while (match('&&')) {
const right = parseUnary()
value = value && right
}
return value
}
parseOr = () => {
let value = parseAnd()
while (match('||')) {
const right = parseAnd()
value = value || right
}
return value
}
const result = parseOr()
if (index !== tokens.length) throw new Error('unexpected trailing expression')
return result
}
function fallbackEvaluate(expr = '', ctx = {}) {
if (!expr) return true
try {
return parseExpression(tokenize(expr), ctx)
} catch (error) {
return false
}
}
function evaluateShowRule(keys = [], resultExpr = '', rowFields = [], getRowFieldValue) {
if (!keys.length || !resultExpr) {
return true
}
try {
const ctx = {}
keys.forEach((key, index) => {
ctx[`val${index + 1}`] = getRowFieldValue(rowFields, key)
})
return fallbackEvaluate(resultExpr, ctx)
} catch (error) {
console.error('[evaluateShowRule] eval error', resultExpr, error)
return false
}
}
export { evaluateShowRule, fallbackEvaluate }
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
evaluateShowRule,
fallbackEvaluate
}
}