@zerodep-dev/flow-ts-model 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +202 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/definition/define.d.ts +32 -0
  4. package/dist/definition/define.d.ts.map +1 -0
  5. package/dist/definition/define.js +3 -0
  6. package/dist/definition/define.js.map +1 -0
  7. package/dist/definition/definition.d.ts +408 -0
  8. package/dist/definition/definition.d.ts.map +1 -0
  9. package/dist/definition/definition.js +32 -0
  10. package/dist/definition/definition.js.map +1 -0
  11. package/dist/definition/diff.d.ts +43 -0
  12. package/dist/definition/diff.d.ts.map +1 -0
  13. package/dist/definition/diff.js +70 -0
  14. package/dist/definition/diff.js.map +1 -0
  15. package/dist/definition/edit.d.ts +56 -0
  16. package/dist/definition/edit.d.ts.map +1 -0
  17. package/dist/definition/edit.js +290 -0
  18. package/dist/definition/edit.js.map +1 -0
  19. package/dist/definition/gateway-pairs.d.ts +24 -0
  20. package/dist/definition/gateway-pairs.d.ts.map +1 -0
  21. package/dist/definition/gateway-pairs.js +133 -0
  22. package/dist/definition/gateway-pairs.js.map +1 -0
  23. package/dist/definition/graph.d.ts +24 -0
  24. package/dist/definition/graph.d.ts.map +1 -0
  25. package/dist/definition/graph.js +32 -0
  26. package/dist/definition/graph.js.map +1 -0
  27. package/dist/definition/schema.d.ts +21 -0
  28. package/dist/definition/schema.d.ts.map +1 -0
  29. package/dist/definition/schema.js +33 -0
  30. package/dist/definition/schema.js.map +1 -0
  31. package/dist/definition/validate.d.ts +33 -0
  32. package/dist/definition/validate.d.ts.map +1 -0
  33. package/dist/definition/validate.js +577 -0
  34. package/dist/definition/validate.js.map +1 -0
  35. package/dist/errors.d.ts +55 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/errors.js +62 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/form/access.d.ts +68 -0
  40. package/dist/form/access.d.ts.map +1 -0
  41. package/dist/form/access.js +125 -0
  42. package/dist/form/access.js.map +1 -0
  43. package/dist/form/field-values.d.ts +42 -0
  44. package/dist/form/field-values.d.ts.map +1 -0
  45. package/dist/form/field-values.js +165 -0
  46. package/dist/form/field-values.js.map +1 -0
  47. package/dist/form/form-source.d.ts +8 -0
  48. package/dist/form/form-source.d.ts.map +1 -0
  49. package/dist/form/form-source.js +40 -0
  50. package/dist/form/form-source.js.map +1 -0
  51. package/dist/form/manifest.d.ts +58 -0
  52. package/dist/form/manifest.d.ts.map +1 -0
  53. package/dist/form/manifest.js +22 -0
  54. package/dist/form/manifest.js.map +1 -0
  55. package/dist/form/validate-manifest.d.ts +14 -0
  56. package/dist/form/validate-manifest.d.ts.map +1 -0
  57. package/dist/form/validate-manifest.js +209 -0
  58. package/dist/form/validate-manifest.js.map +1 -0
  59. package/dist/index.d.ts +30 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +30 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/project.d.ts +85 -0
  64. package/dist/project.d.ts.map +1 -0
  65. package/dist/project.js +14 -0
  66. package/dist/project.js.map +1 -0
  67. package/dist/routing/condition.d.ts +37 -0
  68. package/dist/routing/condition.d.ts.map +1 -0
  69. package/dist/routing/condition.js +136 -0
  70. package/dist/routing/condition.js.map +1 -0
  71. package/dist/routing/routing.d.ts +34 -0
  72. package/dist/routing/routing.d.ts.map +1 -0
  73. package/dist/routing/routing.js +56 -0
  74. package/dist/routing/routing.js.map +1 -0
  75. package/dist/routing/values.d.ts +11 -0
  76. package/dist/routing/values.d.ts.map +1 -0
  77. package/dist/routing/values.js +110 -0
  78. package/dist/routing/values.js.map +1 -0
  79. package/package.json +50 -3
  80. package/src/definition/define.ts +38 -0
  81. package/src/definition/definition.ts +455 -0
  82. package/src/definition/diff.ts +118 -0
  83. package/src/definition/edit.ts +369 -0
  84. package/src/definition/gateway-pairs.ts +159 -0
  85. package/src/definition/graph.ts +50 -0
  86. package/src/definition/schema.ts +49 -0
  87. package/src/definition/validate.ts +684 -0
  88. package/src/errors.ts +107 -0
  89. package/src/form/access.ts +204 -0
  90. package/src/form/field-values.ts +221 -0
  91. package/src/form/form-source.ts +50 -0
  92. package/src/form/manifest.ts +88 -0
  93. package/src/form/validate-manifest.ts +245 -0
  94. package/src/index.ts +29 -0
  95. package/src/project.ts +88 -0
  96. package/src/routing/condition.ts +162 -0
  97. package/src/routing/routing.ts +73 -0
  98. package/src/routing/values.ts +132 -0
  99. package/README.md +0 -3
@@ -0,0 +1,684 @@
1
+ /**
2
+ * 流程定义的校验(docs/decisions/0005 第 7 节):设计器保存时、后端发布时跑同一份规则。只给代号和参数,文案在前端的语言包里。
3
+ * 错误(error)不能发布:引擎会走不下去;警告(warning)可以发布,多半是画漏了。
4
+ *
5
+ * validateProcess(definition, { form: manifest });
6
+ * // → [{ code: 'outcome-unrouted', severity: 'error', node: 'check', params: { outcome: 'back' } }]
7
+ *
8
+ * 要查注册情况的几条(扩展是否注册、调用的流程是否存在、工作日历是否存在)只在给了 context 里对应的函数时才查,后端发布时给。
9
+ */
10
+ import { conditionFields, isConditionComplete, type Condition } from '../routing/condition.ts';
11
+ import {
12
+ isBranching,
13
+ BUILTIN_NODE_TYPES,
14
+ isOrgId,
15
+ isRef,
16
+ type AssigneeSource,
17
+ type FieldAccess,
18
+ type Outcome,
19
+ type ProcessDefinition,
20
+ type ProcessEdge,
21
+ type ProcessNode,
22
+ type TaskNode,
23
+ } from './definition.ts';
24
+ import { gatewayPairs } from './gateway-pairs.ts';
25
+ import { DEFINITION_SCHEMA } from './schema.ts';
26
+ import { processGraph, type ProcessGraph } from './graph.ts';
27
+ import { manifestField, type FormManifest } from '../form/manifest.ts';
28
+
29
+ /** 问题的严重程度 */
30
+ export type Severity = 'error' | 'warning';
31
+
32
+ /** 校验发现的一个问题 */
33
+ export interface Problem {
34
+ readonly code: string;
35
+ readonly severity: Severity;
36
+ readonly node?: string;
37
+ readonly edge?: string;
38
+ readonly lane?: string;
39
+ /** 字段清单的校验:出问题的字段路径(明细表的列写成 `列表.列`) */
40
+ readonly field?: string;
41
+ readonly params?: Readonly<Record<string, string | number>>;
42
+ }
43
+
44
+ /** 扩展的种类 */
45
+ export type ExtensionKind = 'resolver' | 'action' | 'guard' | 'computed' | 'node' | 'completion';
46
+
47
+ /** 校验时能用到的外部信息;后端发布时给全,设计器里按能拿到的给 */
48
+ export interface ValidationContext {
49
+ /** 流程引用的表单的字段清单 */
50
+ readonly form?: FormManifest;
51
+ /** 扩展有没有注册 */
52
+ readonly isRegistered?: (kind: ExtensionKind, name: string) => boolean;
53
+ /** 流程 key 存不存在、有没有停用 */
54
+ readonly processExists?: (key: string) => boolean;
55
+ /** 某个流程(最新版本)调用了哪些流程,查调用成环 */
56
+ readonly callsOf?: (key: string) => readonly string[];
57
+ /** 工作日历存不存在 */
58
+ readonly calendarExists?: (name: string) => boolean;
59
+ }
60
+
61
+ /** 各代号的严重程度;没列出的都是错误 */
62
+ const WARNINGS: ReadonlySet<string> = new Set([
63
+ 'node-unreachable',
64
+ 'edge-default-not-gateway',
65
+ 'gateway-edge-unconditional',
66
+ 'parallel-edge-condition',
67
+ 'parallel-useless',
68
+ 'form-required-unfillable',
69
+ 'return-choose-no-upstream',
70
+ ]);
71
+
72
+ /** `sys.` 下引擎给的只读值;`sys.round.节点` 另外判断 */
73
+ const SYSTEM_NAMES: ReadonlySet<string> = new Set([
74
+ 'initiator',
75
+ 'startedAt',
76
+ 'instanceId',
77
+ 'businessKey',
78
+ ]);
79
+
80
+ /** 校验一个流程定义;问题按规则的先后、再按定义里的先后排 */
81
+ export function validateProcess(
82
+ definition: ProcessDefinition,
83
+ context: ValidationContext = {},
84
+ ): Problem[] {
85
+ const problems: Problem[] = [];
86
+ const report = (
87
+ code: string,
88
+ at: { node?: string; edge?: string; lane?: string } = {},
89
+ params?: Record<string, string | number>,
90
+ ) =>
91
+ problems.push({
92
+ code,
93
+ severity: WARNINGS.has(code) ? 'warning' : 'error',
94
+ ...at,
95
+ ...(params ? { params } : {}),
96
+ });
97
+ const graph = processGraph(definition);
98
+
99
+ if (typeof definition.schema === 'number' && definition.schema > DEFINITION_SCHEMA)
100
+ report('schema-newer', {}, { schema: definition.schema });
101
+ checkIdentities(definition, report);
102
+ checkStartAndEnd(definition, graph, report);
103
+ checkEdges(definition, graph, report);
104
+ for (const node of definition.nodes) checkNode(node, graph, context, report);
105
+ checkReachability(definition, graph, report);
106
+ checkGateways(definition, report);
107
+ checkReturnsAndEscalations(definition, graph, report);
108
+ checkReferences(definition, graph, context, report);
109
+ checkOrgIds(definition, report);
110
+ checkForm(definition, context, report);
111
+ checkPublishOnly(definition, context, report);
112
+ return dedupe(problems);
113
+ }
114
+
115
+ type Report = (
116
+ code: string,
117
+ at?: { node?: string; edge?: string; lane?: string },
118
+ params?: Record<string, string | number>,
119
+ ) => void;
120
+
121
+ /** 同一个代号、同一个位置、同样的参数只留一条 */
122
+ function dedupe(problems: Problem[]): Problem[] {
123
+ const seen = new Set<string>();
124
+ return problems.filter((problem) => {
125
+ const key = JSON.stringify([
126
+ problem.code,
127
+ problem.node,
128
+ problem.edge,
129
+ problem.lane,
130
+ problem.params,
131
+ ]);
132
+ if (seen.has(key)) return false;
133
+ seen.add(key);
134
+ return true;
135
+ });
136
+ }
137
+
138
+ // ---------- 标识、开始与结束、连线 ----------
139
+
140
+ function checkIdentities(definition: ProcessDefinition, report: Report): void {
141
+ const duplicates = (ids: readonly string[]) => ids.filter((id, i) => ids.indexOf(id) !== i);
142
+ for (const id of new Set(duplicates(definition.nodes.map((n) => n.id))))
143
+ report('node-duplicate', { node: id });
144
+ for (const id of new Set(duplicates(definition.edges.map((e) => e.id))))
145
+ report('edge-duplicate', { edge: id });
146
+ for (const id of new Set(duplicates((definition.lanes ?? []).map((l) => l.id))))
147
+ report('lane-duplicate', { lane: id });
148
+ for (const node of definition.nodes) {
149
+ if (!BUILTIN_NODE_TYPES.has(node.type) && !node.type.startsWith('x-'))
150
+ report('node-type-unknown', { node: node.id }, { type: node.type });
151
+ if (
152
+ node.lane !== undefined &&
153
+ !(definition.lanes ?? []).some((lane) => lane.id === node.lane)
154
+ ) {
155
+ report('lane-unknown', { node: node.id }, { lane: node.lane });
156
+ }
157
+ }
158
+ }
159
+
160
+ function checkStartAndEnd(
161
+ definition: ProcessDefinition,
162
+ graph: ProcessGraph,
163
+ report: Report,
164
+ ): void {
165
+ const starts = definition.nodes.filter((n) => n.type === 'start');
166
+ if (starts.length === 0) report('start-missing');
167
+ for (const extra of starts.slice(1)) report('start-multiple', { node: extra.id });
168
+ for (const start of starts)
169
+ if (graph.incoming(start.id).length > 0) report('start-incoming', { node: start.id });
170
+ if (!definition.nodes.some((n) => n.type === 'end')) report('end-missing');
171
+ }
172
+
173
+ function checkEdges(definition: ProcessDefinition, graph: ProcessGraph, report: Report): void {
174
+ for (const edge of definition.edges) {
175
+ for (const side of ['from', 'to'] as const) {
176
+ if (!graph.node(edge[side]))
177
+ report('edge-unknown-node', { edge: edge.id }, { side, node: edge[side] });
178
+ }
179
+ const from = graph.node(edge.from);
180
+ if (!from) continue;
181
+ if (edge.outcome !== undefined) {
182
+ if (!isBranching(from.type))
183
+ report('edge-outcome-not-branching', { edge: edge.id }, { outcome: edge.outcome });
184
+ else {
185
+ const declared = declaredOutcomes(from);
186
+ if (declared && !declared.includes(edge.outcome))
187
+ report('edge-unknown-outcome', { edge: edge.id }, { outcome: edge.outcome });
188
+ }
189
+ }
190
+ if (edge.default && from.type !== 'exclusive' && from.type !== 'inclusive')
191
+ report('edge-default-not-gateway', { edge: edge.id });
192
+ if (edge.when && !isConditionComplete(edge.when))
193
+ report('condition-incomplete', { edge: edge.id });
194
+ }
195
+ }
196
+
197
+ /** 节点写明了的结果;自动节点、调用流程的结果由运行时给出,没有清单 */
198
+ function declaredOutcomes(node: ProcessNode): readonly string[] | undefined {
199
+ if (node.type === 'task') return (node.outcomes ?? []).map((o) => o.key);
200
+ if (node.type === 'receive') return node.outcomes;
201
+ return undefined;
202
+ }
203
+
204
+ // ---------- 各类节点 ----------
205
+
206
+ function checkNode(
207
+ node: ProcessNode,
208
+ graph: ProcessGraph,
209
+ context: ValidationContext,
210
+ report: Report,
211
+ ): void {
212
+ const out = graph.outgoing(node.id);
213
+ if (node.type === 'end') {
214
+ if (out.length > 0) report('end-outgoing', { node: node.id });
215
+ return;
216
+ }
217
+ if (out.length === 0) report('node-no-outgoing', { node: node.id });
218
+
219
+ if (node.type === 'task') checkTask(node, graph, context, report);
220
+ if (node.type === 'receive') {
221
+ const outcomes = node.outcomes ?? [];
222
+ for (const key of new Set(outcomes.filter((k, i) => outcomes.indexOf(k) !== i)))
223
+ report('outcome-duplicate', { node: node.id }, { outcome: key });
224
+ checkUnrouted(node.id, outcomes, out, report);
225
+ if (node.overdue?.action === 'complete' && !outcomes.includes(node.overdue.outcome)) {
226
+ report('overdue-unknown-outcome', { node: node.id }, { outcome: node.overdue.outcome });
227
+ }
228
+ }
229
+ if (node.type === 'exclusive' || node.type === 'inclusive') {
230
+ if (out.filter((e) => e.default).length > 1)
231
+ report('gateway-multiple-default', { node: node.id });
232
+ if (out.length > 1)
233
+ for (const edge of out)
234
+ if (!edge.when && !edge.default) report('gateway-edge-unconditional', { edge: edge.id });
235
+ }
236
+ if (node.type === 'parallel') {
237
+ for (const edge of out) if (edge.when) report('parallel-edge-condition', { edge: edge.id });
238
+ if (out.length === 1 && graph.incoming(node.id).length === 1)
239
+ report('parallel-useless', { node: node.id });
240
+ }
241
+ }
242
+
243
+ function checkTask(
244
+ node: TaskNode,
245
+ graph: ProcessGraph,
246
+ context: ValidationContext,
247
+ report: Report,
248
+ ): void {
249
+ // 草稿里可能还没写结果:当作空的,报 task-no-outcome,而不是校验本身出错
250
+ const outcomes = node.outcomes ?? [];
251
+ const keys = outcomes.map((o) => o.key);
252
+ if (keys.length === 0) report('task-no-outcome', { node: node.id });
253
+ for (const key of new Set(keys.filter((k, i) => keys.indexOf(k) !== i)))
254
+ report('outcome-duplicate', { node: node.id }, { outcome: key });
255
+ // 终止的结果、处理时选退回节点的结果不走出边
256
+ checkUnrouted(
257
+ node.id,
258
+ outcomes.filter((o) => o.kind !== 'terminate' && !choosesTarget(o)).map((o) => o.key),
259
+ graph.outgoing(node.id),
260
+ report,
261
+ );
262
+ for (const outcome of outcomes) {
263
+ if ((outcome.target as string | undefined) !== undefined && !choosesTarget(outcome)) {
264
+ report('return-target-invalid', { node: node.id }, { outcome: outcome.key });
265
+ }
266
+ }
267
+ if (node.overdue?.action === 'complete' && !keys.includes(node.overdue.outcome)) {
268
+ report('overdue-unknown-outcome', { node: node.id }, { outcome: node.overdue.outcome });
269
+ }
270
+ // 引擎自己选的结果(超时自动完成、会签没达到门槛时的 fallback)没人选退回的节点
271
+ const automatic = [
272
+ node.overdue?.action === 'complete' ? node.overdue.outcome : undefined,
273
+ node.multi?.fallback,
274
+ ];
275
+ for (const key of automatic) {
276
+ if (key !== undefined && outcomes.some((o) => o.key === key && choosesTarget(o))) {
277
+ report('outcome-choose-automatic', { node: node.id }, { outcome: key });
278
+ }
279
+ }
280
+ const lane = graph.lane(node.lane);
281
+ // 会签时每份待办给参与人,不看 assignees:参与人是空列表(不是引用)才算没写
282
+ const nobody = node.multi
283
+ ? Array.isArray(node.multi.participants) && node.multi.participants.length === 0
284
+ : !node.assignees?.length;
285
+ if (nobody && !lane?.inbox) report('assignee-missing', { node: node.id });
286
+ const sources = [
287
+ ...(node.assignees ?? []),
288
+ ...(Array.isArray(node.multi?.participants) ? node.multi.participants : []),
289
+ ];
290
+ for (const source of flattenSources(sources)) {
291
+ if ('sameAs' in source && graph.node(source.sameAs)?.type !== 'task') {
292
+ report('assignee-unknown-node', { node: node.id }, { sameAs: source.sameAs });
293
+ }
294
+ }
295
+ const multi = node.multi;
296
+ if (multi && (multi.complete === 'ratio' || multi.complete === 'votes')) {
297
+ if (multi.fallback === undefined) report('multi-no-fallback', { node: node.id });
298
+ else if (!keys.includes(multi.fallback))
299
+ report('multi-no-fallback', { node: node.id }, { fallback: multi.fallback });
300
+ }
301
+ if (
302
+ multi &&
303
+ !['all', 'any', 'ratio', 'votes', 'sequential'].includes(multi.complete) &&
304
+ context.isRegistered?.('completion', multi.complete) === false
305
+ ) {
306
+ report('extension-unknown', { node: node.id }, { kind: 'completion', name: multi.complete });
307
+ }
308
+ }
309
+
310
+ /** 处理时选退回到哪个节点的结果(kind: return、target: choose):不走出边 */
311
+ function choosesTarget(outcome: Outcome): boolean {
312
+ return outcome.kind === 'return' && outcome.target === 'choose';
313
+ }
314
+
315
+ /** 每个结果都要有出边:写明这个结果的,或没写结果的 */
316
+ function checkUnrouted(
317
+ nodeId: string,
318
+ outcomes: readonly string[],
319
+ out: readonly ProcessEdge[],
320
+ report: Report,
321
+ ): void {
322
+ const catchAll = out.some((e) => e.outcome === undefined);
323
+ for (const key of new Set(outcomes)) {
324
+ if (!catchAll && !out.some((e) => e.outcome === key))
325
+ report('outcome-unrouted', { node: nodeId }, { outcome: key });
326
+ }
327
+ }
328
+
329
+ /** 来源连同"上一步选"里嵌着的来源,平铺开 */
330
+ function flattenSources(sources: readonly AssigneeSource[]): AssigneeSource[] {
331
+ return sources.flatMap((source) =>
332
+ 'pick' in source ? [source, ...flattenSources(source.pick.from ?? [])] : [source],
333
+ );
334
+ }
335
+
336
+ // ---------- 走得通 ----------
337
+
338
+ function checkReachability(
339
+ definition: ProcessDefinition,
340
+ graph: ProcessGraph,
341
+ report: Report,
342
+ ): void {
343
+ const start = graph.start;
344
+ if (!start) return;
345
+ const reached = walk([start.id], (id) => graph.outgoing(id).map((e) => e.to));
346
+ for (const node of definition.nodes)
347
+ if (!reached.has(node.id)) report('node-unreachable', { node: node.id });
348
+ const ends = definition.nodes.filter((n) => n.type === 'end').map((n) => n.id);
349
+ if (ends.length === 0) return;
350
+ const reachesEnd = walk(ends, (id) => graph.incoming(id).map((e) => e.from));
351
+ for (const node of definition.nodes) {
352
+ if (reached.has(node.id) && !reachesEnd.has(node.id))
353
+ report('node-dead-end', { node: node.id });
354
+ }
355
+ }
356
+
357
+ /** 从 roots 出发能走到的节点 */
358
+ function walk(roots: readonly string[], next: (id: string) => readonly string[]): Set<string> {
359
+ const seen = new Set(roots);
360
+ const queue = [...roots];
361
+ for (let id = queue.shift(); id !== undefined; id = queue.shift()) {
362
+ for (const to of next(id)) {
363
+ if (!seen.has(to)) {
364
+ seen.add(to);
365
+ queue.push(to);
366
+ }
367
+ }
368
+ }
369
+ return seen;
370
+ }
371
+
372
+ // ---------- 并行与包容的配对(0005 的 4.4) ----------
373
+
374
+ /** 去掉退回、提级连线后的前进图:结构化配对与"上游"都按它算 */
375
+ function forwardEdges(definition: ProcessDefinition, graph: ProcessGraph): ProcessEdge[] {
376
+ return definition.edges.filter(
377
+ (e) => e.kind !== 'return' && e.kind !== 'escalate' && graph.node(e.from) && graph.node(e.to),
378
+ );
379
+ }
380
+
381
+ /** 直接支配节点(Cooper–Harvey–Kennedy 的迭代算法);root 自己映射到自己,走不到的节点不在结果里 */
382
+ /** 并行、包容的分叉与汇合要配对(算法在 gateway-pairs.ts,引擎推进时用同一份) */
383
+ function checkGateways(definition: ProcessDefinition, report: Report): void {
384
+ for (const id of gatewayPairs(definition).unpaired) report('gateway-unpaired', { node: id });
385
+ }
386
+
387
+ // ---------- 退回与提级 ----------
388
+
389
+ function checkReturnsAndEscalations(
390
+ definition: ProcessDefinition,
391
+ graph: ProcessGraph,
392
+ report: Report,
393
+ ): void {
394
+ const edges = forwardEdges(definition, graph);
395
+ const next = (id: string) => edges.filter((e) => e.from === id).map((e) => e.to);
396
+ for (const edge of definition.edges) {
397
+ if (!graph.node(edge.from) || !graph.node(edge.to)) continue;
398
+ if (edge.kind === 'return' && !walk([edge.to], next).has(edge.from))
399
+ report('return-not-upstream', { edge: edge.id });
400
+ if (edge.kind === 'escalate') {
401
+ const target = graph.node(edge.to);
402
+ if (target?.type !== 'task' || !hasInbox(target, graph))
403
+ report('escalate-no-inbox', { edge: edge.id });
404
+ }
405
+ }
406
+ // 处理时选退回节点的结果:前面一个人工节点都没有时,运行时没得选,按钮不出现
407
+ const previous = (id: string) => edges.filter((e) => e.to === id).map((e) => e.from);
408
+ for (const node of definition.nodes) {
409
+ if (node.type !== 'task') continue;
410
+ const choosing = node.outcomes.filter(choosesTarget);
411
+ if (choosing.length === 0) continue;
412
+ const upstream = [...walk([node.id], previous)].some(
413
+ (id) => id !== node.id && graph.node(id)?.type === 'task',
414
+ );
415
+ if (!upstream)
416
+ for (const o of choosing)
417
+ report('return-choose-no-upstream', { node: node.id }, { outcome: o.key });
418
+ }
419
+ }
420
+
421
+ /** 人工节点有没有收件箱:处理人里有角色、部门或扩展的种类,或者没写处理人而泳道有收件箱 */
422
+ function hasInbox(node: TaskNode, graph: ProcessGraph): boolean {
423
+ if (node.assignees === undefined || node.assignees.length === 0)
424
+ return graph.lane(node.lane)?.inbox !== undefined;
425
+ return node.assignees.some((s) => 'role' in s || 'department' in s || 'group' in s);
426
+ }
427
+
428
+ // ---------- 组织的编号 ----------
429
+
430
+ /**
431
+ * 直接写在定义里的用户、角色、部门编号要是正整数(接入方组织表的主键),写成名字(`"role": "finance"`)时报 `org-id-invalid`;
432
+ * 引用(`{ ref }`)到运行时才有值,不在这里查。走的来源同 {@link collectReferences},另加泳道的收件箱本身。与 Java 一致。
433
+ */
434
+ function checkOrgIds(definition: ProcessDefinition, report: Report): void {
435
+ const check = (sources: readonly AssigneeSource[] | undefined, at: { node?: string }) => {
436
+ for (const source of flattenSources(sources ?? [])) {
437
+ const id =
438
+ 'user' in source
439
+ ? source.user
440
+ : 'role' in source
441
+ ? source.role
442
+ : 'department' in source
443
+ ? source.department
444
+ : 'group' in source
445
+ ? source.id
446
+ : undefined;
447
+ if (id !== undefined && !isRef(id) && !isOrgId(id))
448
+ report('org-id-invalid', at, { value: String(id) });
449
+ }
450
+ };
451
+ check(definition.starters, {});
452
+ for (const lane of definition.lanes ?? []) {
453
+ if (!lane.inbox) continue;
454
+ check([lane.inbox as AssigneeSource], {});
455
+ check(lane.inbox.manager, {});
456
+ }
457
+ for (const node of definition.nodes) {
458
+ if (node.type === 'task') {
459
+ check(node.assignees, { node: node.id });
460
+ if (node.multi && !isRef(node.multi.participants))
461
+ check(node.multi.participants, { node: node.id });
462
+ } else if (node.type === 'cc') check(node.to, { node: node.id });
463
+ }
464
+ }
465
+
466
+ // ---------- 引用(0005 的 1.1) ----------
467
+
468
+ interface Reference {
469
+ readonly name: string;
470
+ readonly at: { node?: string; edge?: string };
471
+ /** 用在连线条件里(`fn.` 只能用在这里) */
472
+ readonly inCondition?: boolean;
473
+ /** 期望的类型,查 ref-type-mismatch */
474
+ readonly expect?: 'people' | 'date' | 'list';
475
+ }
476
+
477
+ function checkReferences(
478
+ definition: ProcessDefinition,
479
+ graph: ProcessGraph,
480
+ context: ValidationContext,
481
+ report: Report,
482
+ ): void {
483
+ // 单据的字段也是流程变量(引擎把单据的值存在变量里):标题模板、条件不写 form. 也认得;声明了的变量优先
484
+ const manifest = context.form ?? definition.form?.manifest ?? {};
485
+ const variables = new Map<string, { type: string }>([
486
+ ...Object.entries(manifest).map(([name, field]) => [name, { type: field.type }] as const),
487
+ ...(definition.variables ?? []).map((v) => [v.name, v] as const),
488
+ ]);
489
+ for (const ref of collectReferences(definition)) {
490
+ const problem = resolveReference(ref, definition, graph, variables, context);
491
+ if (problem) report(problem.code, ref.at, problem.params);
492
+ }
493
+ for (const edge of definition.edges) {
494
+ for (const effect of edge.effects ?? []) {
495
+ const target = 'set' in effect ? effect.set : effect.increment;
496
+ if (!variables.has(target)) report('ref-unknown', { edge: edge.id }, { ref: target });
497
+ }
498
+ }
499
+ }
500
+
501
+ function resolveReference(
502
+ ref: Reference,
503
+ definition: ProcessDefinition,
504
+ graph: ProcessGraph,
505
+ variables: ReadonlyMap<string, { type: string }>,
506
+ context: ValidationContext,
507
+ ): { code: string; params: Record<string, string> } | undefined {
508
+ const { name } = ref;
509
+ const unknown = { code: 'ref-unknown', params: { ref: name } };
510
+ if (name.startsWith('form.')) {
511
+ if (!definition.form) return unknown;
512
+ const manifest = context.form ?? definition.form.manifest;
513
+ if (!manifest) return undefined;
514
+ const field = manifestField(manifest, name.slice(5));
515
+ if (!field) return unknown;
516
+ return mismatch(ref, field.type, field.multiple === true)
517
+ ? { code: 'ref-type-mismatch', params: { ref: name, type: field.type } }
518
+ : undefined;
519
+ }
520
+ if (name.startsWith('sys.')) {
521
+ const rest = name.slice(4);
522
+ if (SYSTEM_NAMES.has(rest)) return undefined;
523
+ if (rest.startsWith('round.') && graph.node(rest.slice(6))) return undefined;
524
+ return unknown;
525
+ }
526
+ if (name.startsWith('fn.')) {
527
+ if (!ref.inCondition) return unknown;
528
+ return context.isRegistered?.('computed', name.slice(3)) === false
529
+ ? { code: 'extension-unknown', params: { kind: 'computed', name: name.slice(3) } }
530
+ : undefined;
531
+ }
532
+ const variable = variables.get(name);
533
+ if (!variable) return unknown;
534
+ return mismatch(ref, variable.type, false)
535
+ ? { code: 'ref-type-mismatch', params: { ref: name, type: variable.type } }
536
+ : undefined;
537
+ }
538
+
539
+ /** 引用的类型用不上 */
540
+ function mismatch(ref: Reference, type: string, multiple: boolean): boolean {
541
+ switch (ref.expect) {
542
+ case 'people':
543
+ return type !== 'people' && type !== 'text' && type !== 'select';
544
+ case 'date':
545
+ return type !== 'date' && type !== 'datetime';
546
+ case 'list':
547
+ return type !== 'list' && type !== 'people' && !(type === 'select' && multiple);
548
+ default:
549
+ return false;
550
+ }
551
+ }
552
+
553
+ /** 定义里所有的引用,连同它们在哪 */
554
+ function collectReferences(definition: ProcessDefinition): Reference[] {
555
+ const refs: Reference[] = [];
556
+ const add = (value: unknown, at: Reference['at'], expect?: Reference['expect']) => {
557
+ if (isRef(value)) refs.push({ name: value.ref, at, ...(expect ? { expect } : {}) });
558
+ };
559
+ const addCondition = (condition: Condition | undefined, at: Reference['at']) => {
560
+ if (condition)
561
+ for (const field of conditionFields(condition))
562
+ refs.push({ name: field, at, inCondition: true });
563
+ };
564
+ const addSources = (sources: readonly AssigneeSource[] | undefined, at: Reference['at']) => {
565
+ for (const source of flattenSources(sources ?? [])) {
566
+ if ('user' in source) add(source.user, at, 'people');
567
+ if ('role' in source) add(source.role, at);
568
+ if ('department' in source) add(source.department, at);
569
+ if ('group' in source) add(source.id, at);
570
+ }
571
+ };
572
+ const addDue = (due: unknown, at: Reference['at']) => {
573
+ if (typeof due === 'object' && due !== null && 'until' in due)
574
+ add((due as { until: unknown }).until, at, 'date');
575
+ };
576
+ for (const name of definition.summary ?? []) refs.push({ name, at: {} });
577
+ for (const match of (definition.title ?? '').matchAll(/\{([^{}]+)\}/g))
578
+ refs.push({ name: match[1]!.trim(), at: {} });
579
+ addSources(definition.starters, {});
580
+ for (const lane of definition.lanes ?? []) addSources(lane.inbox?.manager, {});
581
+ for (const node of definition.nodes) {
582
+ const at = { node: node.id };
583
+ if (node.type === 'task') {
584
+ addSources(node.assignees, at);
585
+ if (node.multi) {
586
+ if (isRef(node.multi.participants)) add(node.multi.participants, at, 'list');
587
+ else addSources(node.multi.participants, at);
588
+ }
589
+ addDue(node.due, at);
590
+ } else if (node.type === 'timer') addDue(node.wait, at);
591
+ else if (node.type === 'receive') addDue(node.due, at);
592
+ else if (node.type === 'cc') addSources(node.to, at);
593
+ else if (node.type === 'call') {
594
+ add(node.forEach, at, 'list');
595
+ for (const value of Object.values(node.input ?? {})) {
596
+ // forEach 循环里那一项(及它的字段 as.名字)只在 input 里有效
597
+ if (
598
+ isRef(value) &&
599
+ node.as &&
600
+ (value.ref === node.as || value.ref.startsWith(node.as + '.'))
601
+ )
602
+ continue;
603
+ add(value, at);
604
+ }
605
+ } else if (node.type === 'service')
606
+ for (const value of Object.values(node.args ?? {})) add(value, at);
607
+ }
608
+ for (const edge of definition.edges) {
609
+ addCondition(edge.when, { edge: edge.id });
610
+ for (const effect of edge.effects ?? [])
611
+ if ('set' in effect) add(effect.value, { edge: edge.id });
612
+ }
613
+ return refs;
614
+ }
615
+
616
+ // ---------- 表单(0004 第 4 节) ----------
617
+
618
+ function checkForm(
619
+ definition: ProcessDefinition,
620
+ context: ValidationContext,
621
+ report: Report,
622
+ ): void {
623
+ const manifest = context.form ?? definition.form?.manifest;
624
+ if (!manifest) return;
625
+ for (const node of definition.nodes) {
626
+ if (node.type !== 'task' && node.type !== 'start') continue;
627
+ for (const path of Object.keys(node.form?.fields ?? {})) {
628
+ if (!manifestField(manifest, path))
629
+ report('form-field-unknown', { node: node.id }, { field: path });
630
+ }
631
+ }
632
+ const start = definition.nodes.find((n) => n.type === 'start');
633
+ if (start?.type !== 'start') return;
634
+ const access = (name: string): FieldAccess =>
635
+ start.form?.fields?.[name] ?? start.form?.default ?? 'editable';
636
+ for (const [name, field] of Object.entries(manifest)) {
637
+ if (field.required && (access(name) === 'hidden' || access(name) === 'readonly')) {
638
+ report('form-required-unfillable', { node: start.id }, { field: name });
639
+ }
640
+ }
641
+ }
642
+
643
+ // ---------- 只在发布时查的(要后端的注册情况) ----------
644
+
645
+ function checkPublishOnly(
646
+ definition: ProcessDefinition,
647
+ context: ValidationContext,
648
+ report: Report,
649
+ ): void {
650
+ const registered = context.isRegistered;
651
+ if (registered) {
652
+ const need = (kind: ExtensionKind, name: string, at: { node?: string; edge?: string }) => {
653
+ if (!registered(kind, name)) report('extension-unknown', at, { kind, name });
654
+ };
655
+ for (const node of definition.nodes) {
656
+ const at = { node: node.id };
657
+ if (node.type.startsWith('x-')) need('node', node.type, at);
658
+ if (node.type === 'service') need('action', node.action, at);
659
+ if (node.type === 'task') {
660
+ for (const outcome of node.outcomes ?? [])
661
+ for (const guard of outcome.guards ?? []) need('guard', guard, at);
662
+ for (const source of flattenSources(node.assignees ?? []))
663
+ if ('resolver' in source) need('resolver', source.resolver, at);
664
+ }
665
+ }
666
+ }
667
+ if (context.processExists) {
668
+ for (const node of definition.nodes) {
669
+ if (node.type === 'call' && !context.processExists(node.process))
670
+ report('call-unknown-process', { node: node.id }, { process: node.process });
671
+ }
672
+ }
673
+ if (context.callsOf) {
674
+ const calls = definition.nodes
675
+ .filter((n) => n.type === 'call')
676
+ .map((n) => (n as { process: string }).process);
677
+ const reaches = walk(calls, (key) => (key === definition.key ? [] : context.callsOf!(key)));
678
+ if (reaches.has(definition.key)) report('call-cycle', {}, { process: definition.key });
679
+ }
680
+ const calendar = definition.settings?.calendar;
681
+ if (calendar !== undefined && context.calendarExists && !context.calendarExists(calendar)) {
682
+ report('due-unknown-calendar', {}, { calendar });
683
+ }
684
+ }