action.ts
TypeScript · 60 рядків
1// ACTION (G2): записує поля в data. Значення — літерал (як раніше) або вираз, якщо рядок починається з "="
2// ("=data.expected - data.accepted"). Поля, які записав ACTION, видно наступним блокам (схема виводиться тут —
3// однаково для перевірки на сервері й підказок у редакторі).
4import { actionExpression, evaluateExpression, inferExpressionType } from './condition.ts'
5
6export function literalType(value) {
7 if (value === null || value === undefined) return 'any'
8 if (Array.isArray(value)) return 'any[]'
9 // об'єкт-літерал має відому форму — наступні блоки й контракти бачать його поля, а не просто 'object'
10 if (typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, literalType(item)]))
11 if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'
12 return typeof value
13}
14
15function setSchema(schema, path, type) {
16 const keys = String(path).split('.').filter(Boolean)
17 const last = keys.pop()
18 if (!last) return
19 let target = schema
20 for (const key of keys) {
21 if (!target[key] || typeof target[key] !== 'object' || Array.isArray(target[key])) target[key] = {}
22 target = target[key]
23 }
24 target[last] = type
25}
26
27/** Схема data після ACTION і помилки виразів. scopeSchemas — { task, event }. */
28export function actionOutputSchema(config: any = {}, inherited: any = {}, scopeSchemas: any = {}) {
29 const schema = structuredClone(inherited || {})
30 const errors = []
31 for (const [path, value] of Object.entries(config.set || {})) {
32 if (!String(path).trim()) { errors.push('field path cannot be empty'); continue }
33 const expression = actionExpression(value)
34 if (expression === null) { setSchema(schema, path, literalType(value)); continue }
35 const result = inferExpressionType(expression, { ...scopeSchemas, data: schema })
36 for (const error of result.errors) errors.push(`${path}: ${error}`)
37 setSchema(schema, path, result.type)
38 }
39 return { schema, errors }
40}
41
42function setValue(object, path, value) {
43 const keys = String(path).split('.')
44 const last = keys.pop()
45 const target = keys.reduce((current, key) => {
46 if (!current[key] || typeof current[key] !== 'object') current[key] = {}
47 return current[key]
48 }, object)
49 target[last] = value
50}
51
52/** Виконати ACTION над контекстом. Поля записуються по черзі: наступний вираз бачить попередні. */
53export function applyAction(config: any = {}, context: any, scopes: any = {}) {
54 for (const [path, value] of Object.entries(config.set || {})) {
55 const expression = actionExpression(value)
56 setValue(context, path, expression === null ? structuredClone(value) : evaluateExpression(expression, { ...scopes, data: context, input: context }))
57 }
58 return context
59}
60