@bpmnkit/core 0.2.0 → 0.4.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 (42) hide show
  1. package/dist/bpmn/bpmn-builder.d.ts +71 -0
  2. package/dist/bpmn/bpmn-builder.js +240 -106
  3. package/dist/bpmn/bpmn-serializer.js +70 -0
  4. package/dist/bpmn/builder-coverage.d.ts +59 -0
  5. package/dist/bpmn/builder-coverage.js +62 -0
  6. package/dist/bpmn/compact.d.ts +6 -0
  7. package/dist/bpmn/compact.js +37 -2
  8. package/dist/bpmn/diagram-diff.d.ts +71 -0
  9. package/dist/bpmn/diagram-diff.js +124 -0
  10. package/dist/bpmn/element-catalog.d.ts +31 -0
  11. package/dist/bpmn/element-catalog.js +50 -0
  12. package/dist/bpmn/element-shape.d.ts +49 -0
  13. package/dist/bpmn/element-shape.js +182 -0
  14. package/dist/bpmn/lint.d.ts +97 -0
  15. package/dist/bpmn/lint.js +135 -0
  16. package/dist/bpmn/preserving-writer.d.ts +64 -0
  17. package/dist/bpmn/preserving-writer.js +70 -0
  18. package/dist/bpmn/stable-ids.d.ts +30 -0
  19. package/dist/bpmn/stable-ids.js +134 -0
  20. package/dist/dmn/dmn-serializer.js +7 -2
  21. package/dist/dmn/preserving-writer.d.ts +31 -0
  22. package/dist/dmn/preserving-writer.js +36 -0
  23. package/dist/form/preserving-writer.d.ts +47 -0
  24. package/dist/form/preserving-writer.js +50 -0
  25. package/dist/index.d.ts +15 -1
  26. package/dist/index.js +9 -1
  27. package/dist/json/index.d.ts +5 -0
  28. package/dist/json/index.js +3 -0
  29. package/dist/json/json-patch.d.ts +65 -0
  30. package/dist/json/json-patch.js +416 -0
  31. package/dist/json/json-spans.d.ts +48 -0
  32. package/dist/json/json-spans.js +153 -0
  33. package/dist/layout/types.js +4 -0
  34. package/dist/xml/index.d.ts +5 -1
  35. package/dist/xml/index.js +2 -0
  36. package/dist/xml/xml-parser.d.ts +39 -0
  37. package/dist/xml/xml-parser.js +43 -2
  38. package/dist/xml/xml-patch.d.ts +109 -0
  39. package/dist/xml/xml-patch.js +459 -0
  40. package/dist/xml/xml-spans.d.ts +45 -0
  41. package/dist/xml/xml-spans.js +74 -0
  42. package/package.json +2 -1
@@ -1,16 +1,42 @@
1
1
  import { generateId } from "../types/id-generator.js";
2
2
  import { applyAutoLayout } from "./auto-layout.js";
3
+ import { createFlowElement } from "./element-shape.js";
3
4
  import { restConnectorRetries, restConnectorTaskType, restConnectorToIoMappingInputs, restConnectorToTaskHeaders, } from "./rest-connector.js";
5
+ import { assignStableFlowIds, rootDefinitionId } from "./stable-ids.js";
4
6
  import { ensureZeebeExtension, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
5
7
  // Keep in sync with packages/core/package.json version
6
8
  const EXPORTER_VERSION = "0.0.23";
7
9
  // ---------------------------------------------------------------------------
8
10
  // Internal helpers
9
11
  // ---------------------------------------------------------------------------
12
+ /**
13
+ * Decides whether an explicit root declaration can be recorded.
14
+ *
15
+ * Returns false when the identical declaration is already there, so declaring
16
+ * twice is harmless. Throws when it contradicts one the document already
17
+ * carries: events resolve these by name, so the ones built before this call
18
+ * hold the *other* id, and keeping two definitions of one message is how a
19
+ * `messageRef` ends up naming the wrong one.
20
+ */
21
+ function canDeclareRoot(kind, label, id, existing, all) {
22
+ if (existing !== undefined) {
23
+ if (existing.id === id)
24
+ return false;
25
+ throw new Error(`${kind} "${label}" is already declared as "${existing.id}". Declare it before the events that use it, or name that id instead.`);
26
+ }
27
+ if (all.some((definition) => definition.id === id)) {
28
+ throw new Error(`Duplicate ${kind} id "${id}".`);
29
+ }
30
+ return true;
31
+ }
10
32
  function resolveMessage(messageName, rootMessages) {
11
33
  let existing = rootMessages.find((m) => m.name === messageName);
12
34
  if (!existing) {
13
- existing = { id: generateId("Message"), name: messageName, unknownAttributes: {} };
35
+ existing = {
36
+ id: rootDefinitionId("Message", messageName, rootMessages),
37
+ name: messageName,
38
+ unknownAttributes: {},
39
+ };
14
40
  rootMessages.push(existing);
15
41
  }
16
42
  return existing.id;
@@ -37,7 +63,11 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
37
63
  if (codeOrRef !== undefined && rootErrors) {
38
64
  let existing = rootErrors.find((e) => e.errorCode === codeOrRef || e.name === codeOrRef);
39
65
  if (!existing) {
40
- existing = { id: generateId("Error"), name: codeOrRef, errorCode: codeOrRef };
66
+ existing = {
67
+ id: rootDefinitionId("Error", codeOrRef, rootErrors),
68
+ name: codeOrRef,
69
+ errorCode: codeOrRef,
70
+ };
41
71
  rootErrors.push(existing);
42
72
  }
43
73
  errorRef = existing.id;
@@ -58,7 +88,10 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
58
88
  if (rootSignals) {
59
89
  let existing = rootSignals.find((s) => s.name === opts.signalName);
60
90
  if (!existing) {
61
- existing = { id: generateId("Signal"), name: opts.signalName };
91
+ existing = {
92
+ id: rootDefinitionId("Signal", opts.signalName, rootSignals),
93
+ name: opts.signalName,
94
+ };
62
95
  rootSignals.push(existing);
63
96
  }
64
97
  signalRef = existing.id;
@@ -71,7 +104,7 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
71
104
  let existing = rootEscalations.find((e) => e.escalationCode === opts.escalationCode);
72
105
  if (!existing) {
73
106
  existing = {
74
- id: generateId("Escalation"),
107
+ id: rootDefinitionId("Escalation", opts.escalationCode, rootEscalations),
75
108
  name: opts.escalationCode,
76
109
  escalationCode: opts.escalationCode,
77
110
  };
@@ -86,89 +119,15 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
86
119
  }
87
120
  return defs;
88
121
  }
122
+ /**
123
+ * Build an empty flow element.
124
+ *
125
+ * Delegates to `createFlowElement`, which holds the exhaustive type → shape
126
+ * switch; this wrapper exists so the builder's many call sites keep their
127
+ * shorter local name.
128
+ */
89
129
  function makeFlowElement(id, type, options) {
90
- const base = {
91
- id,
92
- name: options?.name,
93
- incoming: [],
94
- outgoing: [],
95
- documentation: options?.documentation,
96
- extensionElements: options?.extensionElements ?? [],
97
- unknownAttributes: {},
98
- };
99
- switch (type) {
100
- case "startEvent":
101
- case "endEvent":
102
- case "intermediateThrowEvent":
103
- case "intermediateCatchEvent":
104
- return { ...base, type, eventDefinitions: [] };
105
- case "boundaryEvent":
106
- return {
107
- ...base,
108
- type: "boundaryEvent",
109
- attachedToRef: "",
110
- eventDefinitions: [],
111
- };
112
- case "task":
113
- case "serviceTask":
114
- case "scriptTask":
115
- case "userTask":
116
- case "sendTask":
117
- case "receiveTask":
118
- case "businessRuleTask":
119
- case "manualTask":
120
- case "callActivity":
121
- return { ...base, type };
122
- case "exclusiveGateway":
123
- case "inclusiveGateway":
124
- case "complexGateway":
125
- return { ...base, type };
126
- case "parallelGateway":
127
- case "eventBasedGateway":
128
- return { ...base, type };
129
- case "subProcess":
130
- return {
131
- ...base,
132
- type: "subProcess",
133
- flowElements: [],
134
- sequenceFlows: [],
135
- textAnnotations: [],
136
- associations: [],
137
- groups: [],
138
- };
139
- case "adHocSubProcess":
140
- return {
141
- ...base,
142
- type: "adHocSubProcess",
143
- flowElements: [],
144
- sequenceFlows: [],
145
- textAnnotations: [],
146
- associations: [],
147
- groups: [],
148
- };
149
- case "eventSubProcess":
150
- return {
151
- ...base,
152
- type: "eventSubProcess",
153
- flowElements: [],
154
- sequenceFlows: [],
155
- textAnnotations: [],
156
- associations: [],
157
- groups: [],
158
- };
159
- case "transaction":
160
- return {
161
- ...base,
162
- type: "transaction",
163
- flowElements: [],
164
- sequenceFlows: [],
165
- textAnnotations: [],
166
- associations: [],
167
- groups: [],
168
- };
169
- default:
170
- return { ...base, type };
171
- }
130
+ return createFlowElement(id, type, options);
172
131
  }
173
132
  function buildMultiInstance(options) {
174
133
  const extChildren = [];
@@ -449,6 +408,14 @@ function makeInclusiveGatewayEl(id, options) {
449
408
  }
450
409
  return el;
451
410
  }
411
+ function makeComplexGatewayEl(id, options) {
412
+ const el = makeFlowElement(id, "complexGateway", options);
413
+ if (options?.defaultFlow && el.type === "complexGateway") {
414
+ ;
415
+ el.default = options.defaultFlow;
416
+ }
417
+ return el;
418
+ }
452
419
  /**
453
420
  * `subProcess`/`eventSubProcess`/`adHocSubProcess` all take a required content
454
421
  * callback as their 2nd argument and an optional options object as their 3rd.
@@ -474,6 +441,32 @@ function resolveSubProcessArgs(content, options) {
474
441
  }
475
442
  throw new TypeError("subProcess() requires a content callback function");
476
443
  }
444
+ /**
445
+ * Build a transaction element from a content callback.
446
+ *
447
+ * A transaction is a sub-process with atomic semantics: the same container
448
+ * shape and the same content builder, under a distinct element name so a cancel
449
+ * boundary event has a scope to attach to. Shared by all three flow builders —
450
+ * unlike `subProcess`, whose cursor handling differs per class, nothing here
451
+ * varies between them.
452
+ */
453
+ function makeTransactionEl(id, content, options, rootMessages) {
454
+ const resolved = resolveSubProcessArgs(content, options);
455
+ const sub = new SubProcessContentBuilder(rootMessages);
456
+ resolved.content(sub);
457
+ finalizeScope(sub._elements, sub._flows);
458
+ const element = makeFlowElement(id, "transaction", resolved.options);
459
+ if (element.type === "transaction") {
460
+ element.flowElements = sub._elements;
461
+ element.sequenceFlows = sub._flows;
462
+ element.textAnnotations = sub._textAnnotations;
463
+ element.associations = sub._associations;
464
+ if (resolved.options?.multiInstance) {
465
+ element.loopCharacteristics = buildMultiInstance(resolved.options.multiInstance);
466
+ }
467
+ }
468
+ return element;
469
+ }
477
470
  // ---------------------------------------------------------------------------
478
471
  // Shared graph helpers — used by ProcessBuilder and SubProcessContentBuilder
479
472
  // ---------------------------------------------------------------------------
@@ -550,6 +543,17 @@ function insertJoinGateways(elements, flows) {
550
543
  }
551
544
  }
552
545
  }
546
+ /**
547
+ * Settles a finished scope: infer the joins its branches imply, name its
548
+ * sequence flows after what they connect, then rebuild the `incoming`/
549
+ * `outgoing` lists the ids feed. Order matters — a flow's endpoints are not
550
+ * final until join inference has run, and its id is not final until this pass.
551
+ */
552
+ function finalizeScope(elements, flows) {
553
+ insertJoinGateways(elements, flows);
554
+ assignStableFlowIds(elements, flows);
555
+ recomputeIncomingOutgoing(elements, flows);
556
+ }
553
557
  function traceBackToSplit(nodeId, splitGateways, flows) {
554
558
  const visited = new Set();
555
559
  let current = nodeId;
@@ -751,6 +755,13 @@ export class BranchBuilder {
751
755
  callActivity(id, options) {
752
756
  return this.addElement(makeCallActivityEl(id, options));
753
757
  }
758
+ /** Add a manual task — work performed outside the engine, with no job worker. */
759
+ manualTask(id, options) {
760
+ const el = makeFlowElement(id, "manualTask", options);
761
+ if (options?.isForCompensation)
762
+ el.isForCompensation = true;
763
+ return this.addElement(el);
764
+ }
754
765
  /** Add an abstract task with no Zeebe extensions. */
755
766
  task(id, options) {
756
767
  const el = makeFlowElement(id, "task", options);
@@ -805,6 +816,10 @@ export class BranchBuilder {
805
816
  this.currentGatewayId = id;
806
817
  return this.addElement(makeFlowElement(id, "eventBasedGateway", options));
807
818
  }
819
+ complexGateway(id, options) {
820
+ this.currentGatewayId = id;
821
+ return this.addElement(makeComplexGatewayEl(id, options));
822
+ }
808
823
  /**
809
824
  * Add a boundary event attached to an existing activity in this branch.
810
825
  *
@@ -869,8 +884,7 @@ export class BranchBuilder {
869
884
  const resolved = resolveSubProcessArgs(content, options);
870
885
  const sub = new SubProcessContentBuilder(this.rootMessages);
871
886
  resolved.content(sub);
872
- insertJoinGateways(sub._elements, sub._flows);
873
- recomputeIncomingOutgoing(sub._elements, sub._flows);
887
+ finalizeScope(sub._elements, sub._flows);
874
888
  const element = makeFlowElement(id, "subProcess", resolved.options);
875
889
  if (element.type === "subProcess") {
876
890
  element.flowElements = sub._elements;
@@ -883,13 +897,16 @@ export class BranchBuilder {
883
897
  }
884
898
  return this.addElement(element);
885
899
  }
900
+ /** Add a transaction sub-process (mirrors `ProcessBuilder.transaction`). */
901
+ transaction(id, content, options) {
902
+ return this.addElement(makeTransactionEl(id, content, options, this.rootMessages));
903
+ }
886
904
  /** Add an ad-hoc sub-process (mirrors `ProcessBuilder.adHocSubProcess`). */
887
905
  adHocSubProcess(id, content, options) {
888
906
  const resolved = resolveSubProcessArgs(content, options);
889
907
  const sub = new SubProcessContentBuilder(this.rootMessages);
890
908
  resolved.content(sub);
891
- insertJoinGateways(sub._elements, sub._flows);
892
- recomputeIncomingOutgoing(sub._elements, sub._flows);
909
+ finalizeScope(sub._elements, sub._flows);
893
910
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
894
911
  const element = makeFlowElement(id, "adHocSubProcess", {
895
912
  name: resolved.options?.name,
@@ -904,8 +921,7 @@ export class BranchBuilder {
904
921
  const resolved = resolveSubProcessArgs(content, options);
905
922
  const sub = new SubProcessContentBuilder(this.rootMessages);
906
923
  resolved.content(sub);
907
- insertJoinGateways(sub._elements, sub._flows);
908
- recomputeIncomingOutgoing(sub._elements, sub._flows);
924
+ finalizeScope(sub._elements, sub._flows);
909
925
  const element = makeFlowElement(id, "subProcess", resolved.options);
910
926
  if (element.type === "subProcess") {
911
927
  element.triggeredByEvent = true;
@@ -1102,6 +1118,13 @@ export class SubProcessContentBuilder {
1102
1118
  el.messageRef = resolveMessage(options.messageName, this.rootMessages);
1103
1119
  return this.addElement(el);
1104
1120
  }
1121
+ /** Add a manual task — work performed outside the engine, with no job worker. */
1122
+ manualTask(id, options) {
1123
+ const el = makeFlowElement(id, "manualTask", options);
1124
+ if (options?.isForCompensation)
1125
+ el.isForCompensation = true;
1126
+ return this.addElement(el);
1127
+ }
1105
1128
  /** Add an abstract task with no Zeebe extensions. */
1106
1129
  task(id, options) {
1107
1130
  const el = makeFlowElement(id, "task", options);
@@ -1126,6 +1149,10 @@ export class SubProcessContentBuilder {
1126
1149
  this.currentGatewayId = id;
1127
1150
  return this.addElement(makeFlowElement(id, "eventBasedGateway", options));
1128
1151
  }
1152
+ complexGateway(id, options) {
1153
+ this.currentGatewayId = id;
1154
+ return this.addElement(makeComplexGatewayEl(id, options));
1155
+ }
1129
1156
  // ---- Annotations ----
1130
1157
  /** Attach a text annotation to the element at the current cursor position. */
1131
1158
  textAnnotation(text) {
@@ -1273,8 +1300,7 @@ export class SubProcessContentBuilder {
1273
1300
  const resolved = resolveSubProcessArgs(content, options);
1274
1301
  const sub = new SubProcessContentBuilder(this.rootMessages);
1275
1302
  resolved.content(sub);
1276
- insertJoinGateways(sub._elements, sub._flows);
1277
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1303
+ finalizeScope(sub._elements, sub._flows);
1278
1304
  const element = makeFlowElement(id, "subProcess", resolved.options);
1279
1305
  if (element.type === "subProcess") {
1280
1306
  element.flowElements = sub._elements;
@@ -1287,13 +1313,16 @@ export class SubProcessContentBuilder {
1287
1313
  }
1288
1314
  return this.addElement(element);
1289
1315
  }
1316
+ /** Add a transaction sub-process nested inside this sub-process's content. */
1317
+ transaction(id, content, options) {
1318
+ return this.addElement(makeTransactionEl(id, content, options, this.rootMessages));
1319
+ }
1290
1320
  /** Add an ad-hoc sub-process nested inside this sub-process's content. */
1291
1321
  adHocSubProcess(id, content, options) {
1292
1322
  const resolved = resolveSubProcessArgs(content, options);
1293
1323
  const sub = new SubProcessContentBuilder(this.rootMessages);
1294
1324
  resolved.content(sub);
1295
- insertJoinGateways(sub._elements, sub._flows);
1296
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1325
+ finalizeScope(sub._elements, sub._flows);
1297
1326
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1298
1327
  const element = makeFlowElement(id, "adHocSubProcess", {
1299
1328
  name: resolved.options?.name,
@@ -1308,8 +1337,7 @@ export class SubProcessContentBuilder {
1308
1337
  const resolved = resolveSubProcessArgs(content, options);
1309
1338
  const sub = new SubProcessContentBuilder(this.rootMessages);
1310
1339
  resolved.content(sub);
1311
- insertJoinGateways(sub._elements, sub._flows);
1312
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1340
+ finalizeScope(sub._elements, sub._flows);
1313
1341
  const element = makeFlowElement(id, "subProcess", resolved.options);
1314
1342
  if (element.type === "subProcess") {
1315
1343
  element.triggeredByEvent = true;
@@ -1523,6 +1551,80 @@ export class ProcessBuilder {
1523
1551
  this._versionTag = tag;
1524
1552
  return this;
1525
1553
  }
1554
+ // ---- Root definitions ----
1555
+ /**
1556
+ * Declares the root `bpmn:message` for a message name, with the id you choose.
1557
+ *
1558
+ * Events name messages by name — `{ messageName: "Order Received" }` — and the
1559
+ * builder declares one on first use, deriving its id from that name. Call this
1560
+ * first when the id itself matters, typically because something outside this
1561
+ * process already refers to it.
1562
+ *
1563
+ * @param id - The message's element id, used verbatim.
1564
+ * @throws If a message with this name is already declared under another id,
1565
+ * which the events built before this call already point at.
1566
+ * @example
1567
+ * ```typescript
1568
+ * Bpmn.createProcess("orders")
1569
+ * .message("Msg_OrderReceived", { name: "Order Received" })
1570
+ * .startEvent("start", { messageName: "Order Received" })
1571
+ * ```
1572
+ */
1573
+ message(id, options) {
1574
+ const existing = this.rootMessages.find((message) => message.name === options.name);
1575
+ if (canDeclareRoot("Message", options.name, id, existing, this.rootMessages)) {
1576
+ this.rootMessages.push({ id, name: options.name, unknownAttributes: {} });
1577
+ }
1578
+ return this;
1579
+ }
1580
+ /**
1581
+ * Declares the root `bpmn:error` for an error code, with the id you choose.
1582
+ *
1583
+ * @param id - The error's element id, used verbatim.
1584
+ * @param options - The `code` events match on, and the display `name`, which
1585
+ * defaults to the code.
1586
+ * @throws If this code is already declared under another id.
1587
+ */
1588
+ error(id, options) {
1589
+ const existing = this.rootErrors.find((error) => error.errorCode === options.code || error.name === options.code);
1590
+ if (canDeclareRoot("Error", options.code, id, existing, this.rootErrors)) {
1591
+ this.rootErrors.push({ id, name: options.name ?? options.code, errorCode: options.code });
1592
+ }
1593
+ return this;
1594
+ }
1595
+ /**
1596
+ * Declares the root `bpmn:signal` for a signal name, with the id you choose.
1597
+ *
1598
+ * @param id - The signal's element id, used verbatim.
1599
+ * @throws If this name is already declared under another id.
1600
+ */
1601
+ signal(id, options) {
1602
+ const existing = this.rootSignals.find((signal) => signal.name === options.name);
1603
+ if (canDeclareRoot("Signal", options.name, id, existing, this.rootSignals)) {
1604
+ this.rootSignals.push({ id, name: options.name });
1605
+ }
1606
+ return this;
1607
+ }
1608
+ /**
1609
+ * Declares the root `bpmn:escalation` for an escalation code, with the id you
1610
+ * choose.
1611
+ *
1612
+ * @param id - The escalation's element id, used verbatim.
1613
+ * @param options - The `code` events match on, and the display `name`, which
1614
+ * defaults to the code.
1615
+ * @throws If this code is already declared under another id.
1616
+ */
1617
+ escalation(id, options) {
1618
+ const existing = this.rootEscalations.find((escalation) => escalation.escalationCode === options.code);
1619
+ if (canDeclareRoot("Escalation", options.code, id, existing, this.rootEscalations)) {
1620
+ this.rootEscalations.push({
1621
+ id,
1622
+ name: options.name ?? options.code,
1623
+ escalationCode: options.code,
1624
+ });
1625
+ }
1626
+ return this;
1627
+ }
1526
1628
  // ---- Events ----
1527
1629
  /** Add a start event. Start events never auto-connect from the previous element. */
1528
1630
  startEvent(id, options) {
@@ -1740,6 +1842,14 @@ export class ProcessBuilder {
1740
1842
  this.addFlowElement(makeCallActivityEl(id, options));
1741
1843
  return this;
1742
1844
  }
1845
+ /** Add a manual task — work performed outside the engine, with no job worker. */
1846
+ manualTask(id, options) {
1847
+ const el = makeFlowElement(id, "manualTask", options);
1848
+ if (options?.isForCompensation)
1849
+ el.isForCompensation = true;
1850
+ this.addFlowElement(el);
1851
+ return this;
1852
+ }
1743
1853
  /** Add an abstract task with no Zeebe extensions. */
1744
1854
  task(id, options) {
1745
1855
  const el = makeFlowElement(id, "task", options);
@@ -1773,6 +1883,12 @@ export class ProcessBuilder {
1773
1883
  this.currentGatewayId = id;
1774
1884
  return this;
1775
1885
  }
1886
+ /** Add a complex gateway. Aspirational — Zeebe does not execute these. */
1887
+ complexGateway(id, options) {
1888
+ this.addFlowElement(makeComplexGatewayEl(id, options));
1889
+ this.currentGatewayId = id;
1890
+ return this;
1891
+ }
1776
1892
  // ---- Branching & flow control ----
1777
1893
  /**
1778
1894
  * Create a named branch from the current gateway.
@@ -1871,8 +1987,7 @@ export class ProcessBuilder {
1871
1987
  const resolved = resolveSubProcessArgs(content, options);
1872
1988
  const sub = new SubProcessContentBuilder(this.rootMessages);
1873
1989
  resolved.content(sub);
1874
- insertJoinGateways(sub._elements, sub._flows);
1875
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1990
+ finalizeScope(sub._elements, sub._flows);
1876
1991
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1877
1992
  const element = makeFlowElement(id, "adHocSubProcess", {
1878
1993
  name: resolved.options?.name,
@@ -1888,8 +2003,7 @@ export class ProcessBuilder {
1888
2003
  const resolved = resolveSubProcessArgs(content, options);
1889
2004
  const sub = new SubProcessContentBuilder(this.rootMessages);
1890
2005
  resolved.content(sub);
1891
- insertJoinGateways(sub._elements, sub._flows);
1892
- recomputeIncomingOutgoing(sub._elements, sub._flows);
2006
+ finalizeScope(sub._elements, sub._flows);
1893
2007
  const element = makeFlowElement(id, "subProcess", resolved.options);
1894
2008
  if (element.type === "subProcess") {
1895
2009
  element.flowElements = sub._elements;
@@ -1903,13 +2017,17 @@ export class ProcessBuilder {
1903
2017
  this.addFlowElement(element);
1904
2018
  return this;
1905
2019
  }
2020
+ /** Add a transaction sub-process — a sub-process with atomic semantics. */
2021
+ transaction(id, content, options) {
2022
+ this.addFlowElement(makeTransactionEl(id, content, options, this.rootMessages));
2023
+ return this;
2024
+ }
1906
2025
  /** Add an event sub-process. Triggered by its start event — no incoming or outgoing sequence flows. */
1907
2026
  eventSubProcess(id, content, options) {
1908
2027
  const resolved = resolveSubProcessArgs(content, options);
1909
2028
  const sub = new SubProcessContentBuilder(this.rootMessages);
1910
2029
  resolved.content(sub);
1911
- insertJoinGateways(sub._elements, sub._flows);
1912
- recomputeIncomingOutgoing(sub._elements, sub._flows);
2030
+ finalizeScope(sub._elements, sub._flows);
1913
2031
  const element = makeFlowElement(id, "subProcess", resolved.options);
1914
2032
  if (element.type === "subProcess") {
1915
2033
  element.triggeredByEvent = true;
@@ -2000,6 +2118,9 @@ export class ProcessBuilder {
2000
2118
  }
2001
2119
  this.validate();
2002
2120
  this.assertSourceTopologyIntact();
2121
+ // Flows the document already had keep their ids: continuing a model must
2122
+ // not renumber the part the caller did not touch.
2123
+ assignStableFlowIds(this.flowElements, this.sequenceFlows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
2003
2124
  recomputeIncomingOutgoing(this.flowElements, this.sequenceFlows);
2004
2125
  if (this._source !== undefined)
2005
2126
  return this.buildOntoSource(this._source);
@@ -2204,6 +2325,16 @@ export class ProcessBuilder {
2204
2325
  // ---------------------------------------------------------------------------
2205
2326
  // Diagram builder — multi-process support
2206
2327
  // ---------------------------------------------------------------------------
2328
+ /** Appends the root definitions the document does not already declare, matched by id. */
2329
+ function mergeRootDefinitions(into, incoming) {
2330
+ const present = new Set(into.map((definition) => definition.id));
2331
+ for (const definition of incoming) {
2332
+ if (present.has(definition.id))
2333
+ continue;
2334
+ present.add(definition.id);
2335
+ into.push(definition);
2336
+ }
2337
+ }
2207
2338
  /**
2208
2339
  * Builder for a complete BPMN definitions document containing one or more processes.
2209
2340
  * Use `Bpmn.createDiagram(id?)` to obtain an instance.
@@ -2230,8 +2361,11 @@ export class DiagramBuilder {
2230
2361
  callback(builder);
2231
2362
  const defs = builder.build();
2232
2363
  this._processes.push(...defs.processes);
2233
- this._errors.push(...defs.errors);
2234
- this._messages.push(...defs.messages);
2364
+ // Root definitions are named after the message or error code they carry, so
2365
+ // two pools declaring the same one produce the same definition twice. The
2366
+ // document needs it once.
2367
+ mergeRootDefinitions(this._errors, defs.errors);
2368
+ mergeRootDefinitions(this._messages, defs.messages);
2235
2369
  return this;
2236
2370
  }
2237
2371
  /** Renames the collaboration element. Defaults to `"Collaboration_1"`. */
@@ -647,6 +647,76 @@ export function serializeBpmn(definitions) {
647
647
  children.push(serializeDiagram(d, ns));
648
648
  }
649
649
  const root = el(`${bp}:definitions`, attrs, children);
650
+ declareUsedNamespaces(root, attrs);
650
651
  return serializeXml(root);
651
652
  }
653
+ /**
654
+ * URIs for the extension prefixes a document can acquire after it was parsed.
655
+ *
656
+ * Scoped deliberately to extension namespaces — the ones that arrive on content
657
+ * the serializer keeps verbatim, where nothing else is in a position to declare
658
+ * them. A caller adds a `zeebe:taskDefinition` to an element and has no handle
659
+ * on the definitions to declare `zeebe` with.
660
+ *
661
+ * The structural prefixes (`bpmn`, `bpmndi`, `dc`, `di`) are deliberately
662
+ * absent. The serializer emits those itself, so a model carrying a diagram it
663
+ * never declared namespaces for is a different gap with a different owner —
664
+ * and repairing it here would change the model a round trip produces, which
665
+ * `semanticHash` and the `writeBpmn` boundary both hold constant on purpose.
666
+ * Recorded in doc/roadmap.md rather than fixed in passing.
667
+ */
668
+ const KNOWN_NAMESPACE_URIS = {
669
+ zeebe: "http://camunda.org/schema/zeebe/1.0",
670
+ camunda: "http://camunda.org/schema/1.0/bpmn",
671
+ modeler: "http://camunda.org/schema/modeler/1.0",
672
+ bioc: "http://bpmn.io/schema/bpmn/biocolor/1.0",
673
+ color: "http://www.omg.org/spec/BPMN/non-normative/color/1.0",
674
+ };
675
+ /** Prefixes an element tree uses, and prefixes it declares — at any depth. */
676
+ function collectPrefixes(node, used, declared) {
677
+ const nameParts = node.name.split(":");
678
+ if (nameParts.length > 1 && nameParts[0] !== undefined)
679
+ used.add(nameParts[0]);
680
+ for (const key of Object.keys(node.attributes)) {
681
+ if (key.startsWith("xmlns:")) {
682
+ declared.add(key.slice("xmlns:".length));
683
+ continue;
684
+ }
685
+ if (key === "xmlns")
686
+ continue;
687
+ const parts = key.split(":");
688
+ if (parts.length > 1 && parts[0] !== undefined)
689
+ used.add(parts[0]);
690
+ }
691
+ for (const child of node.children)
692
+ collectPrefixes(child, used, declared);
693
+ }
694
+ /**
695
+ * Declares any namespace the document uses but does not announce.
696
+ *
697
+ * A model parsed from a vendor-neutral file has no `zeebe` declaration; give
698
+ * one of its tasks a `zeebe:taskDefinition` — which is what applying a
699
+ * connector template does — and the export would otherwise carry a prefix
700
+ * bound to nothing. That is not merely untidy: the document is no longer
701
+ * namespace-well-formed, and a conforming reader is entitled to reject it.
702
+ *
703
+ * Only prefixes with a known URI are repaired, and only when the model has not
704
+ * already bound them; a document that declares its own mapping keeps it.
705
+ */
706
+ function declareUsedNamespaces(root, attrs) {
707
+ const used = new Set();
708
+ const declared = new Set();
709
+ collectPrefixes(root, used, declared);
710
+ for (const prefix of used) {
711
+ // Declared anywhere counts. A model can bind a prefix on a nested element
712
+ // — `xsi` on an `extensionElements` child is common — and the parser keeps
713
+ // only root-level bindings in `namespaces`, so looking at the root alone
714
+ // would hoist a duplicate declaration and change a document that was fine.
715
+ if (declared.has(prefix))
716
+ continue;
717
+ const uri = KNOWN_NAMESPACE_URIS[prefix];
718
+ if (uri !== undefined)
719
+ attrs[`xmlns:${prefix}`] = uri;
720
+ }
721
+ }
652
722
  //# sourceMappingURL=bpmn-serializer.js.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Which fluent-builder method covers each BPMN element type.
3
+ *
4
+ * The fluent builder is hand-written, one method per element type, while
5
+ * `BpmnElementType` grows whenever the model learns a new construct. Nothing
6
+ * connected the two, so types reached the parser, the serialiser, the layout
7
+ * and the compact/JSON path while the builder — the surface most callers and
8
+ * every code-generating agent actually use — silently lacked a method. An agent
9
+ * that cannot say `.manualTask()` edits the XML by hand instead.
10
+ *
11
+ * This table closes that loop. It is a `Record` keyed by `BpmnElementType`, so
12
+ * **adding a member to that union fails `tsc` here until the new type is either
13
+ * given a builder method or exempted with a reason**. The check is compile-time
14
+ * and total; it cannot be forgotten, and it cannot pass by accident.
15
+ *
16
+ * `tests/builder-coverage.test.ts` carries the runtime half: every `method`
17
+ * named here must exist on all three flow builders, and every `exempt` entry
18
+ * must still have no method of that name — so an exemption someone outgrows
19
+ * fails rather than lingers.
20
+ *
21
+ * Run `pnpm --filter @bpmnkit/core check:builder` to print the table.
22
+ */
23
+ import type { BpmnElementType } from "./bpmn-model.js";
24
+ /** An element type the fluent builder exposes a method for. */
25
+ export interface BuilderMethodEntry {
26
+ /** Method name, present on every flow builder. */
27
+ readonly method: string;
28
+ /**
29
+ * The `type` the method stamps, when it differs from the key.
30
+ *
31
+ * Only `eventSubProcess` needs this: BPMN 2.0 has no `bpmn:eventSubProcess`
32
+ * element, so the builder emits the spec form — `subProcess` with
33
+ * `triggeredByEvent="true"`. The key exists because the parser accepts the
34
+ * non-standard element and round-trips it.
35
+ */
36
+ readonly emits?: BpmnElementType;
37
+ }
38
+ /** An element type the fluent builder deliberately has no method for. */
39
+ export interface BuilderExemptEntry {
40
+ /** Why a method would be wrong — not merely why one is missing. */
41
+ readonly exempt: string;
42
+ }
43
+ export type BuilderSupport = BuilderMethodEntry | BuilderExemptEntry;
44
+ /** Narrows a {@link BuilderSupport} to the entries that name a method. */
45
+ export declare function hasBuilderMethod(support: BuilderSupport): support is BuilderMethodEntry;
46
+ /**
47
+ * Every `BpmnElementType`, mapped to the builder method that creates it.
48
+ *
49
+ * Adding a type to the union without adding it here is a compile error.
50
+ */
51
+ export declare const BUILDER_COVERAGE: Record<BpmnElementType, BuilderSupport>;
52
+ /**
53
+ * The builders the table applies to — every class that builds a flow chain.
54
+ *
55
+ * `DiagramBuilder` is excluded on purpose: it assembles collaborations,
56
+ * participants and message flows, and never adds flow elements itself.
57
+ */
58
+ export declare const FLOW_BUILDER_NAMES: readonly ["ProcessBuilder", "BranchBuilder", "SubProcessContentBuilder"];
59
+ //# sourceMappingURL=builder-coverage.d.ts.map