condition.ts
TypeScript · 319 рядків
1// Мова виразів workflow: умови EVENT, routes у CONDITION, умови на ребрах (G3), обчислення в ACTION (G2).
2// Розбір у дерево й обчислення без eval / Function.
3//
4// літерали: 12 1.5 'текст' "текст" true false null
5// шляхи: data.* input.* model.* task.* event.* (task без шляху — сама задача або false)
6// оператори: || && ! == != === !== < <= > >= + - * / % унарний - ( )
7// функції: len(x) coalesce(a, b, …) min(a, …) max(a, …) round(x) floor(x) ceil(x) abs(x)
8// lower(s) upper(s) now() ts(дата)
9//
10// Сумісність зі старою мовою (лише порівняння): == / != — нестрогі (як у JS), === / !== — строгі; && і || дають boolean.
11// G2 (R-12 §11.3): арифметика, функції, дати. now() і ts('2026-10-11T10:00:00Z') — мілісекунди, тож
12// «задача висить понад 2 год» — now() - ts(task.createdAt) > 2 * 3600000.
13// + з рядком склеює рядки; решта арифметики — лише числа.
14
15const ROOTS = ['data', 'input', 'model', 'task', 'event']
16const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
17
18const toNumber = value => Number(value)
19const FUNCTIONS = {
20 len: { args: [1, 1], type: () => 'integer', run: value => Array.isArray(value) || typeof value === 'string' ? value.length : value && typeof value === 'object' ? Object.keys(value).length : 0 },
21 coalesce: { args: [1, Infinity], type: types => types.find(type => !['null', 'any', 'unknown'].includes(type)) || 'any', run: (...values) => values.find(value => value !== null && value !== undefined) ?? null },
22 min: { args: [1, Infinity], numeric: true, type: () => 'number', run: (...values) => Math.min(...values.map(toNumber)) },
23 max: { args: [1, Infinity], numeric: true, type: () => 'number', run: (...values) => Math.max(...values.map(toNumber)) },
24 round: { args: [1, 1], numeric: true, type: () => 'integer', run: value => Math.round(toNumber(value)) },
25 floor: { args: [1, 1], numeric: true, type: () => 'integer', run: value => Math.floor(toNumber(value)) },
26 ceil: { args: [1, 1], numeric: true, type: () => 'integer', run: value => Math.ceil(toNumber(value)) },
27 abs: { args: [1, 1], numeric: true, type: () => 'number', run: value => Math.abs(toNumber(value)) },
28 lower: { args: [1, 1], type: () => 'string', run: value => String(value ?? '').toLowerCase() },
29 upper: { args: [1, 1], type: () => 'string', run: value => String(value ?? '').toUpperCase() },
30 now: { args: [0, 0], type: () => 'number', run: () => Date.now() },
31 ts: { args: [1, 1], type: () => 'number', run: value => {
32 const time = typeof value === 'number' ? value : Date.parse(String(value ?? ''))
33 if (Number.isNaN(time)) throw new Error(`ts(): not a date: ${value}`)
34 return time
35 } }
36}
37
38const OPERATORS = ['===', '!==', '>=', '<=', '==', '!=', '&&', '||', '>', '<', '!', '+', '-', '*', '/', '%', '(', ')', ',']
39
40function tokenize(source) {
41 const tokens = []
42 let index = 0
43
44 while (index < source.length) {
45 const character = source[index]
46 if (/\s/.test(character)) {
47 index += 1
48 continue
49 }
50
51 if (character === '"' || character === "'") {
52 const quote = character
53 const start = index
54 let value = ''
55 index += 1
56 while (index < source.length && source[index] !== quote) {
57 if (source[index] === '\\') {
58 index += 1
59 const escaped = source[index]
60 index += 1
61 value += escaped === 'n' ? '\n' : escaped === 't' ? '\t' : escaped
62 } else {
63 value += source[index]
64 index += 1
65 }
66 }
67 if (source[index] !== quote) throw new Error(`Unterminated string at ${start}`)
68 index += 1
69 tokens.push({ type: 'literal', value, pos: start })
70 continue
71 }
72
73 const number = source.slice(index).match(/^\d+(?:\.\d+)?/)
74 if (number) {
75 tokens.push({ type: 'literal', value: Number(number[0]), pos: index })
76 index += number[0].length
77 continue
78 }
79
80 const word = source.slice(index).match(/^[A-Za-z_$][A-Za-z0-9_$.]*/)
81 if (word) {
82 const value = word[0]
83 if (value === 'true' || value === 'false' || value === 'null') {
84 tokens.push({
85 type: 'literal',
86 value: value === 'null' ? null : value === 'true',
87 pos: index
88 })
89 } else {
90 tokens.push({ type: 'path', value, pos: index })
91 }
92 index += value.length
93 continue
94 }
95
96 const operator = OPERATORS.find(value => source.startsWith(value, index))
97 if (operator) {
98 tokens.push({ type: 'op', value: operator, pos: index })
99 index += operator.length
100 continue
101 }
102
103 throw new Error(`Unexpected token "${character}" at ${index}`)
104 }
105
106 tokens.push({ type: 'eof', value: '', pos: index })
107 return tokens
108}
109
110const LEVELS = [['||'], ['&&'], ['==', '===', '!=', '!=='], ['>', '>=', '<', '<='], ['+', '-'], ['*', '/', '%']]
111
112export function parseCondition(source) {
113 const tokens = tokenize(String(source))
114 const peek = () => tokens[0]
115 const take = () => tokens.shift()
116 const match = value => peek().type === 'op' && peek().value === value ? (take(), true) : false
117
118 function binary(level) {
119 if (level === LEVELS.length) return unary()
120 let left = binary(level + 1)
121 while (peek().type === 'op' && LEVELS[level].includes(peek().value)) {
122 const op = take().value
123 left = { type: 'binary', op, left, right: binary(level + 1) }
124 }
125 return left
126 }
127
128 function unary() {
129 if (match('!')) return { type: 'unary', op: '!', value: unary() }
130 if (match('-')) return { type: 'unary', op: '-', value: unary() }
131 return primary()
132 }
133
134 function primary() {
135 if (match('(')) {
136 const node = binary(0)
137 if (!match(')')) throw new Error(`Expected ")" at ${peek().pos}`)
138 return node
139 }
140
141 const token = take()
142 if (token.type === 'literal') return { type: 'literal', value: token.value }
143 if (token.type === 'path') {
144 // ім'я з крапкою (process.exit) — не функція: падає нижче на перевірці областей, як і раніше
145 if (peek().type === 'op' && peek().value === '(' && !token.value.includes('.')) {
146 const fn = FUNCTIONS[token.value]
147 if (!fn) throw new Error(`Unknown function ${token.value}() at ${token.pos}`)
148 take()
149 const args = []
150 if (!match(')')) {
151 do args.push(binary(0))
152 while (match(','))
153 if (!match(')')) throw new Error(`Expected ")" at ${peek().pos}`)
154 }
155 const [min, max] = fn.args
156 if (args.length < min || args.length > max) {
157 throw new Error(`${token.value}() expects ${min === max ? min : max === Infinity ? `at least ${min}` : `${min}–${max}`} argument${max === 1 ? '' : 's'} at ${token.pos}`)
158 }
159 return { type: 'call', fn: token.value, args }
160 }
161 const parts = token.value.split('.')
162 const root = parts.shift()
163 if (!ROOTS.includes(root) || (!parts.length && root !== 'task')) {
164 throw new Error(`Only ${ROOTS.map(value => `${value}.*`).join(', ')} fields are allowed at ${token.pos}`)
165 }
166 if (parts.some(part => FORBIDDEN_KEYS.has(part))) throw new Error(`Forbidden field name at ${token.pos}`)
167 return { type: 'path', root, path: parts }
168 }
169 throw new Error(token.type === 'eof' ? `Expected value at ${token.pos}` : `Unexpected token "${token.value}" at ${token.pos}`)
170 }
171
172 const ast = binary(0)
173 if (peek().type !== 'eof') throw new Error(`Unexpected token "${peek().value}" at ${peek().pos}`)
174 return ast
175}
176
177function schemaAt(schema, path) {
178 return path.reduce(
179 (value, key) => value && typeof value === 'object' && !Array.isArray(value) ? value[key] : undefined,
180 schema
181 )
182}
183
184function rootSchema(schema, root) {
185 if (root === 'data') return schema?.data ?? schema
186 return schema?.[root] ?? {}
187}
188
189const numeric = type => ['number', 'integer', 'any', 'unknown'].includes(type)
190
191function typeOf(node, schema, errors) {
192 if (node.type === 'literal') return node.value === null ? 'null' : typeof node.value
193 if (node.type === 'path') {
194 if (node.root === 'task' && !node.path.length) return 'task'
195 const type = schemaAt(rootSchema(schema, node.root), node.path)
196 if (type === undefined) {
197 // data.task / data.event — часта плутанина зі scope task / event (у data їх немає, поки блок їх туди не поклав)
198 const hint = node.root === 'data' && ['task', 'event'].includes(node.path[0])
199 ? ` (did you mean ${node.path.join('.')}?)`
200 : ''
201 errors.push(`Unknown field: ${node.root}.${node.path.join('.')}${hint}`)
202 return 'unknown'
203 }
204 if (typeof type === 'string') return type.endsWith('[]') ? 'array' : type
205 return Array.isArray(type) ? 'array' : 'object'
206 }
207 if (node.type === 'unary') {
208 const type = typeOf(node.value, schema, errors)
209 if (node.op === '!') return 'boolean'
210 if (!numeric(type)) errors.push(`Operator "-" requires a number, received ${type}`)
211 return 'number'
212 }
213 if (node.type === 'call') {
214 const fn = FUNCTIONS[node.fn]
215 const types = node.args.map(arg => typeOf(arg, schema, errors))
216 if (fn.numeric) {
217 for (const type of types) if (!numeric(type)) errors.push(`${node.fn}() requires numbers, received ${type}`)
218 }
219 return fn.type(types)
220 }
221
222 const left = typeOf(node.left, schema, errors)
223 const right = typeOf(node.right, schema, errors)
224 if (['&&', '||'].includes(node.op)) return 'boolean'
225 // any — тип не відомий заздалегідь (поле моделі типу any): порівнювати й рахувати можна з будь-чим
226 const loose = [left, right].some(type => ['any', 'unknown'].includes(type))
227
228 if (node.op === '+') {
229 if (left === 'string' || right === 'string') return 'string'
230 if (loose) return [left, right].every(numeric) ? 'number' : 'any'
231 if (!numeric(left) || !numeric(right)) errors.push(`Operator "+" requires numbers or strings, received ${left} and ${right}`)
232 return left === 'integer' && right === 'integer' ? 'integer' : 'number'
233 }
234 if (['-', '*', '/', '%'].includes(node.op)) {
235 if (!numeric(left) || !numeric(right)) errors.push(`Operator "${node.op}" requires numbers, received ${left} and ${right}`)
236 return node.op !== '/' && left === 'integer' && right === 'integer' ? 'integer' : 'number'
237 }
238 if (loose) return 'boolean'
239 if (['>', '>=', '<', '<='].includes(node.op)
240 && (!['number', 'integer'].includes(left) || !['number', 'integer'].includes(right))) {
241 errors.push(`Operator "${node.op}" requires numbers, received ${left} and ${right}`)
242 }
243 if (['==', '===', '!=', '!=='].includes(node.op)
244 && left !== right
245 && !(left === 'task' && right === 'boolean')
246 && !(left === 'boolean' && right === 'task')
247 && !(['number', 'integer'].includes(left) && ['number', 'integer'].includes(right))) {
248 errors.push(`Cannot compare ${left} with ${right}`)
249 }
250 return 'boolean'
251}
252
253export function validateCondition(source, schema) {
254 try {
255 const ast = parseCondition(source)
256 const errors = []
257 typeOf(ast, schema, errors)
258 return { valid: errors.length === 0, errors, ast }
259 } catch (error) {
260 return { valid: false, errors: [(error as Error).message], ast: null }
261 }
262}
263
264/** Тип результату виразу (для схеми полів, які записує ACTION) і помилки. */
265export function inferExpressionType(source, schema) {
266 try {
267 const errors = []
268 const type = typeOf(parseCondition(source), schema, errors)
269 return { type: type === 'unknown' ? 'any' : type === 'task' ? 'object' : type === 'array' ? 'any[]' : type, errors }
270 } catch (error) {
271 return { type: 'any', errors: [(error as Error).message] }
272 }
273}
274
275/** Обчислити вираз і повернути значення (ACTION). */
276export function evaluateExpression(source, scopes) {
277 const ast = typeof source === 'string' ? parseCondition(source) : source
278
279 function run(node) {
280 if (node.type === 'literal') return node.value
281 if (node.type === 'path') {
282 const root = node.root === 'data' ? (scopes?.data ?? scopes) : scopes?.[node.root]
283 return node.path.reduce((value, key) => value?.[key], root)
284 }
285 if (node.type === 'unary') return node.op === '!' ? !run(node.value) : -Number(run(node.value))
286 if (node.type === 'call') return FUNCTIONS[node.fn].run(...node.args.map(run))
287
288 const left = run(node.left)
289 if (node.op === '&&') return Boolean(left && run(node.right))
290 if (node.op === '||') return Boolean(left || run(node.right))
291
292 const right = run(node.right)
293 if (node.op === '==') return left == right
294 if (node.op === '===') return left === right
295 if (node.op === '!=') return left != right
296 if (node.op === '!==') return left !== right
297 if (node.op === '>') return left > right
298 if (node.op === '>=') return left >= right
299 if (node.op === '<') return left < right
300 if (node.op === '<=') return left <= right
301 if (node.op === '+') return typeof left === 'string' || typeof right === 'string' ? `${left ?? ''}${right ?? ''}` : Number(left) + Number(right)
302 if (node.op === '-') return Number(left) - Number(right)
303 if (node.op === '*') return Number(left) * Number(right)
304 if (node.op === '/') return Number(left) / Number(right)
305 if (node.op === '%') return Number(left) % Number(right)
306 }
307
308 return run(ast)
309}
310
311export function evaluateCondition(source, scopes) {
312 return Boolean(evaluateExpression(source, scopes))
313}
314
315/** ACTION: значення, що починається з "=", — вираз ("=data.expected - data.accepted"); інакше — літерал, як раніше. */
316export function actionExpression(value) {
317 return typeof value === 'string' && value.startsWith('=') && !value.startsWith('==') ? value.slice(1).trim() : null
318}
319