@bpmn-nova/studio 0.4.0 → 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 (32) hide show
  1. package/README.md +1 -1
  2. package/dist/flow-tree.d.ts +4 -0
  3. package/dist/flow-tree.js +14 -0
  4. package/dist/modules/flow-tree/controller.js +364 -0
  5. package/dist/modules/flow-tree/index.d.ts +248 -0
  6. package/dist/modules/flow-tree/index.js +5 -0
  7. package/dist/modules/flow-tree/operations.js +484 -0
  8. package/dist/modules/flow-tree/sample.js +445 -0
  9. package/dist/modules/flow-tree/schema.js +588 -0
  10. package/dist/modules/flow-tree/validate.js +125 -0
  11. package/dist/modules/flow-tree-bpmn/compiler.js +547 -0
  12. package/dist/modules/flow-tree-bpmn/decompiler.js +524 -0
  13. package/dist/modules/flow-tree-bpmn/expression.js +135 -0
  14. package/dist/modules/flow-tree-bpmn/index.d.ts +53 -0
  15. package/dist/modules/flow-tree-bpmn/index.js +14 -0
  16. package/dist/modules/flow-tree-renderer/canvas.js +1003 -0
  17. package/dist/modules/flow-tree-renderer/export-svg.js +325 -0
  18. package/dist/modules/flow-tree-renderer/index.d.ts +143 -0
  19. package/dist/modules/flow-tree-renderer/index.js +3 -0
  20. package/dist/modules/flow-tree-renderer/shell.js +970 -0
  21. package/dist/modules/i18n/locales/en-US.js +399 -0
  22. package/dist/modules/i18n/locales/zh-CN.js +399 -0
  23. package/dist/modules/icons/index.js +23 -0
  24. package/dist/modules/properties-flow-tree/index.d.ts +56 -0
  25. package/dist/modules/properties-flow-tree/index.js +2 -0
  26. package/dist/modules/properties-flow-tree/panel.js +1136 -0
  27. package/dist/modules/properties-flow-tree/widgets.js +625 -0
  28. package/dist/modules/viewer/index.js +10 -2
  29. package/dist/styles.css +2368 -0
  30. package/llms-full.txt +353 -9
  31. package/llms.txt +3 -2
  32. package/package.json +6 -1
@@ -0,0 +1,125 @@
1
+ import { resolveI18n } from '../i18n/index.js';
2
+ import { FLOW_TREE_NODE_DEFINITIONS, isRouteNode } from './schema.js';
3
+ import { walkFlowTree } from './operations.js';
4
+
5
+ function hasAssigneeTargets(config) {
6
+ const type = config?.assigneeType || 'users';
7
+ if (type === 'users') return Boolean(config?.targets?.users?.length);
8
+ if (type === 'roles') return Boolean(config?.targets?.roles?.length);
9
+ if (type === 'departments') return Boolean(config?.targets?.departments?.length);
10
+ if (type === 'supervisor' || type === 'multiLevelSupervisor' || type === 'selfSelect' || type === 'initiatorSelf') return true;
11
+ if (type === 'formUser') return Boolean(String(config?.formUserField || '').trim());
12
+ if (type === 'expression') return Boolean(String(config?.expression || '').trim());
13
+ return false;
14
+ }
15
+
16
+ function hasValidCondition(branch) {
17
+ if (branch.isDefault) return true;
18
+ const config = branch.config || {};
19
+ if (config.mode === 'expression') return Boolean(String(config.expression || '').trim());
20
+ const groups = Array.isArray(config.conditionGroups) ? config.conditionGroups : [];
21
+ return groups.some((group) => (group.rules || []).some((rule) => {
22
+ if (!String(rule.field || '').trim()) return false;
23
+ if (rule.operator === 'isEmpty' || rule.operator === 'isNotEmpty') return true;
24
+ if (rule.operator === 'between') return String(rule.value ?? '').trim() !== '' || String(rule.valueMax ?? '').trim() !== '';
25
+ return String(rule.value ?? '').trim() !== '';
26
+ }));
27
+ }
28
+
29
+ export function validateFlowTree(doc, options = null) {
30
+ const i18n = resolveI18n(options);
31
+ const t = (key, params) => i18n.t(key, params);
32
+ const registry = options?.nodeRegistry || null;
33
+ const issues = [];
34
+ if (!doc) return issues;
35
+
36
+ const seenIds = new Set();
37
+ const push = (level, code, nodeId, message) => {
38
+ issues.push({
39
+ id: `${code}:${nodeId || 'process'}:${issues.length + 1}`,
40
+ level,
41
+ code,
42
+ nodeId: nodeId || null,
43
+ message,
44
+ });
45
+ };
46
+
47
+ walkFlowTree(doc, (node) => {
48
+ if (seenIds.has(node.id)) {
49
+ push('error', 'duplicate-node-id', node.id, t('flowTree.validation.duplicateNodeId', { id: node.id }));
50
+ }
51
+ seenIds.add(node.id);
52
+
53
+ const config = node.config || {};
54
+
55
+ if (node.type === 'approver') {
56
+ if (config.assigneeType === 'expression' && !String(config.expression || '').trim()) {
57
+ push('error', 'approver-missing-expression', node.id, t('flowTree.validation.approverMissingExpression', { name: node.name }));
58
+ } else if (config.assigneeType === 'formUser' && !String(config.formUserField || '').trim()) {
59
+ push('error', 'approver-missing-form-field', node.id, t('flowTree.validation.approverMissingFormField', { name: node.name }));
60
+ } else if (!hasAssigneeTargets(config)) {
61
+ push('error', 'approver-missing-target', node.id, t('flowTree.validation.approverMissingTarget', { name: node.name }));
62
+ }
63
+ if (config.emptyStrategy === 'toSpecified' && !(config.fallbackUsers?.length)) {
64
+ push('warning', 'approver-missing-fallback', node.id, t('flowTree.validation.approverMissingFallback', { name: node.name }));
65
+ }
66
+ } else if (node.type === 'cc') {
67
+ if (!hasAssigneeTargets(config) && !config.allowStarterSelfSelect) {
68
+ push('warning', 'cc-missing-target', node.id, t('flowTree.validation.ccMissingTarget', { name: node.name }));
69
+ }
70
+ } else if (node.type === 'handler') {
71
+ if (!hasAssigneeTargets(config)) {
72
+ push('error', 'handler-missing-target', node.id, t('flowTree.validation.handlerMissingTarget', { name: node.name }));
73
+ }
74
+ } else if (isRouteNode(node)) {
75
+ const def = FLOW_TREE_NODE_DEFINITIONS[node.type];
76
+ if ((node.branches || []).length < 2) {
77
+ push('error', 'route-min-branches', node.id, t('flowTree.validation.routeMinBranches', { name: node.name }));
78
+ }
79
+ if (def?.hasDefaultBranch && !(node.branches || []).some((branch) => branch.isDefault)) {
80
+ push('error', 'condition-missing-default', node.id, t('flowTree.validation.conditionMissingDefault', { name: node.name }));
81
+ }
82
+ if (node.type === 'inclusiveRoute' && doc.engine === 'activiti') {
83
+ push('warning', 'activiti-inclusive-advisory', node.id, t('flowTree.validation.activitiInclusiveAdvisory', { name: node.name }));
84
+ }
85
+ } else if (node.type === 'conditionBranch' || node.type === 'inclusiveBranch') {
86
+ if (!node.isDefault && !hasValidCondition(node)) {
87
+ push('error', 'condition-branch-empty', node.id, t('flowTree.validation.conditionBranchEmpty', { name: node.name }));
88
+ }
89
+ } else if (node.type === 'delay') {
90
+ const valid = config.delayType === 'fixedDate'
91
+ ? Boolean(String(config.fixedDate || '').trim())
92
+ : config.delayType === 'cron'
93
+ ? Boolean(String(config.cronExpression || '').trim())
94
+ : Number(config.duration) > 0;
95
+ if (!valid) {
96
+ push('error', 'delay-missing-value', node.id, t('flowTree.validation.delayMissingValue', { name: node.name }));
97
+ }
98
+ } else if (node.type === 'trigger') {
99
+ const valid = config.triggerType === 'webhook'
100
+ ? Boolean(String(config.url || '').trim())
101
+ : Boolean(String(config.implementation || '').trim());
102
+ if (!valid) {
103
+ push('error', 'trigger-missing-target', node.id, t('flowTree.validation.triggerMissingTarget', { name: node.name }));
104
+ }
105
+ } else if (node.type === 'subFlow') {
106
+ if (config.subFlowMode === 'embedded') {
107
+ if (!(config.steps?.length)) {
108
+ push('warning', 'subflow-empty-embedded', node.id, t('flowTree.validation.subFlowEmptyEmbedded', { name: node.name }));
109
+ }
110
+ } else if (!String(config.calledElement || '').trim()) {
111
+ push('error', 'subflow-missing-called-element', node.id, t('flowTree.validation.subFlowMissingCalledElement', { name: node.name }));
112
+ }
113
+ } else if (registry) {
114
+ const customDef = registry.resolve(node.type);
115
+ if (typeof customDef?.validate === 'function') {
116
+ const customIssues = customDef.validate(node, { document: doc, i18n }) || [];
117
+ for (const item of customIssues) {
118
+ push(item.level || 'warning', item.code || `custom-${node.type}`, node.id, item.message || String(item));
119
+ }
120
+ }
121
+ }
122
+ });
123
+
124
+ return issues;
125
+ }
@@ -0,0 +1,547 @@
1
+ import {
2
+ autoLayout,
3
+ createEdge,
4
+ createEmptyProcess,
5
+ createNode,
6
+ getScopeGraph,
7
+ } from '../core/index.js';
8
+ import { exportBpmn } from '../bpmn-model/index.js';
9
+ import {
10
+ cloneFlowTree,
11
+ isRouteNode,
12
+ normalizeFlowTreeDocument,
13
+ } from '../flow-tree/index.js';
14
+ import { compileBranchCondition, compileDelayToTimer } from './expression.js';
15
+
16
+ export const NOVA_APPROVAL_PREFIX = 'nova';
17
+ export const NOVA_APPROVAL_NS = 'urn:bpmn-nova:approval';
18
+
19
+ function safeCdataJson(value) {
20
+ return JSON.stringify(value).replaceAll(']]>', ']]]]><![CDATA[>');
21
+ }
22
+
23
+ export function encodeNovaNodeConfig(payload) {
24
+ return `<${NOVA_APPROVAL_PREFIX}:nodeConfig><![CDATA[${safeCdataJson(payload)}]]></${NOVA_APPROVAL_PREFIX}:nodeConfig>`;
25
+ }
26
+
27
+ export function encodeNovaBranchConfig(payload) {
28
+ return `<${NOVA_APPROVAL_PREFIX}:branchConfig><![CDATA[${safeCdataJson(payload)}]]></${NOVA_APPROVAL_PREFIX}:branchConfig>`;
29
+ }
30
+
31
+ export function computeTopologyFingerprint(doc) {
32
+ const tokens = [];
33
+ const walk = (steps) => {
34
+ for (const step of steps || []) {
35
+ if (isRouteNode(step)) {
36
+ tokens.push(`R:${step.type}:${step.id}[`);
37
+ for (const branch of step.branches || []) {
38
+ tokens.push(`B:${branch.id}:${branch.isDefault ? 'D' : branch.priority}(`);
39
+ walk(branch.steps);
40
+ tokens.push(')');
41
+ }
42
+ tokens.push(']');
43
+ } else {
44
+ tokens.push(`N:${step.type}:${step.id}`);
45
+ if (step.type === 'subFlow' && step.config?.subFlowMode === 'embedded') {
46
+ tokens.push('{');
47
+ walk(step.config.steps);
48
+ tokens.push('}');
49
+ }
50
+ }
51
+ }
52
+ };
53
+ tokens.push(`P:${doc.id}:S:${doc.starter?.id || ''}:${doc.settings?.starterCompileMode || 'startAndUserTask'}`);
54
+ walk(doc.steps);
55
+ tokens.push(`E:${doc.end?.id || ''}`);
56
+ const str = tokens.join('|');
57
+ let hash = 2166136261;
58
+ for (let i = 0; i < str.length; i += 1) {
59
+ hash ^= str.charCodeAt(i);
60
+ hash = Math.imul(hash, 16777619);
61
+ }
62
+ return `ft1_${(hash >>> 0).toString(16)}`;
63
+ }
64
+
65
+ export function encodeNovaFlowTreeMeta(doc) {
66
+ const topologyHash = computeTopologyFingerprint(doc);
67
+ return `<${NOVA_APPROVAL_PREFIX}:flowTreeMeta schemaVersion="${doc.schemaVersion || 1}" topologyHash="${topologyHash}"><![CDATA[${safeCdataJson(doc)}]]></${NOVA_APPROVAL_PREFIX}:flowTreeMeta>`;
68
+ }
69
+
70
+ function applyAssigneeAndMultiInstance(bpmnProps, node, modeField) {
71
+ const config = node.config || {};
72
+ const assigneeType = config.assigneeType || 'users';
73
+ const mode = config[modeField] || 'or';
74
+ const users = (config.targets?.users || []).map((item) => item.id).filter(Boolean);
75
+ const roles = (config.targets?.roles || []).map((item) => item.id).filter(Boolean);
76
+ const departments = (config.targets?.departments || []).map((item) => item.id).filter(Boolean);
77
+
78
+ let needsMultiInstance = mode === 'and' || mode === 'sequential' || mode === 'percentage';
79
+ const dynamicCollectionVar = `nova_assignees_${node.id}`;
80
+
81
+ if (assigneeType === 'users') {
82
+ if (users.length === 1 && mode === 'or') {
83
+ bpmnProps.assignee = users[0];
84
+ } else if (users.length > 1 && mode === 'or') {
85
+ bpmnProps.candidateUsers = users.join(',');
86
+ } else if (users.length >= 1) {
87
+ needsMultiInstance = true;
88
+ bpmnProps.candidateUsers = users.join(',');
89
+ bpmnProps.assignee = '${assignee}';
90
+ bpmnProps.collection = `\${${dynamicCollectionVar}}`;
91
+ bpmnProps.elementVariable = 'assignee';
92
+ }
93
+ } else if (assigneeType === 'roles') {
94
+ if (roles.length) bpmnProps.candidateGroups = roles.join(',');
95
+ if (needsMultiInstance) {
96
+ bpmnProps.assignee = '${assignee}';
97
+ bpmnProps.collection = `\${${dynamicCollectionVar}}`;
98
+ bpmnProps.elementVariable = 'assignee';
99
+ }
100
+ } else if (assigneeType === 'departments') {
101
+ if (departments.length) bpmnProps.candidateGroups = departments.map((id) => `dept:${id}`).join(',');
102
+ if (needsMultiInstance) {
103
+ bpmnProps.assignee = '${assignee}';
104
+ bpmnProps.collection = `\${${dynamicCollectionVar}}`;
105
+ bpmnProps.elementVariable = 'assignee';
106
+ }
107
+ } else if (assigneeType === 'initiatorSelf') {
108
+ bpmnProps.assignee = '${initiator}';
109
+ needsMultiInstance = false;
110
+ } else if (assigneeType === 'expression') {
111
+ bpmnProps.assignee = String(config.expression || '').trim();
112
+ if (needsMultiInstance) {
113
+ bpmnProps.collection = bpmnProps.assignee || `\${${dynamicCollectionVar}}`;
114
+ bpmnProps.elementVariable = 'assignee';
115
+ bpmnProps.assignee = '${assignee}';
116
+ }
117
+ } else {
118
+ // supervisor, multiLevelSupervisor, selfSelect, formUser -> resolved dynamically at runtime via backend TaskListener
119
+ bpmnProps.assignee = needsMultiInstance ? '${assignee}' : `\${nova_assignee_${node.id}}`;
120
+ if (needsMultiInstance || assigneeType === 'multiLevelSupervisor' || (assigneeType === 'selfSelect' && config.selfSelectMultiple)) {
121
+ needsMultiInstance = true;
122
+ bpmnProps.assignee = '${assignee}';
123
+ bpmnProps.collection = `\${${dynamicCollectionVar}}`;
124
+ bpmnProps.elementVariable = 'assignee';
125
+ }
126
+ }
127
+
128
+ if (needsMultiInstance) {
129
+ bpmnProps.loopType = mode === 'sequential' ? 'sequential' : 'parallel';
130
+ if (mode === 'and' || mode === 'sequential') {
131
+ bpmnProps.completionCondition = '${nrOfCompletedInstances == nrOfInstances}';
132
+ } else if (mode === 'percentage') {
133
+ const percent = Math.max(1, Math.min(100, Number(config.passPercentage) || 60));
134
+ bpmnProps.completionCondition = `\${(nrOfCompletedInstances * 100 / nrOfInstances) >= ${percent}}`;
135
+ } else {
136
+ bpmnProps.completionCondition = '${nrOfCompletedInstances >= 1}';
137
+ }
138
+ }
139
+ }
140
+
141
+ export function compileFlowTreeToBpmn(inputDoc, options = {}) {
142
+ const doc = normalizeFlowTreeDocument(inputDoc, options);
143
+ const engine = options.engine || doc.engine || 'flowable';
144
+ const enginePrefix = engine === 'activiti' ? 'activiti' : 'flowable';
145
+ const registry = options.nodeRegistry || null;
146
+ const model = createEmptyProcess(engine, options);
147
+
148
+ model.id = doc.id;
149
+ model.name = doc.name;
150
+ model.properties.documentation = doc.description || doc.properties?.documentation || '';
151
+ model.properties.extensionAttributes = {
152
+ ...(doc.properties?.extensionAttributes || {}),
153
+ };
154
+ model.namespaceDeclarations = {
155
+ ...model.namespaceDeclarations,
156
+ [`xmlns:${NOVA_APPROVAL_PREFIX}`]: NOVA_APPROVAL_NS,
157
+ };
158
+ model.settings = {
159
+ ...model.settings,
160
+ direction: doc.settings?.direction === 'horizontal' ? 'horizontal' : 'vertical',
161
+ layoutDensity: 'balanced',
162
+ };
163
+
164
+ if (options.includeFlowTreeMeta !== false) {
165
+ model.extensionElements.push(encodeNovaFlowTreeMeta(doc));
166
+ }
167
+
168
+ let flowSeed = 0;
169
+ const nextFlowId = (prefix = 'Flow') => {
170
+ flowSeed += 1;
171
+ return `${prefix}_${flowSeed}`;
172
+ };
173
+
174
+ const addEdge = (sourceId, targetId, scopeId, overrides = {}) => {
175
+ const edge = createEdge(sourceId, targetId, {
176
+ id: overrides.id || nextFlowId('Flow'),
177
+ scopeId,
178
+ ...overrides,
179
+ });
180
+ model.edges.push(edge);
181
+ return edge;
182
+ };
183
+
184
+ const compileStep = (step, scopeId) => {
185
+ if (isRouteNode(step)) {
186
+ const gatewayType = step.type === 'parallelRoute'
187
+ ? 'parallelGateway'
188
+ : step.type === 'inclusiveRoute'
189
+ ? 'inclusiveGateway'
190
+ : 'exclusiveGateway';
191
+ const splitId = `${step.id}__split`;
192
+ const joinId = `${step.id}__join`;
193
+
194
+ const splitNode = createNode(gatewayType, 0, 0, {
195
+ id: splitId,
196
+ name: step.name || '',
197
+ scopeId,
198
+ properties: {
199
+ gatewayDirection: 'Diverging',
200
+ extensionAttributes: {
201
+ [`${NOVA_APPROVAL_PREFIX}:routeId`]: step.id,
202
+ [`${NOVA_APPROVAL_PREFIX}:routeKind`]: step.type,
203
+ [`${NOVA_APPROVAL_PREFIX}:gatewayRole`]: 'split',
204
+ },
205
+ },
206
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, name: step.name })],
207
+ }, options);
208
+
209
+ const joinNode = createNode(gatewayType, 0, 0, {
210
+ id: joinId,
211
+ name: '',
212
+ scopeId,
213
+ properties: {
214
+ gatewayDirection: 'Converging',
215
+ extensionAttributes: {
216
+ [`${NOVA_APPROVAL_PREFIX}:routeId`]: step.id,
217
+ [`${NOVA_APPROVAL_PREFIX}:routeKind`]: step.type,
218
+ [`${NOVA_APPROVAL_PREFIX}:gatewayRole`]: 'join',
219
+ },
220
+ },
221
+ }, options);
222
+
223
+ model.nodes.push(splitNode);
224
+
225
+ const orderedBranches = [...(step.branches || [])].sort((a, b) => (a.priority || 0) - (b.priority || 0));
226
+ for (const branch of orderedBranches) {
227
+ const isConditionAware = step.type === 'conditionRoute' || step.type === 'inclusiveRoute';
228
+ const isDefault = isConditionAware && Boolean(branch.isDefault);
229
+ const condition = isConditionAware && !isDefault ? compileBranchCondition(branch, options) : '';
230
+ const branchFlowId = `Flow_${branch.id}`;
231
+ if (isDefault) splitNode.defaultFlowId = branchFlowId;
232
+
233
+ const branchEdgeOverrides = {
234
+ id: branchFlowId,
235
+ name: branch.name || '',
236
+ condition,
237
+ isDefault,
238
+ properties: {
239
+ extensionAttributes: {
240
+ [`${NOVA_APPROVAL_PREFIX}:branchId`]: branch.id,
241
+ [`${NOVA_APPROVAL_PREFIX}:branchPriority`]: String(branch.priority || 1),
242
+ },
243
+ },
244
+ extensionElements: [encodeNovaBranchConfig({
245
+ id: branch.id,
246
+ type: branch.type,
247
+ name: branch.name,
248
+ priority: branch.priority,
249
+ isDefault,
250
+ config: branch.config || {},
251
+ })],
252
+ };
253
+
254
+ if (!branch.steps?.length) {
255
+ addEdge(splitId, joinId, scopeId, branchEdgeOverrides);
256
+ } else {
257
+ const chain = compileSequence(branch.steps, scopeId);
258
+ addEdge(splitId, chain.entryId, scopeId, branchEdgeOverrides);
259
+ addEdge(chain.exitId, joinId, scopeId);
260
+ }
261
+ }
262
+
263
+ model.nodes.push(joinNode);
264
+ return { entryId: splitId, exitId: joinId };
265
+ }
266
+
267
+ if (step.type === 'approver') {
268
+ const props = {
269
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'approver' },
270
+ };
271
+ applyAssigneeAndMultiInstance(props, step, 'approvalMode');
272
+ const node = createNode('userTask', 0, 0, {
273
+ id: step.id,
274
+ name: step.name,
275
+ scopeId,
276
+ properties: props,
277
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config: step.config })],
278
+ }, options);
279
+ model.nodes.push(node);
280
+ return { entryId: node.id, exitId: node.id };
281
+ }
282
+
283
+ if (step.type === 'handler') {
284
+ const props = {
285
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'handler' },
286
+ };
287
+ applyAssigneeAndMultiInstance(props, step, 'completionMode');
288
+ const node = createNode('userTask', 0, 0, {
289
+ id: step.id,
290
+ name: step.name,
291
+ scopeId,
292
+ properties: props,
293
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config: step.config })],
294
+ }, options);
295
+ model.nodes.push(node);
296
+ return { entryId: node.id, exitId: node.id };
297
+ }
298
+
299
+ if (step.type === 'cc') {
300
+ const config = step.config || {};
301
+ const node = createNode('serviceTask', 0, 0, {
302
+ id: step.id,
303
+ name: step.name,
304
+ scopeId,
305
+ properties: {
306
+ implementationType: 'delegateExpression',
307
+ implementation: config.delegateExpression || '${novaCcDelegate}',
308
+ extensionAttributes: {
309
+ [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'cc',
310
+ ...(doc.settings?.ccCompileMode === 'executionListener'
311
+ ? { [`${NOVA_APPROVAL_PREFIX}:ccCompileMode`]: 'executionListener' }
312
+ : {}),
313
+ },
314
+ },
315
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config })],
316
+ }, options);
317
+ model.nodes.push(node);
318
+ return { entryId: node.id, exitId: node.id };
319
+ }
320
+
321
+ if (step.type === 'delay') {
322
+ const timer = compileDelayToTimer(step.config || {});
323
+ const node = createNode('timerIntermediateCatchEvent', 0, 0, {
324
+ id: step.id,
325
+ name: step.name,
326
+ scopeId,
327
+ properties: {
328
+ timerType: timer.timerType,
329
+ timerValue: timer.timerValue,
330
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'delay' },
331
+ },
332
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config: step.config })],
333
+ }, options);
334
+ model.nodes.push(node);
335
+ return { entryId: node.id, exitId: node.id };
336
+ }
337
+
338
+ if (step.type === 'trigger') {
339
+ const config = step.config || {};
340
+ const isWebhook = (config.triggerType || 'webhook') === 'webhook';
341
+ const implementationType = isWebhook
342
+ ? 'delegateExpression'
343
+ : config.triggerType === 'serviceClass'
344
+ ? 'class'
345
+ : config.triggerType === 'expression'
346
+ ? 'expression'
347
+ : 'delegateExpression';
348
+ const implementation = isWebhook
349
+ ? '${novaWebhookDelegate}'
350
+ : String(config.implementation || '').trim();
351
+ const fields = isWebhook
352
+ ? [
353
+ { name: 'method', type: 'string', value: config.method || 'POST' },
354
+ { name: 'url', type: 'string', value: config.url || '' },
355
+ ...(config.bodyTemplate ? [{ name: 'body', type: 'string', value: config.bodyTemplate }] : []),
356
+ ]
357
+ : (config.fields || []).filter((item) => item?.name);
358
+
359
+ const node = createNode('serviceTask', 0, 0, {
360
+ id: step.id,
361
+ name: step.name,
362
+ scopeId,
363
+ properties: {
364
+ implementationType,
365
+ implementation,
366
+ resultVariable: config.resultVariable || '',
367
+ async: Boolean(config.async),
368
+ failedJobRetryTimeCycle: config.async ? (config.retryCycle || '') : '',
369
+ fields,
370
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'trigger' },
371
+ },
372
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config })],
373
+ }, options);
374
+ model.nodes.push(node);
375
+ return { entryId: node.id, exitId: node.id };
376
+ }
377
+
378
+ if (step.type === 'subFlow') {
379
+ const config = step.config || {};
380
+ if (config.subFlowMode === 'embedded') {
381
+ const subNode = createNode('subProcess', 0, 0, {
382
+ id: step.id,
383
+ name: step.name,
384
+ scopeId,
385
+ properties: {
386
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'subFlow' },
387
+ },
388
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config })],
389
+ }, options);
390
+ model.nodes.push(subNode);
391
+
392
+ const subStart = createNode('startEvent', 0, 0, {
393
+ id: `${step.id}__start`,
394
+ name: '',
395
+ scopeId: subNode.id,
396
+ }, options);
397
+ const subEnd = createNode('endEvent', 0, 0, {
398
+ id: `${step.id}__end`,
399
+ name: '',
400
+ scopeId: subNode.id,
401
+ }, options);
402
+ model.nodes.push(subStart);
403
+ if (config.steps?.length) {
404
+ const inner = compileSequence(config.steps, subNode.id);
405
+ addEdge(subStart.id, inner.entryId, subNode.id);
406
+ addEdge(inner.exitId, subEnd.id, subNode.id);
407
+ } else {
408
+ addEdge(subStart.id, subEnd.id, subNode.id);
409
+ }
410
+ model.nodes.push(subEnd);
411
+ return { entryId: subNode.id, exitId: subNode.id };
412
+ }
413
+
414
+ const callNode = createNode('callActivity', 0, 0, {
415
+ id: step.id,
416
+ name: step.name,
417
+ scopeId,
418
+ properties: {
419
+ calledElement: config.calledElement || '',
420
+ inheritBusinessKey: config.inheritBusinessKey !== false,
421
+ inheritVariables: config.inheritVariables !== false,
422
+ inParameters: cloneFlowTree(config.inParameters || []),
423
+ outParameters: cloneFlowTree(config.outParameters || []),
424
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'subFlow' },
425
+ },
426
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config })],
427
+ }, options);
428
+ model.nodes.push(callNode);
429
+ return { entryId: callNode.id, exitId: callNode.id };
430
+ }
431
+
432
+ // Custom node registered by host
433
+ const customDef = registry?.resolve?.(step.type);
434
+ if (typeof customDef?.compileToBpmn === 'function') {
435
+ const customResult = customDef.compileToBpmn(step, { model, scopeId, createNode, createEdge, addEdge, engine });
436
+ if (customResult?.entryId && customResult?.exitId) return customResult;
437
+ }
438
+
439
+ const fallback = createNode('serviceTask', 0, 0, {
440
+ id: step.id,
441
+ name: step.name,
442
+ scopeId,
443
+ properties: {
444
+ implementationType: 'delegateExpression',
445
+ implementation: `\${novaCustom_${step.type}Delegate}`,
446
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: `custom:${step.type}` },
447
+ },
448
+ extensionElements: [encodeNovaNodeConfig({ id: step.id, type: step.type, config: step.config || {} })],
449
+ }, options);
450
+ model.nodes.push(fallback);
451
+ return { entryId: fallback.id, exitId: fallback.id };
452
+ };
453
+
454
+ const compileSequence = (steps, scopeId) => {
455
+ let entryId = null;
456
+ let prevExitId = null;
457
+ for (const step of steps || []) {
458
+ const compiled = compileStep(step, scopeId);
459
+ if (!entryId) entryId = compiled.entryId;
460
+ if (prevExitId) addEdge(prevExitId, compiled.entryId, scopeId);
461
+ prevExitId = compiled.exitId;
462
+ }
463
+ return { entryId, exitId: prevExitId };
464
+ };
465
+
466
+ // Starter compilation (startAndUserTask vs startEvent)
467
+ const starterMode = doc.settings?.starterCompileMode || 'startAndUserTask';
468
+ let cursorId = null;
469
+ if (starterMode === 'startAndUserTask') {
470
+ const startEvent = createNode('startEvent', 0, 0, {
471
+ id: `StartEvent_${doc.starter.id}`,
472
+ name: '',
473
+ scopeId: model.id,
474
+ properties: {
475
+ extensionAttributes: {
476
+ [`${enginePrefix}:initiator`]: 'initiator',
477
+ [`${NOVA_APPROVAL_PREFIX}:starterEventFor`]: doc.starter.id,
478
+ },
479
+ },
480
+ }, options);
481
+ const starterTask = createNode('userTask', 0, 0, {
482
+ id: doc.starter.id,
483
+ name: doc.starter.name,
484
+ scopeId: model.id,
485
+ properties: {
486
+ assignee: '${initiator}',
487
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'starter' },
488
+ },
489
+ extensionElements: [encodeNovaNodeConfig({ id: doc.starter.id, type: 'starter', config: doc.starter.config })],
490
+ }, options);
491
+ model.nodes.push(startEvent, starterTask);
492
+ addEdge(startEvent.id, starterTask.id, model.id);
493
+ cursorId = starterTask.id;
494
+ } else {
495
+ const startEvent = createNode('startEvent', 0, 0, {
496
+ id: doc.starter.id,
497
+ name: doc.starter.name,
498
+ scopeId: model.id,
499
+ properties: {
500
+ extensionAttributes: {
501
+ [`${enginePrefix}:initiator`]: 'initiator',
502
+ [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'starter',
503
+ },
504
+ },
505
+ extensionElements: [encodeNovaNodeConfig({ id: doc.starter.id, type: 'starter', config: doc.starter.config })],
506
+ }, options);
507
+ model.nodes.push(startEvent);
508
+ cursorId = startEvent.id;
509
+ }
510
+
511
+ // Main steps
512
+ if (doc.steps.length) {
513
+ const compiled = compileSequence(doc.steps, model.id);
514
+ if (compiled.entryId) {
515
+ addEdge(cursorId, compiled.entryId, model.id);
516
+ cursorId = compiled.exitId;
517
+ }
518
+ }
519
+
520
+ // End node
521
+ const endNode = createNode('endEvent', 0, 0, {
522
+ id: doc.end.id,
523
+ name: doc.end.name,
524
+ scopeId: model.id,
525
+ properties: {
526
+ documentation: doc.end.config?.documentation || '',
527
+ extensionAttributes: { [`${NOVA_APPROVAL_PREFIX}:nodeKind`]: 'end' },
528
+ },
529
+ }, options);
530
+ model.nodes.push(endNode);
531
+ addEdge(cursorId, endNode.id, model.id);
532
+
533
+ // Auto-layout root scope and every embedded subProcess scope for clean BPMN DI
534
+ const direction = options.direction || doc.settings?.direction || 'vertical';
535
+ autoLayout(getScopeGraph(model, model.id), { direction, density: options.density || 'balanced' });
536
+ for (const sub of model.nodes.filter((item) => item.type === 'subProcess')) {
537
+ autoLayout(getScopeGraph(model, sub.id), { direction: 'horizontal', density: 'balanced' });
538
+ }
539
+
540
+ return model;
541
+ }
542
+
543
+ export function exportFlowTreeBpmnXml(doc, engine = null, options = {}) {
544
+ const targetEngine = engine || doc?.engine || 'flowable';
545
+ const model = compileFlowTreeToBpmn(doc, { ...options, engine: targetEngine });
546
+ return exportBpmn(model, targetEngine);
547
+ }