techtools
Головна / proto / flow-old / src / dataFlow.js

dataFlow.js

JavaScript · 323 рядків

1import { forwardIncoming } from '../shared/graph.ts'
2import { deriveMappingSchema } from '../shared/mapping.ts'
3import { taskContextModelId } from '../shared/task.ts'
4import { actionOutputSchema } from '../shared/action.ts'
5import { EVENT_SYSTEM_FIELDS, nestAtPath, startEventData } from '../shared/schema-scopes.ts'
6import { decisionOutputSchema } from '../shared/decision.ts'
7
8export const apiErrorSchema = {
9  error: {
10    type: 'string',
11    message: 'string',
12    status: 'number',
13    code: 'string',
14    details: 'object',
15    request: {
16      method: 'string',
17      url: 'string'
18    }
19  }
20}
21
22export const workflowErrorSchema = {
23  error: {
24    type: 'string',
25    message: 'string',
26    code: 'string',
27    details: 'object',
28    nodeId: 'string',
29    blockType: 'string'
30  }
31}
32
33export function expandSchema(schema, models, seen = new Set()) {
34  const result = {}
35  for (const [key, value] of Object.entries(schema || {})) {
36    if (typeof value === 'string') {
37      const array = value.endsWith('[]')
38      const type = array ? value.slice(0, -2) : value
39      const model = models.find(candidate => candidate.name === type)
40      if (model && !seen.has(model.id)) {
41        const expanded = expandSchema(
42          model.schema,
43          models,
44          new Set([...seen, model.id])
45        )
46        result[key] = array ? [expanded] : expanded
47      } else {
48        result[key] = value
49      }
50    } else if (value && typeof value === 'object') {
51      result[key] = expandSchema(value, models, seen)
52    }
53  }
54  return result
55}
56
57const jsonClone = value => JSON.parse(JSON.stringify(value))
58
59function merge(left, right) {
60  const result = jsonClone(left || {})
61  for (const [key, value] of Object.entries(right || {})) {
62    if (result[key]
63      && typeof result[key] === 'object'
64      && !Array.isArray(result[key])
65      && typeof value === 'object'
66      && !Array.isArray(value)) {
67      result[key] = merge(result[key], value)
68    } else {
69      result[key] = jsonClone(value)
70    }
71  }
72  return result
73}
74
75export function outputSchema(
76  workflow,
77  nodeId,
78  portId,
79  models,
80  memo = new Map(),
81  stack = new Set()
82) {
83  const cache = `${nodeId}:${portId}`
84  if (memo.has(cache)) return memo.get(cache)
85  if (stack.has(nodeId)) return { $cycle: 'workflow cycle' }
86  stack.add(nodeId)
87
88  const node = workflow.nodes.find(candidate => candidate.id === nodeId)
89  if (!node) return {}
90
91  let inherited = {}
92  for (const edge of forwardIncoming(workflow, nodeId)) {
93    const incoming = outputSchema(
94      workflow,
95      edge.source,
96      edge.sourcePort,
97      models,
98      memo,
99      new Set(stack)
100    )
101    inherited = merge(
102      inherited,
103      node.type === 'TASK_UPDATE' && edge.targetPort === 'task'
104        ? { task: incoming }
105        : incoming
106    )
107  }
108
109  const modelById = id => models.find(model => model.id === id)
110
111  if (node.type === 'ACTION') {
112    const task = expandSchema(modelById('system-task')?.schema || {}, models)
113    const result = actionOutputSchema(node.config, inherited, {
114      task,
115      event: eventSchema(workflow, nodeId, models)
116    }).schema
117    memo.set(cache, result)
118    return result
119  }
120
121  if (node.type === 'DECISION') {
122    const task = expandSchema(modelById('system-task')?.schema || {}, models)
123    const result = decisionOutputSchema(node.config, inherited, {
124      task,
125      event: eventSchema(workflow, nodeId, models)
126    }).schema
127    memo.set(cache, result)
128    return result
129  }
130
131  if (node.type === 'MAPPING') {
132    const result = deriveMappingSchema(
133      node.config?.mapping || { $copy: 'data' },
134      inherited
135    )
136    memo.set(cache, result)
137    return result
138  }
139
140  if (node.type === 'API_REQUEST' && portId === 'error') {
141    const errorModel = modelById(node.config?.errorModelId || 'system-api-error')
142    const errorSchema = {
143      error: expandSchema(errorModel?.schema || apiErrorSchema.error, models)
144    }
145    const result = merge(inherited, errorSchema)
146    memo.set(cache, result)
147    return result
148  }
149
150  if (node.type === 'CONDITION' && node.config?.routes?.[portId] === '$error') {
151    const errorModel = modelById('system-workflow-error')
152    const result = merge(inherited, {
153      error: expandSchema(errorModel?.schema || workflowErrorSchema.error, models)
154    })
155    memo.set(cache, result)
156    return result
157  }
158
159  if (node.type === 'WORKFLOW') {
160    const result = jsonClone(node.config?.outputContracts?.[portId] || {})
161    memo.set(cache, result)
162    return result
163  }
164
165  if (['TASK', 'TASK_UPDATE'].includes(node.type)) {
166    const task = expandSchema(modelById('system-task')?.schema || {}, models)
167    const taskOutput = node.type === 'TASK' && node.config?.itemsPath
168      ? { tasks: [task] }
169      : { task }
170    const result = portId === 'task' ? task : merge(inherited, taskOutput)
171    memo.set(cache, result)
172    return result
173  }
174
175  const modelId = node.config?.outputModels?.[portId]
176    || (['EVENT', 'WORKFLOW_INPUT'].includes(node.type)
177      ? node.config?.modelId
178      : null)
179    || (node.type === 'API_REQUEST'
180      ? node.config?.modelId || node.config?.responseModelId
181      : null)
182  const model = modelById(modelId)
183  const response = model ? expandSchema(model.schema, models) : {}
184  // відповідь API_REQUEST рушій кладе в data.<resultPath>, як і серверна перевірка (server/data-flow.ts)
185  const added = node.type === 'API_REQUEST' ? nestAtPath(response, node.config?.resultPath) : response
186  // TASK-подія обробника: data — контекст задачі (модель у властивостях workflow, G1)
187  const result = node.type === 'EVENT' && node.config?.activation === 'TASK'
188    ? expandSchema(modelById(taskContextModelId(workflow, node))?.schema || {}, models)
189    : merge(inherited, node.type === 'EVENT' ? startEventData(added) : added)
190  memo.set(cache, result)
191  return result
192}
193
194export function addedSchema(node, portId, models) {
195  if (node.type === 'EVENT') {
196    const task = expandSchema(
197      models.find(item => item.id === 'system-task')?.schema || {},
198      models
199    )
200    return {
201      task: {
202        $type: 'Task | false',
203        $model: 'system-task',
204        $whenMissing: false,
205        ...task
206      }
207    }
208  }
209  if (node.type === 'API_REQUEST' && portId === 'error') {
210    const model = models.find(item =>
211      item.id === (node.config?.errorModelId || 'system-api-error')
212    )
213    return {
214      error: expandSchema(model?.schema || apiErrorSchema.error, models)
215    }
216  }
217
218  if (node.type === 'CONDITION' && node.config?.routes?.[portId] === '$error') {
219    const model = models.find(item => item.id === 'system-workflow-error')
220    return {
221      error: expandSchema(model?.schema || workflowErrorSchema.error, models)
222    }
223  }
224
225  if (['TASK', 'TASK_UPDATE'].includes(node.type)) {
226    const task = expandSchema(
227      models.find(item => item.id === 'system-task')?.schema || {},
228      models
229    )
230    if (portId === 'task') return task
231    return node.type === 'TASK' && node.config?.itemsPath
232      ? { tasks: [task] }
233      : { task }
234  }
235
236  if (node.type === 'DECISION') {
237    // з порожнім входом схема блока — лише його результат у data.<resultPath>
238    return decisionOutputSchema(node.config, {}, {}).schema
239  }
240
241  if (node.type === 'MAPPING'
242    || node.type === 'CLIENT_RESPONSE'
243    || node.type === 'SCREEN'
244    || (node.type === 'EVENT' && node.config?.activation === 'TASK')) {
245    return {}
246  }
247
248  const id = node.config?.outputModels?.[portId]
249    || (node.type === 'EVENT' ? node.config?.modelId : null)
250    || (node.type === 'API_REQUEST'
251      ? node.config?.modelId || node.config?.responseModelId
252      : null)
253  const model = models.find(candidate => candidate.id === id)
254  const schema = expandSchema(model?.schema || {}, models)
255  return node.type === 'API_REQUEST' ? nestAtPath(schema, node.config?.resultPath) : schema
256}
257
258export function nodeDataSchema(workflow, nodeId, models) {
259  const node = workflow.nodes.find(item => item.id === nodeId)
260  return node?.outputs?.length
261    ? outputSchema(workflow, nodeId, node.outputs[0].id, models)
262    : {}
263}
264
265export function inputSchema(workflow, nodeId, models, portId = null) {
266  let result = {}
267  const node = workflow.nodes.find(item => item.id === nodeId)
268  const edges = workflow.edges.filter(edge =>
269    edge.target === nodeId && (!portId || edge.targetPort === portId)
270  )
271  for (const edge of edges) {
272    const incoming = outputSchema(
273      workflow,
274      edge.source,
275      edge.sourcePort,
276      models
277    )
278    result = merge(
279      result,
280      node?.type === 'TASK_UPDATE' && !portId && edge.targetPort === 'task'
281        ? { task: incoming }
282        : incoming
283    )
284  }
285  return result
286}
287
288export function schemaPaths(schema, prefix = 'data', result = []) {
289  for (const [key, value] of Object.entries(schema || {})) {
290    const path = `${prefix}.${key}`
291    if (value && typeof value === 'object' && !Array.isArray(value)) {
292      schemaPaths(value, path, result)
293    } else {
294      result.push({
295        path,
296        type: Array.isArray(value) ? 'array' : value
297      })
298    }
299  }
300  return result
301}
302
303export function eventSchema(workflow, nodeId, models, seen = new Set()) {
304  if (seen.has(nodeId)) return {}
305  seen.add(nodeId)
306
307  const node = workflow.nodes.find(item => item.id === nodeId)
308  if (node?.type === 'EVENT') {
309    const model = models.find(candidate => candidate.id === node.config?.modelId)
310    return { ...EVENT_SYSTEM_FIELDS, ...expandSchema(model?.schema || {}, models) }
311  }
312
313  let result = {}
314  for (const edge of forwardIncoming(workflow, nodeId)) {
315    result = merge(
316      result,
317      eventSchema(workflow, edge.source, models, new Set(seen))
318    )
319  }
320  return result
321}
322
323