@bpmnkit/core 1.8.0 → 1.10.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 (110) hide show
  1. package/agent-cards/bpmn.md +4 -2
  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 +321 -76
  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 +17 -1
  28. package/dist/bpmn/index.js +19 -25
  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/xsd-guards.d.ts +8 -0
  42. package/dist/bpmn/xsd-guards.js +56 -0
  43. package/dist/bpmn/zeebe-extensions.js +2 -1
  44. package/dist/bpmn/zeebe-placement.js +6 -129
  45. package/dist/bpmn/zeebe-validate/context.d.ts +132 -0
  46. package/dist/bpmn/zeebe-validate/context.js +241 -0
  47. package/dist/bpmn/zeebe-validate/gate.d.ts +87 -0
  48. package/dist/bpmn/zeebe-validate/gate.js +492 -0
  49. package/dist/bpmn/zeebe-validate/index.d.ts +37 -0
  50. package/dist/bpmn/zeebe-validate/index.js +106 -0
  51. package/dist/bpmn/zeebe-validate/rules/events.d.ts +4 -0
  52. package/dist/bpmn/zeebe-validate/rules/events.js +580 -0
  53. package/dist/bpmn/zeebe-validate/rules/extensions.d.ts +4 -0
  54. package/dist/bpmn/zeebe-validate/rules/extensions.js +411 -0
  55. package/dist/bpmn/zeebe-validate/rules/gateways.d.ts +3 -0
  56. package/dist/bpmn/zeebe-validate/rules/gateways.js +296 -0
  57. package/dist/bpmn/zeebe-validate/rules/references.d.ts +3 -0
  58. package/dist/bpmn/zeebe-validate/rules/references.js +495 -0
  59. package/dist/bpmn/zeebe-validate/rules/structure.d.ts +3 -0
  60. package/dist/bpmn/zeebe-validate/rules/structure.js +629 -0
  61. package/dist/bpmn/zeebe-validate/rules/tasks.d.ts +4 -0
  62. package/dist/bpmn/zeebe-validate/rules/tasks.js +446 -0
  63. package/dist/bpmn/zeebe-validate/xml.d.ts +15 -0
  64. package/dist/bpmn/zeebe-validate/xml.js +1062 -0
  65. package/dist/bpmn/zeebe-validate/xsd.d.ts +19 -0
  66. package/dist/bpmn/zeebe-validate/xsd.js +350 -0
  67. package/dist/connectors/apply-element.d.ts +5 -2
  68. package/dist/connectors/apply-element.js +6 -0
  69. package/dist/connectors/apply-many.d.ts +9 -2
  70. package/dist/connectors/apply-many.js +17 -2
  71. package/dist/connectors/apply.d.ts +4 -2
  72. package/dist/connectors/deployability.d.ts +27 -0
  73. package/dist/connectors/deployability.js +41 -0
  74. package/dist/connectors/index.d.ts +1 -0
  75. package/dist/connectors/lines.d.ts +10 -0
  76. package/dist/connectors/lines.js +13 -4
  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 +11 -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,10 +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";
10
+ import { assertRetriesOption, assertXsdValues } from "./xsd-guards.js";
7
11
  import { assertZeebePlacement, bpmnElementName, ensureZeebeExtension, makeConditionalDefinition, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
12
+ import { assertDeployable, targetsCamunda8 } from "./zeebe-validate/gate.js";
8
13
  // Keep in sync with packages/core/package.json version
9
14
  const EXPORTER_VERSION = "0.0.23";
10
15
  /**
@@ -23,10 +28,38 @@ function makeDataElement(id, type, ref, options) {
23
28
  el.dataObjectRef = ref;
24
29
  if (el.type === "dataStoreReference")
25
30
  el.dataStoreRef = ref;
26
- if (options?.isCollection && (el.type === "dataObject" || el.type === "dataObjectReference"))
31
+ if (options?.isCollection && el.type === "dataObject")
27
32
  el.isCollection = true;
28
33
  return el;
29
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
+ }
30
63
  /**
31
64
  * Input: the data reference is the association's source. Output: it is the
32
65
  * target. Either way the activity owns the association element.
@@ -36,7 +69,11 @@ function addDataAssociation(elements, activityId, dataRefId, direction) {
36
69
  if (!activity)
37
70
  throw new Error(`dataAssociation(): no element "${activityId}" in this scope`);
38
71
  const association = direction === "input"
39
- ? { sourceRefs: [dataRefId], unknownAttributes: {} }
72
+ ? {
73
+ sourceRefs: [dataRefId],
74
+ targetRef: targetRefPlaceholder(activity),
75
+ unknownAttributes: {},
76
+ }
40
77
  : { sourceRefs: [], targetRef: dataRefId, unknownAttributes: {} };
41
78
  const key = direction === "input" ? "dataInputAssociations" : "dataOutputAssociations";
42
79
  activity[key] = [...(activity[key] ?? []), association];
@@ -130,11 +167,34 @@ function hoistMessageSubscriptions(defs) {
130
167
  }
131
168
  return defs;
132
169
  }
133
- function buildMessageSubscriptionExt(correlationKey) {
134
- 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
+ }
135
178
  return [];
179
+ }
136
180
  return zeebeExtensionsToXmlElements({ subscription: { correlationKey } });
137
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
+ }
138
198
  function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, rootEscalations) {
139
199
  const defs = [];
140
200
  if (opts.timerDuration || opts.timerDate || opts.timerCycle) {
@@ -229,9 +289,18 @@ function isLinkEvent(element, type) {
229
289
  * switch; this wrapper exists so the builder's many call sites keep their
230
290
  * shorter local name.
231
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
+ ]);
232
298
  function makeFlowElement(id, type, options) {
233
299
  const el = createFlowElement(id, type, options);
234
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
+ }
235
304
  // Placement is checked here, so a listener on an element the schema forbids it on
236
305
  // fails at build time, not at deploy time.
237
306
  const listeners = zeebeExtensionsToXmlElements({
@@ -261,7 +330,7 @@ function buildMultiInstance(options) {
261
330
  isSequential: options.isSequential || undefined,
262
331
  completionCondition: options.completionCondition
263
332
  ? {
264
- text: options.completionCondition,
333
+ text: toFeelCondition(options.completionCondition),
265
334
  attributes: { "xsi:type": "bpmn:tFormalExpression" },
266
335
  }
267
336
  : undefined,
@@ -315,6 +384,88 @@ const GATEWAY_ELEMENT_TYPES = new Set([
315
384
  function isGatewayType(type) {
316
385
  return GATEWAY_ELEMENT_TYPES.has(type);
317
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
+ }
318
469
  function recomputeIncomingOutgoing(elements, flows) {
319
470
  for (const el of elements) {
320
471
  el.incoming = [];
@@ -349,6 +500,7 @@ function buildMappingExtensions(options) {
349
500
  return extensions;
350
501
  }
351
502
  function buildServiceTaskExtensions(options) {
503
+ assertRetriesOption(options.retries, options.taskType);
352
504
  const extensions = {
353
505
  taskDefinition: {
354
506
  type: options.taskType,
@@ -364,7 +516,7 @@ function buildServiceTaskExtensions(options) {
364
516
  }
365
517
  function makeConditionExpression(expression) {
366
518
  return {
367
- text: expression,
519
+ text: toFeelCondition(expression),
368
520
  attributes: { "xsi:type": "bpmn:tFormalExpression" },
369
521
  };
370
522
  }
@@ -497,6 +649,9 @@ function makeStartEventEl(id, options) {
497
649
  executionListeners: options?.executionListeners,
498
650
  extensionElements: zeebeExtensionsToXmlElements({
499
651
  ...(options?.formId ? { formDefinition: { formId: options.formId } } : {}),
652
+ ...(options?.correlationKey
653
+ ? { subscription: { correlationKey: options.correlationKey } }
654
+ : {}),
500
655
  ...(options?.zeebeProperties ? { properties: { properties: options.zeebeProperties } } : {}),
501
656
  }),
502
657
  });
@@ -959,6 +1114,7 @@ export class BranchBuilder {
959
1114
  return this;
960
1115
  }
961
1116
  if (this.lastNodeId) {
1117
+ assertNotAfterEnd(this._elements, this.lastNodeId, element.id);
962
1118
  const flowId = this.isFirstElement
963
1119
  ? (this.pendingFlowId ?? generateId("Flow"))
964
1120
  : generateId("Flow");
@@ -999,12 +1155,28 @@ export class BranchBuilder {
999
1155
  * Supports forward references (element created later) and backward references (loops).
1000
1156
  */
1001
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);
1002
1175
  const flowId = this.isFirstElement
1003
1176
  ? (this.pendingFlowId ?? generateId("Flow"))
1004
1177
  : generateId("Flow");
1005
1178
  const flow = {
1006
1179
  id: flowId,
1007
- // biome-ignore lint/style/noNonNullAssertion: lastNodeId starts as gatewayId and is always defined in pre-branch context
1008
1180
  sourceRef: this.lastNodeId,
1009
1181
  targetRef: targetId,
1010
1182
  name: this.isFirstElement ? (this.pendingLabel ?? this.branchName) : undefined,
@@ -1041,7 +1213,7 @@ export class BranchBuilder {
1041
1213
  }
1042
1214
  /** Draws a reference to the data object `dataObjectRef`. */
1043
1215
  dataObjectReference(id, dataObjectRef, options) {
1044
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
1216
+ addDataObjectReference(this._elements, this._ids, id, dataObjectRef, options);
1045
1217
  return this;
1046
1218
  }
1047
1219
  /** Draws a reference to the data store `dataStoreRef`. */
@@ -1057,7 +1229,9 @@ export class BranchBuilder {
1057
1229
  // ---- Annotations ----
1058
1230
  /** Attach a text annotation to the element at the current cursor position. */
1059
1231
  textAnnotation(text) {
1060
- // 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
+ }
1061
1235
  return this.annotate(this.lastNodeId, text);
1062
1236
  }
1063
1237
  /** Attach a text annotation to an element by explicit ID. */
@@ -1098,7 +1272,7 @@ export class BranchBuilder {
1098
1272
  receiveTask(id, options) {
1099
1273
  const el = makeFlowElement(id, "receiveTask", {
1100
1274
  ...options,
1101
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1275
+ extensionElements: buildMessageSubscriptionExt("receiveTask", options),
1102
1276
  });
1103
1277
  if (options?.isForCompensation)
1104
1278
  el.isForCompensation = true;
@@ -1130,6 +1304,8 @@ export class BranchBuilder {
1130
1304
  const el = makeStartEventEl(id ?? generateId("StartEvent"), options);
1131
1305
  if (el.type === "startEvent" && options) {
1132
1306
  el.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
1307
+ if (options.isInterrupting === false)
1308
+ el.isInterrupting = false;
1133
1309
  }
1134
1310
  return this.addElement(el);
1135
1311
  }
@@ -1150,7 +1326,7 @@ export class BranchBuilder {
1150
1326
  intermediateCatchEvent(id, options) {
1151
1327
  const el = makeFlowElement(id ?? generateId("IntermediateCatchEvent"), "intermediateCatchEvent", {
1152
1328
  ...options,
1153
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1329
+ extensionElements: buildMessageSubscriptionExt("intermediateCatchEvent", options),
1154
1330
  });
1155
1331
  if (el.type === "intermediateCatchEvent" && options) {
1156
1332
  el.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
@@ -1189,7 +1365,7 @@ export class BranchBuilder {
1189
1365
  const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
1190
1366
  const element = makeFlowElement(id, "boundaryEvent", {
1191
1367
  ...options,
1192
- extensionElements: buildMessageSubscriptionExt(options.correlationKey),
1368
+ extensionElements: buildMessageSubscriptionExt("boundaryEvent", options),
1193
1369
  });
1194
1370
  if (element.type === "boundaryEvent") {
1195
1371
  element.attachedToRef = options.attachedTo;
@@ -1216,10 +1392,9 @@ export class BranchBuilder {
1216
1392
  if (!attachedTo || attachedTo === this.gatewayId) {
1217
1393
  throw new Error("withBoundary() must follow a task element inside the branch. Current builder position has no active task.");
1218
1394
  }
1219
- const attachedEl = this._elements.find((n) => n.id === attachedTo);
1220
- if (attachedEl?.type === "boundaryEvent") {
1221
- throw new Error("withBoundary() cannot attach to a boundary event. It must follow a task or activity element.");
1222
- }
1395
+ const hostProblem = boundaryHostProblem(this._elements.find((n) => n.id === attachedTo));
1396
+ if (hostProblem !== undefined)
1397
+ throw new Error(hostProblem);
1223
1398
  const savedLast = this.lastNodeId;
1224
1399
  const savedGateway = this.currentGatewayId;
1225
1400
  const savedConnected = this._connected;
@@ -1290,6 +1465,7 @@ export class BranchBuilder {
1290
1465
  const sub = new SubProcessContentBuilder(this.roots());
1291
1466
  resolved.content(sub);
1292
1467
  finalizeScope(sub._elements, sub._flows);
1468
+ assertEventSubProcessSubscriptions(sub._elements);
1293
1469
  const element = makeFlowElement(id, "subProcess", resolved.options);
1294
1470
  if (element.type === "subProcess") {
1295
1471
  element.triggeredByEvent = true;
@@ -1423,6 +1599,7 @@ export class SubProcessContentBuilder {
1423
1599
  this._ids.add(element.id);
1424
1600
  if (this.autoConnect && !isLinkEvent(element, "intermediateCatchEvent")) {
1425
1601
  if (this.lastNodeId) {
1602
+ assertNotAfterEnd(this._elements, this.lastNodeId, element.id);
1426
1603
  this._flows.push({
1427
1604
  id: generateId("Flow"),
1428
1605
  sourceRef: this.lastNodeId,
@@ -1488,7 +1665,7 @@ export class SubProcessContentBuilder {
1488
1665
  intermediateCatchEvent(id, options) {
1489
1666
  const el = makeFlowElement(id ?? generateId("IntermediateCatchEvent"), "intermediateCatchEvent", {
1490
1667
  ...options,
1491
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1668
+ extensionElements: buildMessageSubscriptionExt("intermediateCatchEvent", options),
1492
1669
  });
1493
1670
  if (el.type === "intermediateCatchEvent" && options)
1494
1671
  el.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
@@ -1521,7 +1698,7 @@ export class SubProcessContentBuilder {
1521
1698
  receiveTask(id, options) {
1522
1699
  const el = makeFlowElement(id, "receiveTask", {
1523
1700
  ...options,
1524
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
1701
+ extensionElements: buildMessageSubscriptionExt("receiveTask", options),
1525
1702
  });
1526
1703
  if (options?.isForCompensation)
1527
1704
  el.isForCompensation = true;
@@ -1572,7 +1749,7 @@ export class SubProcessContentBuilder {
1572
1749
  }
1573
1750
  /** Draws a reference to the data object `dataObjectRef`. */
1574
1751
  dataObjectReference(id, dataObjectRef, options) {
1575
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
1752
+ addDataObjectReference(this._elements, this._ids, id, dataObjectRef, options);
1576
1753
  return this;
1577
1754
  }
1578
1755
  /** Draws a reference to the data store `dataStoreRef`. */
@@ -1653,6 +1830,7 @@ export class SubProcessContentBuilder {
1653
1830
  }
1654
1831
  connectTo(targetId) {
1655
1832
  if (this.lastNodeId) {
1833
+ assertNotAfterEnd(this._elements, this.lastNodeId, targetId);
1656
1834
  this._flows.push({
1657
1835
  id: generateId("Flow"),
1658
1836
  sourceRef: this.lastNodeId,
@@ -1685,7 +1863,7 @@ export class SubProcessContentBuilder {
1685
1863
  const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
1686
1864
  const element = makeFlowElement(id, "boundaryEvent", {
1687
1865
  ...options,
1688
- extensionElements: buildMessageSubscriptionExt(options.correlationKey),
1866
+ extensionElements: buildMessageSubscriptionExt("boundaryEvent", options),
1689
1867
  });
1690
1868
  if (element.type === "boundaryEvent") {
1691
1869
  element.attachedToRef = options.attachedTo;
@@ -1711,10 +1889,9 @@ export class SubProcessContentBuilder {
1711
1889
  if (!attachedTo) {
1712
1890
  throw new Error("withBoundary() must follow a task element inside the sub-process. Current builder position has no active task.");
1713
1891
  }
1714
- const attachedEl = this._elements.find((n) => n.id === attachedTo);
1715
- if (attachedEl?.type === "boundaryEvent") {
1716
- throw new Error("withBoundary() cannot attach to a boundary event. It must follow a task or activity element.");
1717
- }
1892
+ const hostProblem = boundaryHostProblem(this._elements.find((n) => n.id === attachedTo));
1893
+ if (hostProblem !== undefined)
1894
+ throw new Error(hostProblem);
1718
1895
  const savedLast = this.lastNodeId;
1719
1896
  const savedGateway = this.currentGatewayId;
1720
1897
  const savedOpenEnds = [...this.openBranchEnds];
@@ -1783,6 +1960,7 @@ export class SubProcessContentBuilder {
1783
1960
  const sub = new SubProcessContentBuilder(this.roots());
1784
1961
  resolved.content(sub);
1785
1962
  finalizeScope(sub._elements, sub._flows);
1963
+ assertEventSubProcessSubscriptions(sub._elements);
1786
1964
  const element = makeFlowElement(id, "subProcess", resolved.options);
1787
1965
  if (element.type === "subProcess") {
1788
1966
  element.triggeredByEvent = true;
@@ -1895,7 +2073,10 @@ export class ProcessBuilder {
1895
2073
  builder.rootMessages.push(...copy.messages);
1896
2074
  builder.rootSignals.push(...copy.signals);
1897
2075
  builder.rootEscalations.push(...copy.escalations);
1898
- 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
+ ]));
1899
2080
  return builder;
1900
2081
  }
1901
2082
  /**
@@ -1917,6 +2098,7 @@ export class ProcessBuilder {
1917
2098
  if (hasOutgoing && !isGatewayType(node.type)) {
1918
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.`);
1919
2100
  }
2101
+ this.resolvePendingSplice();
1920
2102
  this.moveCursor(node);
1921
2103
  return this;
1922
2104
  }
@@ -2081,7 +2263,11 @@ export class ProcessBuilder {
2081
2263
  return this;
2082
2264
  }
2083
2265
  // ---- Events ----
2084
- /** 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
+ */
2085
2271
  startEvent(id, options) {
2086
2272
  const element = makeStartEventEl(id ?? generateId("StartEvent"), options);
2087
2273
  if (element.type === "startEvent" && options) {
@@ -2137,7 +2323,7 @@ export class ProcessBuilder {
2137
2323
  const nodeId = id ?? generateId("IntermediateCatchEvent");
2138
2324
  const element = makeFlowElement(nodeId, "intermediateCatchEvent", {
2139
2325
  ...options,
2140
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
2326
+ extensionElements: buildMessageSubscriptionExt("intermediateCatchEvent", options),
2141
2327
  });
2142
2328
  if (element.type === "intermediateCatchEvent" && options) {
2143
2329
  element.eventDefinitions = buildEventDefinitions(options, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations);
@@ -2155,7 +2341,7 @@ export class ProcessBuilder {
2155
2341
  const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
2156
2342
  const element = makeFlowElement(id, "boundaryEvent", {
2157
2343
  ...options,
2158
- extensionElements: buildMessageSubscriptionExt(options.correlationKey),
2344
+ extensionElements: buildMessageSubscriptionExt("boundaryEvent", options),
2159
2345
  });
2160
2346
  if (element.type === "boundaryEvent") {
2161
2347
  element.attachedToRef = options.attachedTo;
@@ -2188,6 +2374,9 @@ export class ProcessBuilder {
2188
2374
  if (!attachedTo) {
2189
2375
  throw new Error("withBoundary() must follow a task element. Current builder position has no active element.");
2190
2376
  }
2377
+ const hostProblem = boundaryHostProblem(this.flowElements.find((n) => n.id === attachedTo));
2378
+ if (hostProblem !== undefined)
2379
+ throw new Error(hostProblem);
2191
2380
  const savedLast = this.lastNodeId;
2192
2381
  const savedGateway = this.currentGatewayId;
2193
2382
  const savedOpenEnds = [...this.openBranchEnds];
@@ -2263,7 +2452,7 @@ export class ProcessBuilder {
2263
2452
  receiveTask(id, options) {
2264
2453
  const el = makeFlowElement(id, "receiveTask", {
2265
2454
  ...options,
2266
- extensionElements: buildMessageSubscriptionExt(options?.correlationKey),
2455
+ extensionElements: buildMessageSubscriptionExt("receiveTask", options),
2267
2456
  });
2268
2457
  if (options?.isForCompensation)
2269
2458
  el.isForCompensation = true;
@@ -2394,6 +2583,7 @@ export class ProcessBuilder {
2394
2583
  /** Connect the current position to an existing or future element by ID. */
2395
2584
  connectTo(targetId) {
2396
2585
  if (this.lastNodeId) {
2586
+ assertNotAfterEnd(this.flowElements, this.lastNodeId, targetId);
2397
2587
  const flowId = generateId("Flow");
2398
2588
  this.sequenceFlows.push({
2399
2589
  id: flowId,
@@ -2417,6 +2607,7 @@ export class ProcessBuilder {
2417
2607
  if (!found) {
2418
2608
  throw new Error(`Element "${elementId}" not found in process "${this.processId}"`);
2419
2609
  }
2610
+ this.resolvePendingSplice();
2420
2611
  this.lastNodeId = elementId;
2421
2612
  this.currentGatewayId = undefined;
2422
2613
  return this;
@@ -2478,6 +2669,7 @@ export class ProcessBuilder {
2478
2669
  const sub = new SubProcessContentBuilder(this.roots());
2479
2670
  resolved.content(sub);
2480
2671
  finalizeScope(sub._elements, sub._flows);
2672
+ assertEventSubProcessSubscriptions(sub._elements);
2481
2673
  const element = makeFlowElement(id, "subProcess", resolved.options);
2482
2674
  if (element.type === "subProcess") {
2483
2675
  element.triggeredByEvent = true;
@@ -2506,7 +2698,7 @@ export class ProcessBuilder {
2506
2698
  }
2507
2699
  /** Draws a reference to the data object `dataObjectRef`. */
2508
2700
  dataObjectReference(id, dataObjectRef, options) {
2509
- addDataElement(this.flowElements, this.elementIds, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
2701
+ addDataObjectReference(this.flowElements, this.elementIds, id, dataObjectRef, options);
2510
2702
  return this;
2511
2703
  }
2512
2704
  /** Draws a reference to the data store `dataStoreRef`. */
@@ -2568,43 +2760,59 @@ export class ProcessBuilder {
2568
2760
  * says: inference reads the whole topology, and on a document you were handed
2569
2761
  * that means rewriting edges you never touched.
2570
2762
  *
2571
- * @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.
2572
2773
  */
2573
2774
  build(options) {
2775
+ return gateBuild(this.buildModel(options), options);
2776
+ }
2777
+ buildModel(options) {
2574
2778
  this.resolvePendingSplice();
2575
- 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;
2576
2783
  // Continuing a document never infers joins. `insertJoinGateways` reads the
2577
2784
  // whole topology, so on a parsed model it retargets edges the caller never
2578
2785
  // touched — the corpus has a document where a no-op continue would have
2579
2786
  // invented a join gateway and rerouted two flows into it. Building a branch
2580
2787
  // that needs a join here means saying so with `.connectTo(joinId)`.
2581
2788
  if (this._source === undefined)
2582
- insertJoinGateways(this.flowElements, this.sequenceFlows);
2789
+ insertJoinGateways(elements, flows);
2583
2790
  const explicitJoins = options?.explicitJoins ?? false;
2584
- if (explicitJoins && this.flowElements.length > beforeCount) {
2585
- const inserted = this.flowElements
2791
+ if (explicitJoins && elements.length > beforeCount) {
2792
+ const inserted = elements
2586
2793
  .slice(beforeCount)
2587
2794
  .map((e) => e.id)
2588
2795
  .join(", ");
2589
2796
  throw new Error(`Inferred join gateways: ${inserted}. Declare them with .connectTo(joinId), or drop { explicitJoins: true } to keep the inference.`);
2590
2797
  }
2591
- this.validate();
2592
- this.assertSourceTopologyIntact();
2798
+ assertElementIdsUnique(elements, this.processId);
2799
+ this.validate(elements, flows);
2800
+ this.assertSourceTopologyIntact(flows);
2593
2801
  // Flows the document already had keep their ids: continuing a model must
2594
2802
  // not renumber the part the caller did not touch.
2595
- assignStableFlowIds(this.flowElements, this.sequenceFlows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
2596
- assertExplicitFlowIdsUnique(this.flowElements, this.sequenceFlows);
2803
+ assignStableFlowIds(elements, flows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
2804
+ assertExplicitFlowIdsUnique(elements, flows);
2597
2805
  // A continued document keeps its untouched part byte-for-byte, ids included.
2598
2806
  if (this._source === undefined) {
2599
- for (const el of this.flowElements) {
2807
+ for (const el of elements) {
2600
2808
  if ("eventDefinitions" in el)
2601
2809
  assignEventDefinitionIds(el.id, el.eventDefinitions);
2602
2810
  }
2603
2811
  }
2604
- recomputeIncomingOutgoing(this.flowElements, this.sequenceFlows);
2812
+ recomputeIncomingOutgoing(elements, flows);
2605
2813
  if (this._source !== undefined)
2606
- return this.buildOntoSource(this._source);
2607
- const extensionElements = embeddedFormElements(this.flowElements);
2814
+ return this.buildOntoSource(this._source, elements, flows);
2815
+ const extensionElements = embeddedFormElements(elements);
2608
2816
  if (this._versionTag) {
2609
2817
  extensionElements.push({
2610
2818
  name: "zeebe:versionTag",
@@ -2617,10 +2825,10 @@ export class ProcessBuilder {
2617
2825
  name: this.processName,
2618
2826
  isExecutable: this._isExecutable,
2619
2827
  extensionElements,
2620
- flowElements: this.flowElements,
2621
- sequenceFlows: this.sequenceFlows,
2622
- textAnnotations: this._textAnnotations,
2623
- associations: this._associations,
2828
+ flowElements: elements,
2829
+ sequenceFlows: flows,
2830
+ textAnnotations: structuredClone(this._textAnnotations),
2831
+ associations: structuredClone(this._associations),
2624
2832
  groups: [],
2625
2833
  unknownAttributes: {},
2626
2834
  };
@@ -2642,10 +2850,10 @@ export class ProcessBuilder {
2642
2850
  "modeler:executionPlatform": "Camunda Cloud",
2643
2851
  "modeler:executionPlatformVersion": this._executionPlatformVersion,
2644
2852
  },
2645
- errors: this.rootErrors,
2646
- escalations: this.rootEscalations,
2647
- messages: this.rootMessages,
2648
- signals: this.rootSignals,
2853
+ errors: structuredClone(this.rootErrors),
2854
+ escalations: structuredClone(this.rootEscalations),
2855
+ messages: structuredClone(this.rootMessages),
2856
+ signals: structuredClone(this.rootSignals),
2649
2857
  collaborations: [],
2650
2858
  processes: [process],
2651
2859
  // Seed diagram stub so applyAutoLayout preserves process-specific IDs.
@@ -2677,12 +2885,13 @@ export class ProcessBuilder {
2677
2885
  * positions, and elements added here have none until `withAutoLayout()` or a
2678
2886
  * later `applyAutoLayout()` gives them one.
2679
2887
  */
2680
- buildOntoSource(source) {
2681
- const { definitions, process } = source;
2682
- process.flowElements = this.flowElements;
2683
- process.sequenceFlows = this.sequenceFlows;
2684
- process.textAnnotations = this._textAnnotations;
2685
- 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);
2686
2895
  if (this.processName !== undefined)
2687
2896
  process.name = this.processName;
2688
2897
  // Only when asked. BPMN reads an absent `isExecutable` as false, so writing
@@ -2695,17 +2904,17 @@ export class ProcessBuilder {
2695
2904
  // bag: a real process carries other extensions next to it.
2696
2905
  ensureZeebeExtension({ type: "process", extensionElements: process.extensionElements }, "zeebe:versionTag").attributes.value = this._versionTag;
2697
2906
  }
2698
- for (const form of embeddedFormElements(this.flowElements)) {
2907
+ for (const form of embeddedFormElements(elements)) {
2699
2908
  const at = process.extensionElements.findIndex((e) => e.name === form.name && e.attributes.id === form.attributes.id);
2700
2909
  if (at >= 0)
2701
2910
  process.extensionElements[at] = form;
2702
2911
  else
2703
2912
  process.extensionElements.push(form);
2704
2913
  }
2705
- definitions.errors = this.rootErrors;
2706
- definitions.messages = this.rootMessages;
2707
- definitions.signals = this.rootSignals;
2708
- 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);
2709
2918
  return hoistMessageSubscriptions(this._autoLayout
2710
2919
  ? applyAutoLayout(definitions, "semantic", this.rootLayoutHints)
2711
2920
  : definitions);
@@ -2718,12 +2927,12 @@ export class ProcessBuilder {
2718
2927
  * document would come back with edges the caller never touched pointing
2719
2928
  * somewhere else. Continuing a model has to leave the model alone.
2720
2929
  */
2721
- assertSourceTopologyIntact() {
2930
+ assertSourceTopologyIntact(flows) {
2722
2931
  if (this._source === undefined)
2723
2932
  return;
2724
2933
  const rewired = [];
2725
- const byId = new Map(this.sequenceFlows.map((flow) => [flow.id, flow]));
2726
- 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) {
2727
2936
  const flow = byId.get(id);
2728
2937
  if (flow === undefined) {
2729
2938
  rewired.push(`${id} (removed)`);
@@ -2731,24 +2940,31 @@ export class ProcessBuilder {
2731
2940
  }
2732
2941
  // A spliced flow was moved on purpose, but only its source may move:
2733
2942
  // `insertAfter` inserts into a path, it does not redirect one.
2734
- const [, target] = endpoints.split("→");
2735
2943
  if (this._splicedFlowIds.has(id)) {
2736
2944
  if (flow.targetRef !== target) {
2737
2945
  rewired.push(`${id} (spliced flow now targets ${flow.targetRef}, not ${target})`);
2738
2946
  }
2739
2947
  continue;
2740
2948
  }
2741
- const now = `${flow.sourceRef}→${flow.targetRef}`;
2742
- if (now !== endpoints)
2743
- 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
+ }
2744
2952
  }
2745
2953
  if (rewired.length > 0) {
2746
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.`);
2747
2955
  }
2748
2956
  }
2749
- validate() {
2750
- const elementIds = new Set(this.flowElements.map((el) => el.id));
2751
- for (const flow of this.sequenceFlows) {
2957
+ validate(elements, flows) {
2958
+ // A parsed document keeps whatever ids it came with; only new builds are held to the XSD.
2959
+ if (this._source === undefined) {
2960
+ assertXsdValues({
2961
+ id: this.processId,
2962
+ flowElements: elements,
2963
+ sequenceFlows: flows,
2964
+ });
2965
+ }
2966
+ const elementIds = new Set(elements.map((el) => el.id));
2967
+ for (const flow of flows) {
2752
2968
  if (!elementIds.has(flow.targetRef)) {
2753
2969
  throw new Error(`Sequence flow "${flow.id}" in process "${this.processId}" references unknown ` +
2754
2970
  `element "${flow.targetRef}". Check connectTo() calls — target must exist.`);
@@ -2790,6 +3006,7 @@ export class ProcessBuilder {
2790
3006
  return;
2791
3007
  }
2792
3008
  if (this.lastNodeId) {
3009
+ assertNotAfterEnd(this.flowElements, this.lastNodeId, element.id);
2793
3010
  const flowId = generateId("Flow");
2794
3011
  this.sequenceFlows.push({
2795
3012
  id: flowId,
@@ -2830,6 +3047,23 @@ function mergeRootDefinitions(into, incoming) {
2830
3047
  into.push(definition);
2831
3048
  }
2832
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
+ }
2833
3067
  /**
2834
3068
  * Builder for a complete BPMN definitions document containing one or more processes.
2835
3069
  * Use `Bpmn.createDiagram(id?)` to obtain an instance.
@@ -2854,13 +3088,15 @@ export class DiagramBuilder {
2854
3088
  process(id, callback) {
2855
3089
  const builder = new ProcessBuilder(id);
2856
3090
  callback(builder);
2857
- 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 });
2858
3093
  this._processes.push(...defs.processes);
2859
3094
  // Root definitions are named after the message or error code they carry, so
2860
3095
  // two pools declaring the same one produce the same definition twice. The
2861
3096
  // document needs it once.
2862
3097
  mergeRootDefinitions(this._errors, defs.errors);
2863
3098
  mergeRootDefinitions(this._messages, defs.messages);
3099
+ adoptMessageSubscriptions(this._messages, defs.messages);
2864
3100
  return this;
2865
3101
  }
2866
3102
  /** Renames the collaboration element. Defaults to `"Collaboration_1"`. */
@@ -3009,7 +3245,16 @@ export class DiagramBuilder {
3009
3245
  }
3010
3246
  return index;
3011
3247
  }
3012
- 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() {
3013
3258
  return hoistMessageSubscriptions({
3014
3259
  id: this._id,
3015
3260
  targetNamespace: "http://bpmn.io/schema/bpmn",