group-show-rule-eval.js 4.85 KB
/**
 * 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
	}
}