@bpmnkit/core 1.9.0 → 1.10.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 (110) hide show
  1. package/agent-cards/bpmn.md +3 -3
  2. package/builder-reference.md +11 -9
  3. package/dist/bpmn/auto-layout.js +82 -26
  4. package/dist/bpmn/bpmn-builder.d.ts +84 -7
  5. package/dist/bpmn/bpmn-builder.js +313 -78
  6. package/dist/bpmn/bpmn-model.d.ts +2 -0
  7. package/dist/bpmn/bpmn-parser.js +68 -76
  8. package/dist/bpmn/bpmn-serializer.js +60 -19
  9. package/dist/bpmn/bpmnlint.js +4 -69
  10. package/dist/bpmn/builder-rules.d.ts +20 -0
  11. package/dist/bpmn/builder-rules.js +120 -0
  12. package/dist/bpmn/camunda-compat-data.d.ts +10 -148
  13. package/dist/bpmn/camunda-compat-data.js +16 -407
  14. package/dist/bpmn/camunda-compat-feel.d.ts +3 -0
  15. package/dist/bpmn/camunda-compat-feel.js +1 -1
  16. package/dist/bpmn/camunda-compat.js +7 -6
  17. package/dist/bpmn/camunda7/export.js +4 -1
  18. package/dist/bpmn/camunda7/juel.js +2 -1
  19. package/dist/bpmn/camunda7/migrate.d.ts +23 -0
  20. package/dist/bpmn/camunda7/migrate.js +75 -3
  21. package/dist/bpmn/compact-stream.js +2 -1
  22. package/dist/bpmn/compact.d.ts +80 -4
  23. package/dist/bpmn/compact.js +220 -38
  24. package/dist/bpmn/feel-condition.d.ts +9 -0
  25. package/dist/bpmn/feel-condition.js +19 -0
  26. package/dist/bpmn/full-operations.js +31 -4
  27. package/dist/bpmn/index.d.ts +13 -3
  28. package/dist/bpmn/index.js +16 -15
  29. package/dist/bpmn/operations.d.ts +4 -4
  30. package/dist/bpmn/operations.js +14 -2
  31. package/dist/bpmn/optimize/bpmnlint-rules.js +7 -40
  32. package/dist/bpmn/optimize/index.js +15 -1
  33. package/dist/bpmn/optimize/tasks.js +12 -3
  34. package/dist/bpmn/process-delta.d.ts +18 -0
  35. package/dist/bpmn/process-delta.js +20 -2
  36. package/dist/bpmn/process-text-writer.js +27 -1
  37. package/dist/bpmn/process-text.d.ts +9 -3
  38. package/dist/bpmn/process-text.js +122 -16
  39. package/dist/bpmn/stable-ids.d.ts +2 -0
  40. package/dist/bpmn/stable-ids.js +8 -0
  41. package/dist/bpmn/zeebe-extensions.js +2 -1
  42. package/dist/bpmn/zeebe-placement.js +6 -129
  43. package/dist/bpmn/zeebe-validate/context.d.ts +132 -0
  44. package/dist/bpmn/zeebe-validate/context.js +241 -0
  45. package/dist/bpmn/zeebe-validate/gate.d.ts +87 -0
  46. package/dist/bpmn/zeebe-validate/gate.js +492 -0
  47. package/dist/bpmn/zeebe-validate/index.d.ts +37 -0
  48. package/dist/bpmn/zeebe-validate/index.js +106 -0
  49. package/dist/bpmn/zeebe-validate/rules/events.d.ts +4 -0
  50. package/dist/bpmn/zeebe-validate/rules/events.js +580 -0
  51. package/dist/bpmn/zeebe-validate/rules/extensions.d.ts +4 -0
  52. package/dist/bpmn/zeebe-validate/rules/extensions.js +411 -0
  53. package/dist/bpmn/zeebe-validate/rules/gateways.d.ts +3 -0
  54. package/dist/bpmn/zeebe-validate/rules/gateways.js +296 -0
  55. package/dist/bpmn/zeebe-validate/rules/references.d.ts +3 -0
  56. package/dist/bpmn/zeebe-validate/rules/references.js +495 -0
  57. package/dist/bpmn/zeebe-validate/rules/structure.d.ts +3 -0
  58. package/dist/bpmn/zeebe-validate/rules/structure.js +629 -0
  59. package/dist/bpmn/zeebe-validate/rules/tasks.d.ts +4 -0
  60. package/dist/bpmn/zeebe-validate/rules/tasks.js +446 -0
  61. package/dist/bpmn/zeebe-validate/xml.d.ts +15 -0
  62. package/dist/bpmn/zeebe-validate/xml.js +1062 -0
  63. package/dist/bpmn/zeebe-validate/xsd.d.ts +19 -0
  64. package/dist/bpmn/zeebe-validate/xsd.js +350 -0
  65. package/dist/connectors/aliases.js +1 -0
  66. package/dist/connectors/apply-element.d.ts +5 -2
  67. package/dist/connectors/apply-element.js +6 -0
  68. package/dist/connectors/apply-many.d.ts +9 -2
  69. package/dist/connectors/apply-many.js +17 -2
  70. package/dist/connectors/apply.d.ts +4 -2
  71. package/dist/connectors/deployability.d.ts +27 -0
  72. package/dist/connectors/deployability.js +41 -0
  73. package/dist/connectors/index.d.ts +1 -0
  74. package/dist/connectors/lines.d.ts +10 -0
  75. package/dist/connectors/lines.js +13 -4
  76. package/dist/connectors/templates/generated.js +10101 -3188
  77. package/dist/dmn/dmn-model.d.ts +24 -4
  78. package/dist/dmn/dmn-parser.js +37 -3
  79. package/dist/dmn/dmn-serializer.js +48 -47
  80. package/dist/dmn/lint.js +4 -11
  81. package/dist/errors.d.ts +30 -1
  82. package/dist/errors.js +31 -0
  83. package/dist/form/form-model.d.ts +11 -0
  84. package/dist/form/form-parser.d.ts +1 -0
  85. package/dist/form/form-parser.js +48 -12
  86. package/dist/form/form-serializer.js +40 -17
  87. package/dist/form/lint.js +6 -40
  88. package/dist/generated/bpmn-elements.d.ts +5 -0
  89. package/dist/generated/bpmn-elements.js +151 -0
  90. package/dist/generated/camunda-compat-data.d.ts +148 -0
  91. package/dist/generated/camunda-compat-data.js +371 -0
  92. package/dist/generated/dmn-elements.d.ts +12 -0
  93. package/dist/generated/dmn-elements.js +45 -0
  94. package/dist/generated/form-elements.d.ts +5 -0
  95. package/dist/generated/form-elements.js +45 -0
  96. package/dist/generated/lint-rules.d.ts +17 -0
  97. package/dist/generated/lint-rules.js +116 -0
  98. package/dist/generated/zeebe-elements.d.ts +10 -0
  99. package/dist/generated/zeebe-elements.js +168 -0
  100. package/dist/generated/zeebe-rules.d.ts +25 -0
  101. package/dist/generated/zeebe-rules.js +202 -0
  102. package/dist/index.d.ts +10 -4
  103. package/dist/index.js +4 -1
  104. package/dist/layout/annotations.js +21 -1
  105. package/dist/layout/orthogonal.js +9 -3
  106. package/dist/plan/compile.d.ts +26 -1
  107. package/dist/plan/compile.js +48 -6
  108. package/dist/plan/merge.d.ts +2 -1
  109. package/dist/plan/merge.js +13 -5
  110. package/package.json +2 -2
@@ -1,11 +1,15 @@
1
1
  import { ValidationError } from "../errors.js";
2
2
  import { generateId } from "../types/id-generator.js";
3
3
  import { applyAutoLayout } from "./auto-layout.js";
4
- import { createFlowElement } from "./element-shape.js";
4
+ import { camunda8BuilderProblem } from "./builder-rules.js";
5
+ import { normalizeCamundaVersion } from "./camunda-compat.js";
6
+ import { createFlowElement, isLoopCapableType } from "./element-shape.js";
7
+ import { toFeelCondition } from "./feel-condition.js";
5
8
  import { REST_CONNECTOR_TEMPLATE_VERSION, restConnectorRetries, restConnectorTaskType, restConnectorToIoMappingInputs, restConnectorToTaskHeaders, } from "./rest-connector.js";
6
- import { assertExplicitFlowIdsUnique, assignEventDefinitionIds, assignStableFlowIds, markExplicitFlowId, rootDefinitionId, setFlowDiscriminatorSource, } from "./stable-ids.js";
9
+ import { assertExplicitFlowIdsUnique, assignEventDefinitionIds, assignStableFlowIds, copyFlowTags, markExplicitFlowId, rootDefinitionId, setFlowDiscriminatorSource, } from "./stable-ids.js";
7
10
  import { assertRetriesOption, assertXsdValues } from "./xsd-guards.js";
8
11
  import { assertZeebePlacement, bpmnElementName, ensureZeebeExtension, makeConditionalDefinition, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
12
+ import { assertDeployable, targetsCamunda8 } from "./zeebe-validate/gate.js";
9
13
  // Keep in sync with packages/core/package.json version
10
14
  const EXPORTER_VERSION = "0.0.23";
11
15
  /**
@@ -24,10 +28,38 @@ function makeDataElement(id, type, ref, options) {
24
28
  el.dataObjectRef = ref;
25
29
  if (el.type === "dataStoreReference")
26
30
  el.dataStoreRef = ref;
27
- if (options?.isCollection && (el.type === "dataObject" || el.type === "dataObjectReference"))
31
+ if (options?.isCollection && el.type === "dataObject")
28
32
  el.isCollection = true;
29
33
  return el;
30
34
  }
35
+ /**
36
+ * BPMN20.xsd puts `isCollection` on the data object only, so a reference asking
37
+ * for the marker sets it on the object it points at (when that object is in
38
+ * this scope) rather than on itself.
39
+ */
40
+ function addDataObjectReference(elements, ids, id, dataObjectRef, options) {
41
+ addDataElement(elements, ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
42
+ if (!options?.isCollection)
43
+ return;
44
+ const target = elements.find((e) => e.id === dataObjectRef);
45
+ if (target?.type === "dataObject")
46
+ target.isCollection = true;
47
+ }
48
+ /**
49
+ * BPMN20.xsd requires a dataInputAssociation's targetRef. Without an
50
+ * ioSpecification there is no data input to point at, so (like Camunda
51
+ * Modeler) the activity gets one `__targetRef_placeholder` property that every
52
+ * input association targets.
53
+ */
54
+ function targetRefPlaceholder(activity) {
55
+ const name = "__targetRef_placeholder";
56
+ const existing = activity.properties?.find((p) => p.name === name && p.id !== undefined);
57
+ if (existing?.id !== undefined)
58
+ return existing.id;
59
+ const id = `Property_${activity.id}`;
60
+ activity.properties = [...(activity.properties ?? []), { id, name, unknownAttributes: {} }];
61
+ return id;
62
+ }
31
63
  /**
32
64
  * Input: the data reference is the association's source. Output: it is the
33
65
  * target. Either way the activity owns the association element.
@@ -37,7 +69,11 @@ function addDataAssociation(elements, activityId, dataRefId, direction) {
37
69
  if (!activity)
38
70
  throw new Error(`dataAssociation(): no element "${activityId}" in this scope`);
39
71
  const association = direction === "input"
40
- ? { sourceRefs: [dataRefId], unknownAttributes: {} }
72
+ ? {
73
+ sourceRefs: [dataRefId],
74
+ targetRef: targetRefPlaceholder(activity),
75
+ unknownAttributes: {},
76
+ }
41
77
  : { sourceRefs: [], targetRef: dataRefId, unknownAttributes: {} };
42
78
  const key = direction === "input" ? "dataInputAssociations" : "dataOutputAssociations";
43
79
  activity[key] = [...(activity[key] ?? []), association];
@@ -131,11 +167,34 @@ function hoistMessageSubscriptions(defs) {
131
167
  }
132
168
  return defs;
133
169
  }
134
- function buildMessageSubscriptionExt(correlationKey) {
135
- if (!correlationKey)
170
+ function buildMessageSubscriptionExt(method, options) {
171
+ const correlationKey = options?.correlationKey;
172
+ if (!correlationKey) {
173
+ // Zeebe rejects a caught message without a subscription key, and there is no
174
+ // key we could infer, so refuse rather than emit a model that cannot deploy.
175
+ if (options?.messageName) {
176
+ throw new Error(missingCorrelationKey(`${method}()`, options.messageName));
177
+ }
136
178
  return [];
179
+ }
137
180
  return zeebeExtensionsToXmlElements({ subscription: { correlationKey } });
138
181
  }
182
+ function missingCorrelationKey(subject, messageName) {
183
+ return `${subject}: message "${messageName}" needs a correlationKey; Camunda 8 requires a zeebe:subscription correlationKey on a message caught outside a process start event`;
184
+ }
185
+ /** An event sub-process's message start is a catch too: Zeebe needs its correlation key. */
186
+ function assertEventSubProcessSubscriptions(elements) {
187
+ for (const el of elements) {
188
+ if (el.type !== "startEvent")
189
+ continue;
190
+ if (!el.eventDefinitions.some((d) => d.type === "message"))
191
+ continue;
192
+ if (el.extensionElements.some((x) => x.name === "zeebe:subscription"))
193
+ continue;
194
+ const ref = el.eventDefinitions.find((d) => d.type === "message")?.messageRef ?? el.id;
195
+ throw new Error(missingCorrelationKey(`eventSubProcess(): start event "${el.id}"`, ref));
196
+ }
197
+ }
139
198
  function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, rootEscalations) {
140
199
  const defs = [];
141
200
  if (opts.timerDuration || opts.timerDate || opts.timerCycle) {
@@ -230,9 +289,18 @@ function isLinkEvent(element, type) {
230
289
  * switch; this wrapper exists so the builder's many call sites keep their
231
290
  * shorter local name.
232
291
  */
292
+ /** Elements whose message Camunda 8 hands to a job worker (`taskType`). */
293
+ const MESSAGE_JOB_TYPES = new Set([
294
+ "sendTask",
295
+ "intermediateThrowEvent",
296
+ "endEvent",
297
+ ]);
233
298
  function makeFlowElement(id, type, options) {
234
299
  const el = createFlowElement(id, type, options);
235
300
  el.extensionElements = [...el.extensionElements];
301
+ if (options?.taskType !== undefined && MESSAGE_JOB_TYPES.has(type)) {
302
+ el.extensionElements.push(...zeebeExtensionsToXmlElements({ taskDefinition: { type: options.taskType } }));
303
+ }
236
304
  // Placement is checked here, so a listener on an element the schema forbids it on
237
305
  // fails at build time, not at deploy time.
238
306
  const listeners = zeebeExtensionsToXmlElements({
@@ -262,7 +330,7 @@ function buildMultiInstance(options) {
262
330
  isSequential: options.isSequential || undefined,
263
331
  completionCondition: options.completionCondition
264
332
  ? {
265
- text: options.completionCondition,
333
+ text: toFeelCondition(options.completionCondition),
266
334
  attributes: { "xsi:type": "bpmn:tFormalExpression" },
267
335
  }
268
336
  : undefined,
@@ -316,6 +384,88 @@ const GATEWAY_ELEMENT_TYPES = new Set([
316
384
  function isGatewayType(type) {
317
385
  return GATEWAY_ELEMENT_TYPES.has(type);
318
386
  }
387
+ /**
388
+ * Why `withBoundary()` may not attach to `host`, or undefined when it may.
389
+ * BPMN attaches boundary events to activities only, which are exactly the
390
+ * loop-capable types. An unknown host (a cursor that `connectTo()` moved
391
+ * outside this scope) is left alone.
392
+ */
393
+ function boundaryHostProblem(host) {
394
+ if (host === undefined || isLoopCapableType(host.type))
395
+ return undefined;
396
+ if (host.type === "boundaryEvent") {
397
+ return "withBoundary() cannot attach to a boundary event. It must follow a task or activity element.";
398
+ }
399
+ return `withBoundary() cannot attach to ${host.type} "${host.id}". It must follow a task or activity element.`;
400
+ }
401
+ /**
402
+ * Throws on an id used twice anywhere in the process. Each builder scope only
403
+ * checks its own ids, but BPMN ids are unique per document.
404
+ */
405
+ /**
406
+ * Zeebe refuses an end event with an outgoing flow, so nothing may be chained
407
+ * after one. Structural, so it holds with `validate: false` too.
408
+ */
409
+ function assertNotAfterEnd(elements, sourceId, nextId) {
410
+ // From the back: the source is almost always one of the last elements added.
411
+ let source;
412
+ for (let i = elements.length - 1; i >= 0 && source === undefined; i--) {
413
+ if (elements[i]?.id === sourceId)
414
+ source = elements[i];
415
+ }
416
+ if (source?.type !== "endEvent")
417
+ return;
418
+ throw new Error(`Cannot chain "${nextId}" after end event "${sourceId}": an end event has no outgoing sequence flow. Remove the end event, or continue from another element.`);
419
+ }
420
+ /**
421
+ * The end of every `build()`: the Camunda 8 builder rules, then the deploy gate,
422
+ * for a model that targets Camunda 8 unless `validate: false`.
423
+ */
424
+ function gateBuild(defs, options) {
425
+ if (options?.validate === false || !targetsCamunda8(defs))
426
+ return defs;
427
+ const placeholders = options?.placeholders ?? false;
428
+ const problem = camunda8BuilderProblem(defs, { placeholders });
429
+ if (problem !== undefined)
430
+ throw new Error(problem);
431
+ const camundaVersion = normalizeCamundaVersion(options?.camundaVersion ?? defs.unknownAttributes["modeler:executionPlatformVersion"]);
432
+ return assertDeployable(defs, { camundaVersion, placeholders }).definitions;
433
+ }
434
+ function assertElementIdsUnique(elements, processId) {
435
+ const seen = new Set();
436
+ const walk = (scope) => {
437
+ for (const element of scope) {
438
+ if (seen.has(element.id)) {
439
+ throw new Error(`Duplicate element ID "${element.id}" in process "${processId}"`);
440
+ }
441
+ seen.add(element.id);
442
+ if ("flowElements" in element)
443
+ walk(element.flowElements);
444
+ }
445
+ };
446
+ walk(elements);
447
+ }
448
+ /**
449
+ * Deep-copies a scope for `build()`, carrying the builder's side tables (keyed
450
+ * by object) over to the copies, so building leaves the builder untouched.
451
+ */
452
+ function cloneScope(elements, flows) {
453
+ const [elementsCopy, flowsCopy] = structuredClone([elements, flows]);
454
+ const carry = (from, fromFlows, to, toFlows) => {
455
+ from.forEach((element, i) => {
456
+ const copy = to[i];
457
+ const form = embeddedForms.get(element);
458
+ if (form !== undefined)
459
+ embeddedForms.set(copy, form);
460
+ if ("flowElements" in element && "flowElements" in copy) {
461
+ carry(element.flowElements, element.sequenceFlows, copy.flowElements, copy.sequenceFlows);
462
+ }
463
+ });
464
+ fromFlows.forEach((flow, i) => copyFlowTags(flow, toFlows[i]));
465
+ };
466
+ carry(elements, flows, elementsCopy, flowsCopy);
467
+ return { elements: elementsCopy, flows: flowsCopy };
468
+ }
319
469
  function recomputeIncomingOutgoing(elements, flows) {
320
470
  for (const el of elements) {
321
471
  el.incoming = [];
@@ -366,7 +516,7 @@ function buildServiceTaskExtensions(options) {
366
516
  }
367
517
  function makeConditionExpression(expression) {
368
518
  return {
369
- text: expression,
519
+ text: toFeelCondition(expression),
370
520
  attributes: { "xsi:type": "bpmn:tFormalExpression" },
371
521
  };
372
522
  }
@@ -499,6 +649,9 @@ function makeStartEventEl(id, options) {
499
649
  executionListeners: options?.executionListeners,
500
650
  extensionElements: zeebeExtensionsToXmlElements({
501
651
  ...(options?.formId ? { formDefinition: { formId: options.formId } } : {}),
652
+ ...(options?.correlationKey
653
+ ? { subscription: { correlationKey: options.correlationKey } }
654
+ : {}),
502
655
  ...(options?.zeebeProperties ? { properties: { properties: options.zeebeProperties } } : {}),
503
656
  }),
504
657
  });
@@ -961,6 +1114,7 @@ export class BranchBuilder {
961
1114
  return this;
962
1115
  }
963
1116
  if (this.lastNodeId) {
1117
+ assertNotAfterEnd(this._elements, this.lastNodeId, element.id);
964
1118
  const flowId = this.isFirstElement
965
1119
  ? (this.pendingFlowId ?? generateId("Flow"))
966
1120
  : generateId("Flow");
@@ -1001,12 +1155,28 @@ export class BranchBuilder {
1001
1155
  * Supports forward references (element created later) and backward references (loops).
1002
1156
  */
1003
1157
  connectTo(targetId) {
1158
+ // After a nested branch() the position is that branch's open ends, not one node.
1159
+ if (this.lastNodeId === undefined) {
1160
+ for (const branchEnd of this.openBranchEnds) {
1161
+ this._flows.push({
1162
+ id: generateId("Flow"),
1163
+ sourceRef: branchEnd,
1164
+ targetRef: targetId,
1165
+ extensionElements: [],
1166
+ unknownAttributes: {},
1167
+ });
1168
+ }
1169
+ this.openBranchEnds = [];
1170
+ this.lastNodeId = targetId;
1171
+ this._connected = true;
1172
+ return this;
1173
+ }
1174
+ assertNotAfterEnd(this._elements, this.lastNodeId, targetId);
1004
1175
  const flowId = this.isFirstElement
1005
1176
  ? (this.pendingFlowId ?? generateId("Flow"))
1006
1177
  : generateId("Flow");
1007
1178
  const flow = {
1008
1179
  id: flowId,
1009
- // biome-ignore lint/style/noNonNullAssertion: lastNodeId starts as gatewayId and is always defined in pre-branch context
1010
1180
  sourceRef: this.lastNodeId,
1011
1181
  targetRef: targetId,
1012
1182
  name: this.isFirstElement ? (this.pendingLabel ?? this.branchName) : undefined,
@@ -1043,7 +1213,7 @@ export class BranchBuilder {
1043
1213
  }
1044
1214
  /** Draws a reference to the data object `dataObjectRef`. */
1045
1215
  dataObjectReference(id, dataObjectRef, options) {
1046
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
1216
+ addDataObjectReference(this._elements, this._ids, id, dataObjectRef, options);
1047
1217
  return this;
1048
1218
  }
1049
1219
  /** Draws a reference to the data store `dataStoreRef`. */
@@ -1059,7 +1229,9 @@ export class BranchBuilder {
1059
1229
  // ---- Annotations ----
1060
1230
  /** Attach a text annotation to the element at the current cursor position. */
1061
1231
  textAnnotation(text) {
1062
- // biome-ignore lint/style/noNonNullAssertion: lastNodeId starts as gatewayId and is always defined in pre-branch context
1232
+ if (!this.lastNodeId) {
1233
+ throw new Error("textAnnotation() must follow a flow element");
1234
+ }
1063
1235
  return this.annotate(this.lastNodeId, text);
1064
1236
  }
1065
1237
  /** Attach a text annotation to an element by explicit ID. */
@@ -1100,7 +1272,7 @@ export class BranchBuilder {
1100
1272
  receiveTask(id, options) {
1101
1273
  const el = makeFlowElement(id, "receiveTask", {
1102
1274
  ...options,
1103
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1275
+ extensionElements: buildMessageSubscriptionExt("receiveTask", options),
1104
1276
  });
1105
1277
  if (options?.isForCompensation)
1106
1278
  el.isForCompensation = true;
@@ -1132,6 +1304,8 @@ export class BranchBuilder {
1132
1304
  const el = makeStartEventEl(id ?? generateId("StartEvent"), options);
1133
1305
  if (el.type === "startEvent" && options) {
1134
1306
  el.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
1307
+ if (options.isInterrupting === false)
1308
+ el.isInterrupting = false;
1135
1309
  }
1136
1310
  return this.addElement(el);
1137
1311
  }
@@ -1152,7 +1326,7 @@ export class BranchBuilder {
1152
1326
  intermediateCatchEvent(id, options) {
1153
1327
  const el = makeFlowElement(id ?? generateId("IntermediateCatchEvent"), "intermediateCatchEvent", {
1154
1328
  ...options,
1155
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1329
+ extensionElements: buildMessageSubscriptionExt("intermediateCatchEvent", options),
1156
1330
  });
1157
1331
  if (el.type === "intermediateCatchEvent" && options) {
1158
1332
  el.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
@@ -1191,7 +1365,7 @@ export class BranchBuilder {
1191
1365
  const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
1192
1366
  const element = makeFlowElement(id, "boundaryEvent", {
1193
1367
  ...options,
1194
- extensionElements: buildMessageSubscriptionExt(options.correlationKey),
1368
+ extensionElements: buildMessageSubscriptionExt("boundaryEvent", options),
1195
1369
  });
1196
1370
  if (element.type === "boundaryEvent") {
1197
1371
  element.attachedToRef = options.attachedTo;
@@ -1218,10 +1392,9 @@ export class BranchBuilder {
1218
1392
  if (!attachedTo || attachedTo === this.gatewayId) {
1219
1393
  throw new Error("withBoundary() must follow a task element inside the branch. Current builder position has no active task.");
1220
1394
  }
1221
- const attachedEl = this._elements.find((n) => n.id === attachedTo);
1222
- if (attachedEl?.type === "boundaryEvent") {
1223
- throw new Error("withBoundary() cannot attach to a boundary event. It must follow a task or activity element.");
1224
- }
1395
+ const hostProblem = boundaryHostProblem(this._elements.find((n) => n.id === attachedTo));
1396
+ if (hostProblem !== undefined)
1397
+ throw new Error(hostProblem);
1225
1398
  const savedLast = this.lastNodeId;
1226
1399
  const savedGateway = this.currentGatewayId;
1227
1400
  const savedConnected = this._connected;
@@ -1292,6 +1465,7 @@ export class BranchBuilder {
1292
1465
  const sub = new SubProcessContentBuilder(this.roots());
1293
1466
  resolved.content(sub);
1294
1467
  finalizeScope(sub._elements, sub._flows);
1468
+ assertEventSubProcessSubscriptions(sub._elements);
1295
1469
  const element = makeFlowElement(id, "subProcess", resolved.options);
1296
1470
  if (element.type === "subProcess") {
1297
1471
  element.triggeredByEvent = true;
@@ -1425,6 +1599,7 @@ export class SubProcessContentBuilder {
1425
1599
  this._ids.add(element.id);
1426
1600
  if (this.autoConnect && !isLinkEvent(element, "intermediateCatchEvent")) {
1427
1601
  if (this.lastNodeId) {
1602
+ assertNotAfterEnd(this._elements, this.lastNodeId, element.id);
1428
1603
  this._flows.push({
1429
1604
  id: generateId("Flow"),
1430
1605
  sourceRef: this.lastNodeId,
@@ -1490,7 +1665,7 @@ export class SubProcessContentBuilder {
1490
1665
  intermediateCatchEvent(id, options) {
1491
1666
  const el = makeFlowElement(id ?? generateId("IntermediateCatchEvent"), "intermediateCatchEvent", {
1492
1667
  ...options,
1493
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1668
+ extensionElements: buildMessageSubscriptionExt("intermediateCatchEvent", options),
1494
1669
  });
1495
1670
  if (el.type === "intermediateCatchEvent" && options)
1496
1671
  el.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
@@ -1523,7 +1698,7 @@ export class SubProcessContentBuilder {
1523
1698
  receiveTask(id, options) {
1524
1699
  const el = makeFlowElement(id, "receiveTask", {
1525
1700
  ...options,
1526
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1701
+ extensionElements: buildMessageSubscriptionExt("receiveTask", options),
1527
1702
  });
1528
1703
  if (options?.isForCompensation)
1529
1704
  el.isForCompensation = true;
@@ -1574,7 +1749,7 @@ export class SubProcessContentBuilder {
1574
1749
  }
1575
1750
  /** Draws a reference to the data object `dataObjectRef`. */
1576
1751
  dataObjectReference(id, dataObjectRef, options) {
1577
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
1752
+ addDataObjectReference(this._elements, this._ids, id, dataObjectRef, options);
1578
1753
  return this;
1579
1754
  }
1580
1755
  /** Draws a reference to the data store `dataStoreRef`. */
@@ -1655,6 +1830,7 @@ export class SubProcessContentBuilder {
1655
1830
  }
1656
1831
  connectTo(targetId) {
1657
1832
  if (this.lastNodeId) {
1833
+ assertNotAfterEnd(this._elements, this.lastNodeId, targetId);
1658
1834
  this._flows.push({
1659
1835
  id: generateId("Flow"),
1660
1836
  sourceRef: this.lastNodeId,
@@ -1687,7 +1863,7 @@ export class SubProcessContentBuilder {
1687
1863
  const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
1688
1864
  const element = makeFlowElement(id, "boundaryEvent", {
1689
1865
  ...options,
1690
- extensionElements: buildMessageSubscriptionExt(options.correlationKey),
1866
+ extensionElements: buildMessageSubscriptionExt("boundaryEvent", options),
1691
1867
  });
1692
1868
  if (element.type === "boundaryEvent") {
1693
1869
  element.attachedToRef = options.attachedTo;
@@ -1713,10 +1889,9 @@ export class SubProcessContentBuilder {
1713
1889
  if (!attachedTo) {
1714
1890
  throw new Error("withBoundary() must follow a task element inside the sub-process. Current builder position has no active task.");
1715
1891
  }
1716
- const attachedEl = this._elements.find((n) => n.id === attachedTo);
1717
- if (attachedEl?.type === "boundaryEvent") {
1718
- throw new Error("withBoundary() cannot attach to a boundary event. It must follow a task or activity element.");
1719
- }
1892
+ const hostProblem = boundaryHostProblem(this._elements.find((n) => n.id === attachedTo));
1893
+ if (hostProblem !== undefined)
1894
+ throw new Error(hostProblem);
1720
1895
  const savedLast = this.lastNodeId;
1721
1896
  const savedGateway = this.currentGatewayId;
1722
1897
  const savedOpenEnds = [...this.openBranchEnds];
@@ -1785,6 +1960,7 @@ export class SubProcessContentBuilder {
1785
1960
  const sub = new SubProcessContentBuilder(this.roots());
1786
1961
  resolved.content(sub);
1787
1962
  finalizeScope(sub._elements, sub._flows);
1963
+ assertEventSubProcessSubscriptions(sub._elements);
1788
1964
  const element = makeFlowElement(id, "subProcess", resolved.options);
1789
1965
  if (element.type === "subProcess") {
1790
1966
  element.triggeredByEvent = true;
@@ -1897,7 +2073,10 @@ export class ProcessBuilder {
1897
2073
  builder.rootMessages.push(...copy.messages);
1898
2074
  builder.rootSignals.push(...copy.signals);
1899
2075
  builder.rootEscalations.push(...copy.escalations);
1900
- builder._sourceFlowTargets = new Map(process.sequenceFlows.map((flow) => [flow.id, `${flow.sourceRef}→${flow.targetRef}`]));
2076
+ builder._sourceFlowTargets = new Map(process.sequenceFlows.map((flow) => [
2077
+ flow.id,
2078
+ { sourceRef: flow.sourceRef, targetRef: flow.targetRef },
2079
+ ]));
1901
2080
  return builder;
1902
2081
  }
1903
2082
  /**
@@ -1919,6 +2098,7 @@ export class ProcessBuilder {
1919
2098
  if (hasOutgoing && !isGatewayType(node.type)) {
1920
2099
  throw new Error(`"${nodeId}" already has an outgoing sequence flow. Continuing from it would give a ${node.type} two outgoing flows, which is an uncontrolled split. Use insertAfter("${nodeId}") to splice into that path instead.`);
1921
2100
  }
2101
+ this.resolvePendingSplice();
1922
2102
  this.moveCursor(node);
1923
2103
  return this;
1924
2104
  }
@@ -2083,7 +2263,11 @@ export class ProcessBuilder {
2083
2263
  return this;
2084
2264
  }
2085
2265
  // ---- Events ----
2086
- /** Add a start event. Start events never auto-connect from the previous element. */
2266
+ /**
2267
+ * Add a start event. Like every element it chains from the current position;
2268
+ * at the beginning of a process there is none. Use `addStartEvent()` for a
2269
+ * start event that begins a new, disconnected path.
2270
+ */
2087
2271
  startEvent(id, options) {
2088
2272
  const element = makeStartEventEl(id ?? generateId("StartEvent"), options);
2089
2273
  if (element.type === "startEvent" && options) {
@@ -2139,7 +2323,7 @@ export class ProcessBuilder {
2139
2323
  const nodeId = id ?? generateId("IntermediateCatchEvent");
2140
2324
  const element = makeFlowElement(nodeId, "intermediateCatchEvent", {
2141
2325
  ...options,
2142
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
2326
+ extensionElements: buildMessageSubscriptionExt("intermediateCatchEvent", options),
2143
2327
  });
2144
2328
  if (element.type === "intermediateCatchEvent" && options) {
2145
2329
  element.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
@@ -2157,7 +2341,7 @@ export class ProcessBuilder {
2157
2341
  const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
2158
2342
  const element = makeFlowElement(id, "boundaryEvent", {
2159
2343
  ...options,
2160
- extensionElements: buildMessageSubscriptionExt(options.correlationKey),
2344
+ extensionElements: buildMessageSubscriptionExt("boundaryEvent", options),
2161
2345
  });
2162
2346
  if (element.type === "boundaryEvent") {
2163
2347
  element.attachedToRef = options.attachedTo;
@@ -2190,6 +2374,9 @@ export class ProcessBuilder {
2190
2374
  if (!attachedTo) {
2191
2375
  throw new Error("withBoundary() must follow a task element. Current builder position has no active element.");
2192
2376
  }
2377
+ const hostProblem = boundaryHostProblem(this.flowElements.find((n) => n.id === attachedTo));
2378
+ if (hostProblem !== undefined)
2379
+ throw new Error(hostProblem);
2193
2380
  const savedLast = this.lastNodeId;
2194
2381
  const savedGateway = this.currentGatewayId;
2195
2382
  const savedOpenEnds = [...this.openBranchEnds];
@@ -2265,7 +2452,7 @@ export class ProcessBuilder {
2265
2452
  receiveTask(id, options) {
2266
2453
  const el = makeFlowElement(id, "receiveTask", {
2267
2454
  ...options,
2268
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
2455
+ extensionElements: buildMessageSubscriptionExt("receiveTask", options),
2269
2456
  });
2270
2457
  if (options?.isForCompensation)
2271
2458
  el.isForCompensation = true;
@@ -2396,6 +2583,7 @@ export class ProcessBuilder {
2396
2583
  /** Connect the current position to an existing or future element by ID. */
2397
2584
  connectTo(targetId) {
2398
2585
  if (this.lastNodeId) {
2586
+ assertNotAfterEnd(this.flowElements, this.lastNodeId, targetId);
2399
2587
  const flowId = generateId("Flow");
2400
2588
  this.sequenceFlows.push({
2401
2589
  id: flowId,
@@ -2419,6 +2607,7 @@ export class ProcessBuilder {
2419
2607
  if (!found) {
2420
2608
  throw new Error(`Element "${elementId}" not found in process "${this.processId}"`);
2421
2609
  }
2610
+ this.resolvePendingSplice();
2422
2611
  this.lastNodeId = elementId;
2423
2612
  this.currentGatewayId = undefined;
2424
2613
  return this;
@@ -2480,6 +2669,7 @@ export class ProcessBuilder {
2480
2669
  const sub = new SubProcessContentBuilder(this.roots());
2481
2670
  resolved.content(sub);
2482
2671
  finalizeScope(sub._elements, sub._flows);
2672
+ assertEventSubProcessSubscriptions(sub._elements);
2483
2673
  const element = makeFlowElement(id, "subProcess", resolved.options);
2484
2674
  if (element.type === "subProcess") {
2485
2675
  element.triggeredByEvent = true;
@@ -2508,7 +2698,7 @@ export class ProcessBuilder {
2508
2698
  }
2509
2699
  /** Draws a reference to the data object `dataObjectRef`. */
2510
2700
  dataObjectReference(id, dataObjectRef, options) {
2511
- addDataElement(this.flowElements, this.elementIds, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
2701
+ addDataObjectReference(this.flowElements, this.elementIds, id, dataObjectRef, options);
2512
2702
  return this;
2513
2703
  }
2514
2704
  /** Draws a reference to the data store `dataStoreRef`. */
@@ -2570,43 +2760,59 @@ export class ProcessBuilder {
2570
2760
  * says: inference reads the whole topology, and on a document you were handed
2571
2761
  * that means rewriting edges you never touched.
2572
2762
  *
2573
- * @param options - `explicitJoins` refuses inferred join gateways.
2763
+ * **The deploy gate.** A model that targets Camunda 8 (every new one does) must
2764
+ * deploy: `build()` refuses with a clear error what the builder can name (a
2765
+ * branch without a condition, a send task without a `taskType`, ...) and then
2766
+ * runs {@link assertDeployable}, which throws a `DeployabilityError` listing
2767
+ * whatever Zeebe would still reject. See {@link BuildGateOptions} for
2768
+ * `validate`, `placeholders` and `camundaVersion`.
2769
+ *
2770
+ * @param options - `explicitJoins` refuses inferred join gateways; `validate`,
2771
+ * `placeholders` and `camundaVersion` control the deploy gate.
2772
+ * @throws {DeployabilityError} When the gate runs and Zeebe would reject the model.
2574
2773
  */
2575
2774
  build(options) {
2775
+ return gateBuild(this.buildModel(options), options);
2776
+ }
2777
+ buildModel(options) {
2576
2778
  this.resolvePendingSplice();
2577
- const beforeCount = this.flowElements.length;
2779
+ // Built from a copy: the result shares nothing with the builder, and a
2780
+ // second build() (or one after a throwing build) starts from the same state.
2781
+ const { elements, flows } = cloneScope(this.flowElements, this.sequenceFlows);
2782
+ const beforeCount = elements.length;
2578
2783
  // Continuing a document never infers joins. `insertJoinGateways` reads the
2579
2784
  // whole topology, so on a parsed model it retargets edges the caller never
2580
2785
  // touched — the corpus has a document where a no-op continue would have
2581
2786
  // invented a join gateway and rerouted two flows into it. Building a branch
2582
2787
  // that needs a join here means saying so with `.connectTo(joinId)`.
2583
2788
  if (this._source === undefined)
2584
- insertJoinGateways(this.flowElements, this.sequenceFlows);
2789
+ insertJoinGateways(elements, flows);
2585
2790
  const explicitJoins = options?.explicitJoins ?? false;
2586
- if (explicitJoins && this.flowElements.length > beforeCount) {
2587
- const inserted = this.flowElements
2791
+ if (explicitJoins && elements.length > beforeCount) {
2792
+ const inserted = elements
2588
2793
  .slice(beforeCount)
2589
2794
  .map((e) => e.id)
2590
2795
  .join(", ");
2591
2796
  throw new Error(`Inferred join gateways: ${inserted}. Declare them with .connectTo(joinId), or drop { explicitJoins: true } to keep the inference.`);
2592
2797
  }
2593
- this.validate();
2594
- this.assertSourceTopologyIntact();
2798
+ assertElementIdsUnique(elements, this.processId);
2799
+ this.validate(elements, flows);
2800
+ this.assertSourceTopologyIntact(flows);
2595
2801
  // Flows the document already had keep their ids: continuing a model must
2596
2802
  // not renumber the part the caller did not touch.
2597
- assignStableFlowIds(this.flowElements, this.sequenceFlows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
2598
- assertExplicitFlowIdsUnique(this.flowElements, this.sequenceFlows);
2803
+ assignStableFlowIds(elements, flows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
2804
+ assertExplicitFlowIdsUnique(elements, flows);
2599
2805
  // A continued document keeps its untouched part byte-for-byte, ids included.
2600
2806
  if (this._source === undefined) {
2601
- for (const el of this.flowElements) {
2807
+ for (const el of elements) {
2602
2808
  if ("eventDefinitions" in el)
2603
2809
  assignEventDefinitionIds(el.id, el.eventDefinitions);
2604
2810
  }
2605
2811
  }
2606
- recomputeIncomingOutgoing(this.flowElements, this.sequenceFlows);
2812
+ recomputeIncomingOutgoing(elements, flows);
2607
2813
  if (this._source !== undefined)
2608
- return this.buildOntoSource(this._source);
2609
- const extensionElements = embeddedFormElements(this.flowElements);
2814
+ return this.buildOntoSource(this._source, elements, flows);
2815
+ const extensionElements = embeddedFormElements(elements);
2610
2816
  if (this._versionTag) {
2611
2817
  extensionElements.push({
2612
2818
  name: "zeebe:versionTag",
@@ -2619,10 +2825,10 @@ export class ProcessBuilder {
2619
2825
  name: this.processName,
2620
2826
  isExecutable: this._isExecutable,
2621
2827
  extensionElements,
2622
- flowElements: this.flowElements,
2623
- sequenceFlows: this.sequenceFlows,
2624
- textAnnotations: this._textAnnotations,
2625
- associations: this._associations,
2828
+ flowElements: elements,
2829
+ sequenceFlows: flows,
2830
+ textAnnotations: structuredClone(this._textAnnotations),
2831
+ associations: structuredClone(this._associations),
2626
2832
  groups: [],
2627
2833
  unknownAttributes: {},
2628
2834
  };
@@ -2644,10 +2850,10 @@ export class ProcessBuilder {
2644
2850
  "modeler:executionPlatform": "Camunda Cloud",
2645
2851
  "modeler:executionPlatformVersion": this._executionPlatformVersion,
2646
2852
  },
2647
- errors: this.rootErrors,
2648
- escalations: this.rootEscalations,
2649
- messages: this.rootMessages,
2650
- signals: this.rootSignals,
2853
+ errors: structuredClone(this.rootErrors),
2854
+ escalations: structuredClone(this.rootEscalations),
2855
+ messages: structuredClone(this.rootMessages),
2856
+ signals: structuredClone(this.rootSignals),
2651
2857
  collaborations: [],
2652
2858
  processes: [process],
2653
2859
  // Seed diagram stub so applyAutoLayout preserves process-specific IDs.
@@ -2679,12 +2885,13 @@ export class ProcessBuilder {
2679
2885
  * positions, and elements added here have none until `withAutoLayout()` or a
2680
2886
  * later `applyAutoLayout()` gives them one.
2681
2887
  */
2682
- buildOntoSource(source) {
2683
- const { definitions, process } = source;
2684
- process.flowElements = this.flowElements;
2685
- process.sequenceFlows = this.sequenceFlows;
2686
- process.textAnnotations = this._textAnnotations;
2687
- process.associations = this._associations;
2888
+ buildOntoSource(source, elements, flows) {
2889
+ const definitions = structuredClone(source.definitions);
2890
+ const process = definitions.processes[source.definitions.processes.indexOf(source.process)];
2891
+ process.flowElements = elements;
2892
+ process.sequenceFlows = flows;
2893
+ process.textAnnotations = structuredClone(this._textAnnotations);
2894
+ process.associations = structuredClone(this._associations);
2688
2895
  if (this.processName !== undefined)
2689
2896
  process.name = this.processName;
2690
2897
  // Only when asked. BPMN reads an absent `isExecutable` as false, so writing
@@ -2697,17 +2904,17 @@ export class ProcessBuilder {
2697
2904
  // bag: a real process carries other extensions next to it.
2698
2905
  ensureZeebeExtension({ type: "process", extensionElements: process.extensionElements }, "zeebe:versionTag").attributes.value = this._versionTag;
2699
2906
  }
2700
- for (const form of embeddedFormElements(this.flowElements)) {
2907
+ for (const form of embeddedFormElements(elements)) {
2701
2908
  const at = process.extensionElements.findIndex((e) => e.name === form.name && e.attributes.id === form.attributes.id);
2702
2909
  if (at >= 0)
2703
2910
  process.extensionElements[at] = form;
2704
2911
  else
2705
2912
  process.extensionElements.push(form);
2706
2913
  }
2707
- definitions.errors = this.rootErrors;
2708
- definitions.messages = this.rootMessages;
2709
- definitions.signals = this.rootSignals;
2710
- definitions.escalations = this.rootEscalations;
2914
+ definitions.errors = structuredClone(this.rootErrors);
2915
+ definitions.messages = structuredClone(this.rootMessages);
2916
+ definitions.signals = structuredClone(this.rootSignals);
2917
+ definitions.escalations = structuredClone(this.rootEscalations);
2711
2918
  return hoistMessageSubscriptions(this._autoLayout
2712
2919
  ? applyAutoLayout(definitions, "semantic", this.rootLayoutHints)
2713
2920
  : definitions);
@@ -2720,12 +2927,12 @@ export class ProcessBuilder {
2720
2927
  * document would come back with edges the caller never touched pointing
2721
2928
  * somewhere else. Continuing a model has to leave the model alone.
2722
2929
  */
2723
- assertSourceTopologyIntact() {
2930
+ assertSourceTopologyIntact(flows) {
2724
2931
  if (this._source === undefined)
2725
2932
  return;
2726
2933
  const rewired = [];
2727
- const byId = new Map(this.sequenceFlows.map((flow) => [flow.id, flow]));
2728
- for (const [id, endpoints] of this._sourceFlowTargets) {
2934
+ const byId = new Map(flows.map((flow) => [flow.id, flow]));
2935
+ for (const [id, { sourceRef, targetRef: target }] of this._sourceFlowTargets) {
2729
2936
  const flow = byId.get(id);
2730
2937
  if (flow === undefined) {
2731
2938
  rewired.push(`${id} (removed)`);
@@ -2733,32 +2940,31 @@ export class ProcessBuilder {
2733
2940
  }
2734
2941
  // A spliced flow was moved on purpose, but only its source may move:
2735
2942
  // `insertAfter` inserts into a path, it does not redirect one.
2736
- const [, target] = endpoints.split("→");
2737
2943
  if (this._splicedFlowIds.has(id)) {
2738
2944
  if (flow.targetRef !== target) {
2739
2945
  rewired.push(`${id} (spliced flow now targets ${flow.targetRef}, not ${target})`);
2740
2946
  }
2741
2947
  continue;
2742
2948
  }
2743
- const now = `${flow.sourceRef}→${flow.targetRef}`;
2744
- if (now !== endpoints)
2745
- rewired.push(`${id} (${endpoints} became ${now})`);
2949
+ if (flow.sourceRef !== sourceRef || flow.targetRef !== target) {
2950
+ rewired.push(`${id} (${sourceRef}→${target} became ${flow.sourceRef}→${flow.targetRef})`);
2951
+ }
2746
2952
  }
2747
2953
  if (rewired.length > 0) {
2748
2954
  throw new Error(`Building would rewire sequence flows this document already had: ${rewired.join(", ")}. Continuing a model must not change the part you did not touch.`);
2749
2955
  }
2750
2956
  }
2751
- validate() {
2957
+ validate(elements, flows) {
2752
2958
  // A parsed document keeps whatever ids it came with; only new builds are held to the XSD.
2753
2959
  if (this._source === undefined) {
2754
2960
  assertXsdValues({
2755
2961
  id: this.processId,
2756
- flowElements: this.flowElements,
2757
- sequenceFlows: this.sequenceFlows,
2962
+ flowElements: elements,
2963
+ sequenceFlows: flows,
2758
2964
  });
2759
2965
  }
2760
- const elementIds = new Set(this.flowElements.map((el) => el.id));
2761
- for (const flow of this.sequenceFlows) {
2966
+ const elementIds = new Set(elements.map((el) => el.id));
2967
+ for (const flow of flows) {
2762
2968
  if (!elementIds.has(flow.targetRef)) {
2763
2969
  throw new Error(`Sequence flow "${flow.id}" in process "${this.processId}" references unknown ` +
2764
2970
  `element "${flow.targetRef}". Check connectTo() calls — target must exist.`);
@@ -2800,6 +3006,7 @@ export class ProcessBuilder {
2800
3006
  return;
2801
3007
  }
2802
3008
  if (this.lastNodeId) {
3009
+ assertNotAfterEnd(this.flowElements, this.lastNodeId, element.id);
2803
3010
  const flowId = generateId("Flow");
2804
3011
  this.sequenceFlows.push({
2805
3012
  id: flowId,
@@ -2840,6 +3047,23 @@ function mergeRootDefinitions(into, incoming) {
2840
3047
  into.push(definition);
2841
3048
  }
2842
3049
  }
3050
+ /**
3051
+ * A message two pools share keeps the correlation key a later pool hoisted onto
3052
+ * its copy when the first copy has none; dropping it would leave that pool's
3053
+ * catch without the `zeebe:subscription` Zeebe requires.
3054
+ */
3055
+ function adoptMessageSubscriptions(into, incoming) {
3056
+ const isSubscription = (x) => x.name === "zeebe:subscription";
3057
+ for (const message of incoming) {
3058
+ const sub = message.extensionElements?.find(isSubscription);
3059
+ const target = into.find((m) => m.id === message.id);
3060
+ if (sub === undefined || target === undefined || target === message)
3061
+ continue;
3062
+ if (target.extensionElements?.some(isSubscription))
3063
+ continue;
3064
+ target.extensionElements = [...(target.extensionElements ?? []), sub];
3065
+ }
3066
+ }
2843
3067
  /**
2844
3068
  * Builder for a complete BPMN definitions document containing one or more processes.
2845
3069
  * Use `Bpmn.createDiagram(id?)` to obtain an instance.
@@ -2864,13 +3088,15 @@ export class DiagramBuilder {
2864
3088
  process(id, callback) {
2865
3089
  const builder = new ProcessBuilder(id);
2866
3090
  callback(builder);
2867
- const defs = builder.build();
3091
+ // The document is gated as a whole in build(): a pool may only deploy next to the others.
3092
+ const defs = builder.build({ validate: false });
2868
3093
  this._processes.push(...defs.processes);
2869
3094
  // Root definitions are named after the message or error code they carry, so
2870
3095
  // two pools declaring the same one produce the same definition twice. The
2871
3096
  // document needs it once.
2872
3097
  mergeRootDefinitions(this._errors, defs.errors);
2873
3098
  mergeRootDefinitions(this._messages, defs.messages);
3099
+ adoptMessageSubscriptions(this._messages, defs.messages);
2874
3100
  return this;
2875
3101
  }
2876
3102
  /** Renames the collaboration element. Defaults to `"Collaboration_1"`. */
@@ -3019,7 +3245,16 @@ export class DiagramBuilder {
3019
3245
  }
3020
3246
  return index;
3021
3247
  }
3022
- build() {
3248
+ /**
3249
+ * Build the document. Gated like {@link ProcessBuilder.build}: see
3250
+ * {@link BuildGateOptions}.
3251
+ *
3252
+ * @throws {DeployabilityError} When the gate runs and Zeebe would reject the document.
3253
+ */
3254
+ build(options) {
3255
+ return gateBuild(this.buildModel(), options);
3256
+ }
3257
+ buildModel() {
3023
3258
  return hoistMessageSubscriptions({
3024
3259
  id: this._id,
3025
3260
  targetNamespace: "http://bpmn.io/schema/bpmn",