@bpmn-nova/studio 0.3.9-preview → 0.4.1

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 (79) hide show
  1. package/README.md +2 -2
  2. package/dist/canvas.js +97 -25
  3. package/dist/config.js +13 -0
  4. package/dist/context-menu.js +41 -32
  5. package/dist/controller.js +45 -19
  6. package/dist/flow-tree.d.ts +4 -0
  7. package/dist/flow-tree.js +14 -0
  8. package/dist/index.d.ts +47 -2
  9. package/dist/index.js +1 -0
  10. package/dist/interactions.js +6 -1
  11. package/dist/modules/bpmn-model/index.d.ts +2 -1
  12. package/dist/modules/bpmn-model/index.js +12 -10
  13. package/dist/modules/core/gateway.js +16 -13
  14. package/dist/modules/core/index.d.ts +6 -4
  15. package/dist/modules/core/model.js +12 -7
  16. package/dist/modules/designer/index.d.ts +5 -1
  17. package/dist/modules/designer/index.js +36 -15
  18. package/dist/modules/export-svg/index.d.ts +12 -5
  19. package/dist/modules/export-svg/preview.js +34 -24
  20. package/dist/modules/export-svg/render.js +102 -50
  21. package/dist/modules/flow-tree/controller.js +364 -0
  22. package/dist/modules/flow-tree/index.d.ts +248 -0
  23. package/dist/modules/flow-tree/index.js +5 -0
  24. package/dist/modules/flow-tree/operations.js +484 -0
  25. package/dist/modules/flow-tree/sample.js +445 -0
  26. package/dist/modules/flow-tree/schema.js +588 -0
  27. package/dist/modules/flow-tree/validate.js +125 -0
  28. package/dist/modules/flow-tree-bpmn/compiler.js +547 -0
  29. package/dist/modules/flow-tree-bpmn/decompiler.js +524 -0
  30. package/dist/modules/flow-tree-bpmn/expression.js +135 -0
  31. package/dist/modules/flow-tree-bpmn/index.d.ts +53 -0
  32. package/dist/modules/flow-tree-bpmn/index.js +14 -0
  33. package/dist/modules/flow-tree-renderer/canvas.js +1003 -0
  34. package/dist/modules/flow-tree-renderer/export-svg.js +325 -0
  35. package/dist/modules/flow-tree-renderer/index.d.ts +143 -0
  36. package/dist/modules/flow-tree-renderer/index.js +3 -0
  37. package/dist/modules/flow-tree-renderer/shell.js +970 -0
  38. package/dist/modules/i18n/index.d.ts +647 -0
  39. package/dist/modules/i18n/index.js +247 -0
  40. package/dist/modules/i18n/locales/en-US.js +1222 -0
  41. package/dist/modules/i18n/locales/zh-CN.js +1204 -0
  42. package/dist/modules/icons/index.js +23 -0
  43. package/dist/modules/node-presentation/index.d.ts +3 -2
  44. package/dist/modules/node-presentation/index.js +14 -11
  45. package/dist/modules/palette/index.d.ts +6 -1
  46. package/dist/modules/palette/index.js +26 -8
  47. package/dist/modules/palette/panel.js +44 -6
  48. package/dist/modules/properties/index.d.ts +2 -1
  49. package/dist/modules/properties/index.js +2 -2
  50. package/dist/modules/properties-activiti/index.js +84 -59
  51. package/dist/modules/properties-bpmn/index.js +151 -128
  52. package/dist/modules/properties-core/index.d.ts +9 -3
  53. package/dist/modules/properties-core/index.js +16 -4
  54. package/dist/modules/properties-flow-tree/index.d.ts +56 -0
  55. package/dist/modules/properties-flow-tree/index.js +2 -0
  56. package/dist/modules/properties-flow-tree/panel.js +1136 -0
  57. package/dist/modules/properties-flow-tree/widgets.js +625 -0
  58. package/dist/modules/properties-flowable/index.js +55 -34
  59. package/dist/modules/properties-renderer/index.d.ts +5 -1
  60. package/dist/modules/properties-renderer/index.js +110 -42
  61. package/dist/modules/renderer-svg/index.d.ts +6 -2
  62. package/dist/modules/renderer-svg/index.js +113 -38
  63. package/dist/modules/runtime/index.d.ts +33 -5
  64. package/dist/modules/runtime/index.js +97 -73
  65. package/dist/modules/runtime/time.js +89 -4
  66. package/dist/modules/runtime/visits.js +6 -4
  67. package/dist/modules/theme/index.d.ts +5 -2
  68. package/dist/modules/theme/index.js +8 -4
  69. package/dist/modules/viewer/index.d.ts +28 -7
  70. package/dist/modules/viewer/index.js +223 -58
  71. package/dist/modules/viewer/runtime-content.js +26 -20
  72. package/dist/modules/viewer/runtime-trace.js +43 -25
  73. package/dist/modules/viewer/timeline.js +103 -36
  74. package/dist/shell.js +258 -75
  75. package/dist/sidebars.js +3 -1
  76. package/dist/styles.css +2371 -2
  77. package/llms-full.txt +586 -47
  78. package/llms.txt +6 -5
  79. package/package.json +7 -3
@@ -0,0 +1,524 @@
1
+ import { getScopeGraph, NODE_DEFINITIONS } from '../core/index.js';
2
+ import { importBpmn } from '../bpmn-model/index.js';
3
+ import {
4
+ cloneFlowTree,
5
+ createFlowTreeBranch,
6
+ createFlowTreeNode,
7
+ createFlowTreeRoute,
8
+ normalizeFlowTreeDocument,
9
+ } from '../flow-tree/index.js';
10
+ import { computeTopologyFingerprint } from './compiler.js';
11
+
12
+ function extractTaggedJson(rawList = [], tagLocalName) {
13
+ for (const raw of rawList || []) {
14
+ const text = String(raw || '');
15
+ const regex = new RegExp(`<(?:[\\w-]+:)?${tagLocalName}\\b[^>]*>(?:<!\\[CDATA\\[)?([\\s\\S]*?)(?:\\]\\]>)?<\\/(?:[\\w-]+:)?${tagLocalName}>`);
16
+ const match = text.match(regex);
17
+ if (!match) continue;
18
+ try {
19
+ const jsonText = match[1].replaceAll(']]]]><![CDATA[>', ']]>');
20
+ return JSON.parse(jsonText);
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+ return null;
26
+ }
27
+
28
+ function extractMetaTag(rawList = []) {
29
+ for (const raw of rawList || []) {
30
+ const text = String(raw || '');
31
+ const match = text.match(/<(?:[\w-]+:)?flowTreeMeta\b([^>]*)>(?:<!\[CDATA\[)?([\s\S]*?)(?:\]\]>)?<\/(?:[\w-]+:)?flowTreeMeta>/);
32
+ if (!match) continue;
33
+ const attrs = match[1] || '';
34
+ const hashMatch = attrs.match(/topologyHash="([^"]+)"/);
35
+ try {
36
+ const jsonText = match[2].replaceAll(']]]]><![CDATA[>', ']]>');
37
+ return {
38
+ topologyHash: hashMatch ? hashMatch[1] : '',
39
+ document: JSON.parse(jsonText),
40
+ };
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+
48
+ function syncNamesFromModel(doc, bpmnModel) {
49
+ const byId = new Map((bpmnModel.nodes || []).map((item) => [item.id, item]));
50
+ const edgeByBranch = new Map();
51
+ for (const edge of bpmnModel.edges || []) {
52
+ const branchId = edge.properties?.extensionAttributes?.['nova:branchId'];
53
+ if (branchId) edgeByBranch.set(branchId, edge);
54
+ }
55
+ doc.id = bpmnModel.id || doc.id;
56
+ doc.name = bpmnModel.name || doc.name;
57
+ doc.engine = bpmnModel.engine || doc.engine;
58
+ if (byId.has(doc.starter.id)) doc.starter.name = byId.get(doc.starter.id).name || doc.starter.name;
59
+ if (byId.has(doc.end.id)) doc.end.name = byId.get(doc.end.id).name || doc.end.name;
60
+
61
+ const visit = (steps) => {
62
+ for (const step of steps || []) {
63
+ if (Array.isArray(step.branches)) {
64
+ for (const branch of step.branches) {
65
+ const edge = edgeByBranch.get(branch.id);
66
+ if (edge?.name) branch.name = edge.name;
67
+ visit(branch.steps);
68
+ }
69
+ } else if (byId.has(step.id)) {
70
+ step.name = byId.get(step.id).name || step.name;
71
+ }
72
+ }
73
+ };
74
+ visit(doc.steps);
75
+ }
76
+
77
+ function isFlowNode(node) {
78
+ const kind = NODE_DEFINITIONS[node?.type]?.kind;
79
+ return ['event', 'task', 'container', 'gateway'].includes(kind);
80
+ }
81
+
82
+ function convertBpmnNodeToFlowTreeStep(node, scopeModel, fullModel, options, diagnostics) {
83
+ const extConfig = extractTaggedJson(node.extensionElements, 'nodeConfig');
84
+ const nodeKind = node.properties?.extensionAttributes?.['nova:nodeKind'] || '';
85
+
86
+ if (extConfig?.type && !['starter', 'end'].includes(extConfig.type)) {
87
+ return createFlowTreeNode(extConfig.type, {
88
+ id: node.id,
89
+ name: node.name,
90
+ config: extConfig.config || {},
91
+ }, options);
92
+ }
93
+
94
+ if (nodeKind === 'cc') {
95
+ return createFlowTreeNode('cc', {
96
+ id: node.id,
97
+ name: node.name,
98
+ config: {
99
+ delegateExpression: node.properties?.implementation || '${novaCcDelegate}',
100
+ },
101
+ }, options);
102
+ }
103
+
104
+ if (node.type === 'userTask') {
105
+ const p = node.properties || {};
106
+ const targetType = nodeKind === 'handler' ? 'handler' : 'approver';
107
+ let assigneeType = 'users';
108
+ const targets = { users: [], roles: [], departments: [] };
109
+ let expression = '';
110
+ if (p.candidateGroups) {
111
+ assigneeType = 'roles';
112
+ targets.roles = String(p.candidateGroups).split(',').map((s) => s.trim()).filter(Boolean).map((id) => ({ id, name: id }));
113
+ } else if (p.candidateUsers) {
114
+ assigneeType = 'users';
115
+ targets.users = String(p.candidateUsers).split(',').map((s) => s.trim()).filter(Boolean).map((id) => ({ id, name: id }));
116
+ } else if (p.assignee) {
117
+ if (p.assignee.includes('${')) {
118
+ assigneeType = 'expression';
119
+ expression = p.assignee;
120
+ } else {
121
+ assigneeType = 'users';
122
+ targets.users = [{ id: p.assignee, name: p.assignee }];
123
+ }
124
+ }
125
+ const mode = p.loopType === 'sequential'
126
+ ? 'sequential'
127
+ : p.loopType === 'parallel'
128
+ ? (String(p.completionCondition || '').includes('>= 1') ? 'or' : 'and')
129
+ : 'or';
130
+
131
+ return createFlowTreeNode(targetType, {
132
+ id: node.id,
133
+ name: node.name,
134
+ config: {
135
+ assigneeType,
136
+ targets,
137
+ expression,
138
+ ...(targetType === 'handler' ? { completionMode: mode } : { approvalMode: mode }),
139
+ },
140
+ }, options);
141
+ }
142
+
143
+ if (node.type === 'timerIntermediateCatchEvent') {
144
+ const p = node.properties || {};
145
+ const config = {};
146
+ if (p.timerType === 'date') {
147
+ config.delayType = 'fixedDate';
148
+ config.fixedDate = p.timerValue || '';
149
+ } else if (p.timerType === 'cycle') {
150
+ config.delayType = 'cron';
151
+ config.cronExpression = p.timerValue || '';
152
+ } else {
153
+ config.delayType = 'duration';
154
+ const match = String(p.timerValue || '').match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/i);
155
+ if (match?.[1]) { config.duration = Number(match[1]); config.unit = 'day'; }
156
+ else if (match?.[2]) { config.duration = Number(match[2]); config.unit = 'hour'; }
157
+ else if (match?.[3]) { config.duration = Number(match[3]); config.unit = 'minute'; }
158
+ else { config.duration = 1; config.unit = 'hour'; }
159
+ }
160
+ return createFlowTreeNode('delay', { id: node.id, name: node.name, config }, options);
161
+ }
162
+
163
+ if (node.type === 'serviceTask' || node.type === 'sendTask' || node.type === 'scriptTask' || node.type === 'businessRuleTask') {
164
+ const p = node.properties || {};
165
+ const triggerType = p.implementationType === 'class'
166
+ ? 'serviceClass'
167
+ : p.implementationType === 'expression'
168
+ ? 'expression'
169
+ : 'delegateExpression';
170
+ return createFlowTreeNode('trigger', {
171
+ id: node.id,
172
+ name: node.name,
173
+ config: {
174
+ triggerType,
175
+ implementation: p.implementation || '',
176
+ resultVariable: p.resultVariable || '',
177
+ async: Boolean(p.async),
178
+ retryCycle: p.failedJobRetryTimeCycle || '',
179
+ fields: cloneFlowTree(p.fields || []),
180
+ },
181
+ }, options);
182
+ }
183
+
184
+ if (node.type === 'callActivity') {
185
+ const p = node.properties || {};
186
+ return createFlowTreeNode('subFlow', {
187
+ id: node.id,
188
+ name: node.name,
189
+ config: {
190
+ subFlowMode: 'callActivity',
191
+ calledElement: p.calledElement || '',
192
+ inheritBusinessKey: p.inheritBusinessKey !== false,
193
+ inheritVariables: p.inheritVariables !== false,
194
+ inParameters: cloneFlowTree(p.inParameters || []),
195
+ outParameters: cloneFlowTree(p.outParameters || []),
196
+ },
197
+ }, options);
198
+ }
199
+
200
+ if (node.type === 'subProcess') {
201
+ const inner = reduceScopeToSteps(fullModel, node.id, options, diagnostics);
202
+ return createFlowTreeNode('subFlow', {
203
+ id: node.id,
204
+ name: node.name,
205
+ config: {
206
+ subFlowMode: 'embedded',
207
+ steps: inner.steps,
208
+ },
209
+ }, options);
210
+ }
211
+
212
+ diagnostics.push({
213
+ level: 'warning',
214
+ code: 'unsupported-node-type',
215
+ elementId: node.id,
216
+ message: `BPMN element "${node.name || node.id}" (${node.type}) was mapped as a generic trigger node.`,
217
+ });
218
+ return createFlowTreeNode('trigger', {
219
+ id: node.id,
220
+ name: node.name || node.id,
221
+ config: { triggerType: 'delegateExpression', implementation: '' },
222
+ }, options);
223
+ }
224
+
225
+ function reduceScopeToSteps(fullModel, scopeId, options, diagnostics) {
226
+ const scope = getScopeGraph(fullModel, scopeId);
227
+ const flowNodes = scope.nodes.filter(isFlowNode);
228
+ const byId = new Map(flowNodes.map((n) => [n.id, n]));
229
+ const unsupportedNodes = scope.nodes.filter((n) => ['boundary', 'participant', 'lane'].includes(NODE_DEFINITIONS[n.type]?.kind));
230
+ for (const item of unsupportedNodes) {
231
+ diagnostics.push({
232
+ level: 'error',
233
+ code: 'unsupported-topology-element',
234
+ elementId: item.id,
235
+ message: `Element "${item.name || item.id}" (${item.type}) is not supported in structured FlowTree mode.`,
236
+ });
237
+ }
238
+
239
+ const outgoing = new Map(flowNodes.map((n) => [n.id, []]));
240
+ const incoming = new Map(flowNodes.map((n) => [n.id, []]));
241
+ for (const edge of scope.edges) {
242
+ if ((edge.type || 'sequenceFlow') !== 'sequenceFlow') continue;
243
+ if (!byId.has(edge.source) || !byId.has(edge.target)) continue;
244
+ outgoing.get(edge.source).push(edge);
245
+ incoming.get(edge.target).push(edge);
246
+ }
247
+
248
+ const starts = flowNodes.filter((n) => NODE_DEFINITIONS[n.type]?.eventStage === 'start');
249
+ const ends = flowNodes.filter((n) => NODE_DEFINITIONS[n.type]?.eventStage === 'end');
250
+ if (starts.length !== 1) {
251
+ diagnostics.push({
252
+ level: 'error',
253
+ code: 'invalid-start-count',
254
+ elementId: starts[0]?.id || null,
255
+ message: `Expected exactly 1 startEvent in scope "${scopeId}", found ${starts.length}.`,
256
+ });
257
+ return { starter: null, steps: [], end: null, compatible: false };
258
+ }
259
+ if (ends.length !== 1) {
260
+ diagnostics.push({
261
+ level: 'error',
262
+ code: 'invalid-end-count',
263
+ elementId: ends[0]?.id || null,
264
+ message: `Expected exactly 1 endEvent in scope "${scopeId}", found ${ends.length}.`,
265
+ });
266
+ return { starter: null, steps: [], end: null, compatible: false };
267
+ }
268
+
269
+ // Compute reachable sets from every node to locate immediate join gateways cleanly
270
+ const reachableFrom = (startId) => {
271
+ const visited = new Set();
272
+ const queue = [startId];
273
+ while (queue.length) {
274
+ const id = queue.shift();
275
+ if (visited.has(id)) continue;
276
+ visited.add(id);
277
+ for (const edge of outgoing.get(id) || []) queue.push(edge.target);
278
+ }
279
+ return visited;
280
+ };
281
+
282
+ const findJoinGateway = (splitId, stopId) => {
283
+ const outEdges = outgoing.get(splitId) || [];
284
+ if (outEdges.length < 2) return null;
285
+ const branchReachSets = outEdges.map((edge) => reachableFrom(edge.target));
286
+ const common = [...branchReachSets[0]].filter((id) => id !== splitId && branchReachSets.every((set) => set.has(id)));
287
+ if (!common.length) return null;
288
+ // Choose the earliest common node (minimum distance along branch 0) that has incoming >= 2
289
+ const dist = new Map();
290
+ const queue = [[outEdges[0].target, 0]];
291
+ while (queue.length) {
292
+ const [id, d] = queue.shift();
293
+ if (dist.has(id)) continue;
294
+ dist.set(id, d);
295
+ if (id === stopId) continue;
296
+ for (const edge of outgoing.get(id) || []) queue.push([edge.target, d + 1]);
297
+ }
298
+ const candidates = common
299
+ .filter((id) => (incoming.get(id) || []).length >= 2)
300
+ .sort((a, b) => (dist.get(a) ?? 999999) - (dist.get(b) ?? 999999));
301
+ return candidates[0] || null;
302
+ };
303
+
304
+ const visitedGlobal = new Set();
305
+
306
+ const reduceChain = (startNodeId, stopNodeId, activeStack = new Set()) => {
307
+ const steps = [];
308
+ let currentId = startNodeId;
309
+ while (currentId && currentId !== stopNodeId) {
310
+ if (activeStack.has(currentId)) {
311
+ diagnostics.push({
312
+ level: 'error',
313
+ code: 'cycle-detected',
314
+ elementId: currentId,
315
+ message: `Cycle detected at "${currentId}". Structured FlowTree does not support arbitrary graph loops.`,
316
+ });
317
+ return steps;
318
+ }
319
+ if (visitedGlobal.has(currentId)) {
320
+ diagnostics.push({
321
+ level: 'error',
322
+ code: 'cross-branch-merge',
323
+ elementId: currentId,
324
+ message: `Non-structured cross-branch merge detected at "${currentId}".`,
325
+ });
326
+ return steps;
327
+ }
328
+ const node = byId.get(currentId);
329
+ if (!node) break;
330
+ activeStack.add(currentId);
331
+ visitedGlobal.add(currentId);
332
+
333
+ const outs = outgoing.get(currentId) || [];
334
+ const def = NODE_DEFINITIONS[node.type];
335
+ if (def?.kind === 'gateway' && outs.length >= 2) {
336
+ const joinId = findJoinGateway(currentId, stopNodeId);
337
+ if (!joinId) {
338
+ diagnostics.push({
339
+ level: 'error',
340
+ code: 'unpaired-gateway',
341
+ elementId: currentId,
342
+ message: `Gateway "${node.name || node.id}" does not reconverge at a single join node.`,
343
+ });
344
+ return steps;
345
+ }
346
+ const routeType = node.type === 'parallelGateway'
347
+ ? 'parallelRoute'
348
+ : node.type === 'inclusiveGateway'
349
+ ? 'inclusiveRoute'
350
+ : 'conditionRoute';
351
+ const routeId = node.properties?.extensionAttributes?.['nova:routeId'] || node.id.replace(/__split$/, '');
352
+ const branches = outs.map((edge, idx) => {
353
+ const branchMeta = extractTaggedJson(edge.extensionElements, 'branchConfig');
354
+ const isDefault = Boolean(edge.isDefault || node.defaultFlowId === edge.id);
355
+ const branchSteps = edge.target === joinId
356
+ ? []
357
+ : reduceChain(edge.target, joinId, new Set(activeStack));
358
+ return createFlowTreeBranch(routeType, {
359
+ id: branchMeta?.id || edge.properties?.extensionAttributes?.['nova:branchId'] || edge.id,
360
+ name: branchMeta?.name || edge.name || undefined,
361
+ priority: branchMeta?.priority || idx + 1,
362
+ isDefault: routeType === 'parallelRoute' ? false : isDefault,
363
+ config: branchMeta?.config || (edge.condition ? { mode: 'expression', expression: edge.condition, conditionGroups: [] } : {}),
364
+ steps: branchSteps,
365
+ }, options);
366
+ });
367
+ const route = createFlowTreeRoute(routeType, {
368
+ id: routeId,
369
+ name: node.name || undefined,
370
+ branches,
371
+ }, options);
372
+ steps.push(route);
373
+
374
+ // Advance past join gateway
375
+ if (joinId === stopNodeId) break;
376
+ const joinNode = byId.get(joinId);
377
+ const joinOuts = outgoing.get(joinId) || [];
378
+ if (NODE_DEFINITIONS[joinNode?.type]?.kind === 'gateway') {
379
+ visitedGlobal.add(joinId);
380
+ currentId = joinOuts[0]?.target || null;
381
+ } else {
382
+ // Implicit join directly on a task/end node: continue from joinId itself
383
+ currentId = joinId;
384
+ }
385
+ continue;
386
+ }
387
+
388
+ steps.push(convertBpmnNodeToFlowTreeStep(node, scope, fullModel, options, diagnostics));
389
+ if (outs.length > 1) {
390
+ diagnostics.push({
391
+ level: 'error',
392
+ code: 'multiple-outgoing-without-gateway',
393
+ elementId: currentId,
394
+ message: `Node "${node.name || node.id}" has multiple outgoing sequence flows without a gateway.`,
395
+ });
396
+ return steps;
397
+ }
398
+ currentId = outs[0]?.target || null;
399
+ }
400
+ return steps;
401
+ };
402
+
403
+ const startNode = starts[0];
404
+ const endNode = ends[0];
405
+ visitedGlobal.add(startNode.id);
406
+ const startOuts = outgoing.get(startNode.id) || [];
407
+ let starter = createFlowTreeNode('starter', {
408
+ id: startNode.id,
409
+ name: startNode.name || undefined,
410
+ }, options);
411
+ let starterCompileMode = 'startEvent';
412
+ let firstStepId = startOuts[0]?.target || null;
413
+
414
+ // Detect StartEvent -> UserTask(starter) pattern
415
+ if (firstStepId) {
416
+ const firstNode = byId.get(firstStepId);
417
+ const isMarkedStarter = firstNode?.properties?.extensionAttributes?.['nova:nodeKind'] === 'starter'
418
+ || startNode.properties?.extensionAttributes?.['nova:starterEventFor'] === firstStepId;
419
+ if (firstNode?.type === 'userTask' && isMarkedStarter) {
420
+ const starterMeta = extractTaggedJson(firstNode.extensionElements, 'nodeConfig');
421
+ starter = createFlowTreeNode('starter', {
422
+ id: firstNode.id,
423
+ name: firstNode.name || undefined,
424
+ config: starterMeta?.config || {},
425
+ }, options);
426
+ starterCompileMode = 'startAndUserTask';
427
+ visitedGlobal.add(firstNode.id);
428
+ firstStepId = (outgoing.get(firstNode.id) || [])[0]?.target || null;
429
+ }
430
+ }
431
+
432
+ const steps = firstStepId ? reduceChain(firstStepId, endNode.id) : [];
433
+ visitedGlobal.add(endNode.id);
434
+
435
+ // Check for unvisited / disconnected nodes
436
+ for (const node of flowNodes) {
437
+ if (!visitedGlobal.has(node.id)) {
438
+ diagnostics.push({
439
+ level: 'error',
440
+ code: 'disconnected-or-unreduced-node',
441
+ elementId: node.id,
442
+ message: `Element "${node.name || node.id}" is disconnected or outside a structured FlowTree block.`,
443
+ });
444
+ }
445
+ }
446
+
447
+ const end = createFlowTreeNode('end', {
448
+ id: endNode.id,
449
+ name: endNode.name || undefined,
450
+ config: { documentation: endNode.properties?.documentation || '' },
451
+ }, options);
452
+
453
+ return {
454
+ starter,
455
+ starterCompileMode,
456
+ steps,
457
+ end,
458
+ compatible: !diagnostics.some((item) => item.level === 'error'),
459
+ };
460
+ }
461
+
462
+ export function decompileBpmnToFlowTree(modelOrXml, engineHint = null, options = {}) {
463
+ const bpmnModel = typeof modelOrXml === 'string'
464
+ ? importBpmn(modelOrXml, engineHint, options)
465
+ : modelOrXml;
466
+ if (!bpmnModel) {
467
+ return { document: null, compatible: false, diagnostics: [{ level: 'error', code: 'empty-model', elementId: null, message: 'No BPMN model provided.' }], bpmnModel: null };
468
+ }
469
+
470
+ // L1 lossless restoration path via embedded <nova:flowTreeMeta>
471
+ const meta = extractMetaTag(bpmnModel.extensionElements);
472
+ if (meta?.document) {
473
+ const restored = normalizeFlowTreeDocument(meta.document, options);
474
+ const expectedHash = computeTopologyFingerprint(restored);
475
+ const nodeIds = new Set((bpmnModel.nodes || []).map((item) => item.id));
476
+ const starterPresent = nodeIds.has(restored.starter.id);
477
+ const endPresent = nodeIds.has(restored.end.id);
478
+ if ((!meta.topologyHash || meta.topologyHash === expectedHash) && starterPresent && endPresent) {
479
+ syncNamesFromModel(restored, bpmnModel);
480
+ return {
481
+ document: restored,
482
+ compatible: true,
483
+ restorationLevel: 'L1-lossless',
484
+ diagnostics: [],
485
+ bpmnModel,
486
+ };
487
+ }
488
+ }
489
+
490
+ // L2 general SP-Graph structural decompilation
491
+ const diagnostics = [];
492
+ const reduced = reduceScopeToSteps(bpmnModel, bpmnModel.id, options, diagnostics);
493
+ if (!reduced.compatible || !reduced.starter || !reduced.end) {
494
+ return {
495
+ document: null,
496
+ compatible: false,
497
+ restorationLevel: 'incompatible',
498
+ diagnostics,
499
+ bpmnModel,
500
+ };
501
+ }
502
+
503
+ const document = normalizeFlowTreeDocument({
504
+ id: bpmnModel.id,
505
+ name: bpmnModel.name,
506
+ engine: bpmnModel.engine || engineHint || 'flowable',
507
+ description: bpmnModel.properties?.documentation || '',
508
+ starter: reduced.starter,
509
+ steps: reduced.steps,
510
+ end: reduced.end,
511
+ settings: {
512
+ direction: bpmnModel.settings?.direction === 'horizontal' ? 'horizontal' : 'vertical',
513
+ starterCompileMode: reduced.starterCompileMode || 'startAndUserTask',
514
+ },
515
+ }, options);
516
+
517
+ return {
518
+ document,
519
+ compatible: true,
520
+ restorationLevel: 'L2-reduced',
521
+ diagnostics,
522
+ bpmnModel,
523
+ };
524
+ }
@@ -0,0 +1,135 @@
1
+ function escapeJuelString(value = '') {
2
+ return String(value).replaceAll('\\', '\\\\').replaceAll("'", "\\'");
3
+ }
4
+
5
+ function isNumericLiteral(value, fieldType) {
6
+ if (fieldType === 'number') return value !== '' && Number.isFinite(Number(value));
7
+ return /^-?\d+(?:\.\d+)?$/.test(String(value ?? '').trim());
8
+ }
9
+
10
+ function formatJuelLiteral(value, fieldType) {
11
+ const raw = String(value ?? '').trim();
12
+ if (fieldType === 'boolean' || raw === 'true' || raw === 'false') return raw === 'true' ? 'true' : 'false';
13
+ if (isNumericLiteral(raw, fieldType)) return String(Number(raw));
14
+ return `'${escapeJuelString(raw)}'`;
15
+ }
16
+
17
+ function splitListValues(value) {
18
+ if (Array.isArray(value)) return value.map((item) => String(item).trim()).filter(Boolean);
19
+ return String(value ?? '')
20
+ .split(/[,,\n]/)
21
+ .map((item) => item.trim())
22
+ .filter(Boolean);
23
+ }
24
+
25
+ function sanitizeFieldIdentifier(field = '') {
26
+ return String(field || '').trim();
27
+ }
28
+
29
+ export function compileConditionRule(rule, options = {}) {
30
+ if (!rule) return '';
31
+ if (typeof options.ruleCompiler === 'function') {
32
+ const custom = options.ruleCompiler(rule, options);
33
+ if (typeof custom === 'string') return custom;
34
+ }
35
+ const field = sanitizeFieldIdentifier(rule.field);
36
+ if (!field) return '';
37
+ const op = rule.operator || 'eq';
38
+ const fieldType = rule.fieldType || 'string';
39
+
40
+ if (op === 'isEmpty') return `(${field} == null || ${field} == '')`;
41
+ if (op === 'isNotEmpty') return `(${field} != null && ${field} != '')`;
42
+
43
+ if (op === 'between') {
44
+ const min = String(rule.value ?? '').trim();
45
+ const max = String(rule.valueMax ?? '').trim();
46
+ const parts = [];
47
+ if (min !== '') parts.push(`${field} >= ${formatJuelLiteral(min, fieldType)}`);
48
+ if (max !== '') parts.push(`${field} <= ${formatJuelLiteral(max, fieldType)}`);
49
+ return parts.length ? `(${parts.join(' && ')})` : '';
50
+ }
51
+
52
+ if (op === 'in' || op === 'notIn') {
53
+ const values = splitListValues(rule.value);
54
+ if (!values.length) return '';
55
+ const clauses = values.map((item) => `${field} == ${formatJuelLiteral(item, fieldType)}`);
56
+ const expr = clauses.length === 1 ? clauses[0] : `(${clauses.join(' || ')})`;
57
+ return op === 'notIn' ? `!(${expr})` : expr;
58
+ }
59
+
60
+ if (op === 'belongsToDept') {
61
+ const values = splitListValues(rule.value);
62
+ if (!values.length) return '';
63
+ const encoded = escapeJuelString(values.join(','));
64
+ return `nova.belongsToDept(${field}, '${encoded}')`;
65
+ }
66
+
67
+ if (op === 'hasRole') {
68
+ const values = splitListValues(rule.value);
69
+ if (!values.length) return '';
70
+ const encoded = escapeJuelString(values.join(','));
71
+ return `nova.hasRole(${field}, '${encoded}')`;
72
+ }
73
+
74
+ const rawValue = String(rule.value ?? '').trim();
75
+ if (rawValue === '') return '';
76
+ const literal = formatJuelLiteral(rawValue, fieldType);
77
+
78
+ if (op === 'eq') return `${field} == ${literal}`;
79
+ if (op === 'neq') return `${field} != ${literal}`;
80
+ if (op === 'gt') return `${field} > ${literal}`;
81
+ if (op === 'gte') return `${field} >= ${literal}`;
82
+ if (op === 'lt') return `${field} < ${literal}`;
83
+ if (op === 'lte') return `${field} <= ${literal}`;
84
+ if (op === 'contains') return `(${field} != null && ${field}.contains(${literal}))`;
85
+ if (op === 'notContains') return `(${field} == null || !${field}.contains(${literal}))`;
86
+ return `${field} == ${literal}`;
87
+ }
88
+
89
+ export function compileConditionGroups(conditionGroups = [], options = {}) {
90
+ if (typeof options.expressionCompiler === 'function') {
91
+ const custom = options.expressionCompiler(conditionGroups, options);
92
+ if (typeof custom === 'string') return custom;
93
+ }
94
+ const groupExprs = [];
95
+ for (const group of conditionGroups || []) {
96
+ const joiner = group?.logic === 'OR' ? ' || ' : ' && ';
97
+ const ruleExprs = (group?.rules || [])
98
+ .map((rule) => compileConditionRule(rule, options))
99
+ .filter(Boolean);
100
+ if (!ruleExprs.length) continue;
101
+ groupExprs.push(ruleExprs.length === 1 ? ruleExprs[0] : `(${ruleExprs.join(joiner)})`);
102
+ }
103
+ if (!groupExprs.length) return '';
104
+ const body = groupExprs.length === 1 ? groupExprs[0] : groupExprs.join(' || ');
105
+ return `\${${body}}`;
106
+ }
107
+
108
+ export function compileBranchCondition(branch, options = {}) {
109
+ if (!branch || branch.isDefault) return '';
110
+ const config = branch.config || {};
111
+ if (config.mode === 'expression') {
112
+ const raw = String(config.expression || '').trim();
113
+ if (!raw) return '';
114
+ return raw.startsWith('${') && raw.endsWith('}') ? raw : `\${${raw}}`;
115
+ }
116
+ return compileConditionGroups(config.conditionGroups || [], options);
117
+ }
118
+
119
+ export function compileDelayToTimer(config = {}) {
120
+ const delayType = config.delayType || 'duration';
121
+ if (delayType === 'fixedDate') {
122
+ return { timerType: 'date', timerValue: String(config.fixedDate || '').trim() };
123
+ }
124
+ if (delayType === 'cron') {
125
+ return { timerType: 'cycle', timerValue: String(config.cronExpression || '').trim() };
126
+ }
127
+ const amount = Math.max(1, Number(config.duration) || 1);
128
+ const unit = config.unit || 'hour';
129
+ const timerValue = unit === 'minute'
130
+ ? `PT${amount}M`
131
+ : unit === 'day'
132
+ ? `P${amount}D`
133
+ : `PT${amount}H`;
134
+ return { timerType: 'duration', timerValue };
135
+ }