@bpmnkit/core 1.14.0 → 1.15.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.
@@ -5,6 +5,7 @@ import { camunda8BuilderProblem } from "./builder-rules.js";
5
5
  import { normalizeCamundaVersion } from "./camunda-compat.js";
6
6
  import { createFlowElement, isLoopCapableType } from "./element-shape.js";
7
7
  import { toFeelCondition } from "./feel-condition.js";
8
+ import { levenshtein } from "./optimize/variable-flow.js";
8
9
  import { REST_CONNECTOR_TEMPLATE_VERSION, restConnectorRetries, restConnectorTaskType, restConnectorToIoMappingInputs, restConnectorToTaskHeaders, } from "./rest-connector.js";
9
10
  import { assertExplicitFlowIdsUnique, assignEventDefinitionIds, assignStableFlowIds, copyFlowTags, markExplicitFlowId, rootDefinitionId, setFlowDiscriminatorSource, } from "./stable-ids.js";
10
11
  import { assertRetriesOption, assertXsdValues } from "./xsd-guards.js";
@@ -22,6 +23,21 @@ function addDataElement(elements, ids, element) {
22
23
  elements.push(element);
23
24
  ids.add(element.id);
24
25
  }
26
+ /** Data objects a `dataObjectReference()` declared on its own; a later explicit `dataObject()` adopts them. */
27
+ const implicitDataObjects = new WeakSet();
28
+ function addDataObject(elements, ids, id, options) {
29
+ const implicit = elements.find((e) => e.id === id && implicitDataObjects.has(e));
30
+ if (implicit?.type === "dataObject") {
31
+ implicitDataObjects.delete(implicit);
32
+ const explicit = makeDataElement(id, "dataObject", undefined, options);
33
+ if (explicit.name !== undefined)
34
+ implicit.name = explicit.name;
35
+ if (options?.isCollection)
36
+ implicit.isCollection = true;
37
+ return;
38
+ }
39
+ addDataElement(elements, ids, makeDataElement(id, "dataObject", undefined, options));
40
+ }
25
41
  function makeDataElement(id, type, ref, options) {
26
42
  const el = createFlowElement(id, type, { name: options?.name });
27
43
  if (el.type === "dataObjectReference")
@@ -38,6 +54,13 @@ function makeDataElement(id, type, ref, options) {
38
54
  * this scope) rather than on itself.
39
55
  */
40
56
  function addDataObjectReference(elements, ids, id, dataObjectRef, options) {
57
+ // An unresolved dataObjectRef is a raw XSD IDREF error at build; agents
58
+ // expect the reference to bring its object, so declare it here.
59
+ if (!elements.some((e) => e.id === dataObjectRef && e.type === "dataObject")) {
60
+ const object = makeDataElement(dataObjectRef, "dataObject", undefined, undefined);
61
+ addDataElement(elements, ids, object);
62
+ implicitDataObjects.add(object);
63
+ }
41
64
  addDataElement(elements, ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
42
65
  if (!options?.isCollection)
43
66
  return;
@@ -68,14 +91,17 @@ function addDataAssociation(elements, activityId, dataRefId, direction) {
68
91
  const activity = elements.find((e) => e.id === activityId);
69
92
  if (!activity)
70
93
  throw new Error(`dataAssociation(): no element "${activityId}" in this scope`);
94
+ const key = direction === "input" ? "dataInputAssociations" : "dataOutputAssociations";
95
+ // Ids let auto layout draw the association; without one it has no DI edge.
96
+ const id = `${direction === "input" ? "DataInputAssociation" : "DataOutputAssociation"}_${activityId}_${dataRefId}_${(activity[key]?.length ?? 0) + 1}`;
71
97
  const association = direction === "input"
72
98
  ? {
99
+ id,
73
100
  sourceRefs: [dataRefId],
74
101
  targetRef: targetRefPlaceholder(activity),
75
102
  unknownAttributes: {},
76
103
  }
77
- : { sourceRefs: [], targetRef: dataRefId, unknownAttributes: {} };
78
- const key = direction === "input" ? "dataInputAssociations" : "dataOutputAssociations";
104
+ : { id, sourceRefs: [], targetRef: dataRefId, unknownAttributes: {} };
79
105
  activity[key] = [...(activity[key] ?? []), association];
80
106
  }
81
107
  // ---------------------------------------------------------------------------
@@ -124,6 +150,44 @@ function resolveMessage(messageName, rootMessages) {
124
150
  * cannot hold both, so those stay on their elements, where lint reports them,
125
151
  * rather than one silently winning.
126
152
  */
153
+ function finishDocument(defs) {
154
+ return declareDataStores(hoistMessageSubscriptions(defs));
155
+ }
156
+ /**
157
+ * A `dataStoreReference` points at a root `bpmn:dataStore`; the builder only
158
+ * knows the reference, so the store is declared once per id here, after the
159
+ * model is complete (a store shared by two pools stays one element).
160
+ */
161
+ function declareDataStores(defs) {
162
+ const declared = new Set((defs.unknownChildren ?? [])
163
+ .filter((c) => c.name === "bpmn:dataStore")
164
+ .map((c) => c.attributes.id));
165
+ const stores = [];
166
+ const visit = (elements) => {
167
+ for (const el of elements) {
168
+ if (el.type === "dataStoreReference" && el.dataStoreRef !== undefined) {
169
+ if (!declared.has(el.dataStoreRef)) {
170
+ declared.add(el.dataStoreRef);
171
+ stores.push({
172
+ name: "bpmn:dataStore",
173
+ attributes: {
174
+ id: el.dataStoreRef,
175
+ ...(el.name !== undefined ? { name: el.name } : {}),
176
+ },
177
+ children: [],
178
+ });
179
+ }
180
+ }
181
+ if ("flowElements" in el && Array.isArray(el.flowElements))
182
+ visit(el.flowElements);
183
+ }
184
+ };
185
+ for (const process of defs.processes)
186
+ visit(process.flowElements);
187
+ if (stores.length > 0)
188
+ defs.unknownChildren = [...(defs.unknownChildren ?? []), ...stores];
189
+ return defs;
190
+ }
127
191
  function hoistMessageSubscriptions(defs) {
128
192
  const isSubscription = (el) => el.name === "zeebe:subscription";
129
193
  const owners = new Map();
@@ -295,9 +359,93 @@ const MESSAGE_JOB_TYPES = new Set([
295
359
  "intermediateThrowEvent",
296
360
  "endEvent",
297
361
  ]);
362
+ /** Per-node `lane` option, read when the owning builder adds the element. */
363
+ const laneOverride = new WeakMap();
364
+ /**
365
+ * Lane bookkeeping shared by a process builder and its gateway branches (never by
366
+ * sub-process contents: nodes inside a sub-process are not lane members).
367
+ */
368
+ class LaneState {
369
+ /** Lane id -> name, in first-use order (top to bottom). */
370
+ names = new Map();
371
+ membership = new Map();
372
+ current;
373
+ declare(id, name) {
374
+ if (id === "")
375
+ throw new Error("inLane() needs a non-empty lane id");
376
+ if (!this.names.has(id) || (name !== undefined && this.names.get(id) === undefined)) {
377
+ this.names.set(id, name);
378
+ }
379
+ }
380
+ enter(id, name) {
381
+ this.declare(id, name);
382
+ this.current = id;
383
+ }
384
+ record(el) {
385
+ // A boundary event rides on its host's lane (as bpmn-js lists it); resolved at build.
386
+ if (el.type === "boundaryEvent")
387
+ return;
388
+ const lane = laneOverride.get(el) ?? this.current;
389
+ if (lane === undefined)
390
+ return;
391
+ this.declare(lane);
392
+ this.membership.set(el.id, lane);
393
+ }
394
+ /** Runs `fn`, then puts back the lane that was current before it. */
395
+ scoped(fn) {
396
+ const saved = this.current;
397
+ try {
398
+ fn();
399
+ }
400
+ finally {
401
+ this.current = saved;
402
+ }
403
+ }
404
+ /** The process's lane set, or undefined when no lane was used. */
405
+ toLaneSet(processId, elements, inferredFrom) {
406
+ if (this.names.size === 0)
407
+ return undefined;
408
+ const laneOf = new Map(this.membership);
409
+ // Joins inferred at build() sit on the lane of the split they close.
410
+ for (const el of elements.slice(inferredFrom)) {
411
+ const lane = laneOf.get(el.id.replace(/_(join|merge)(_\d+)?$/, ""));
412
+ if (lane !== undefined)
413
+ laneOf.set(el.id, lane);
414
+ }
415
+ for (const el of elements) {
416
+ if (el.type !== "boundaryEvent" || !el.attachedToRef)
417
+ continue;
418
+ const lane = laneOf.get(el.attachedToRef);
419
+ if (lane !== undefined)
420
+ laneOf.set(el.id, lane);
421
+ }
422
+ // Data objects and stores are flow elements, not flow nodes: no lane holds them.
423
+ const isData = (el) => el.type === "dataObject" ||
424
+ el.type === "dataObjectReference" ||
425
+ el.type === "dataStoreReference";
426
+ const missing = elements.filter((el) => !isData(el) && !laneOf.has(el.id)).map((el) => el.id);
427
+ if (missing.length > 0) {
428
+ throw new Error(`Process "${processId}" uses lanes, so every flow node needs one; no lane for: ${missing.join(", ")}. Call inLane(id) before them or pass { lane } on the node. See agent-cards/bpmn.md#traps.`);
429
+ }
430
+ const lanes = [...this.names].map(([id, name]) => ({
431
+ id,
432
+ name: name ?? id,
433
+ flowNodeRefs: elements.filter((el) => laneOf.get(el.id) === id).map((el) => el.id),
434
+ unknownAttributes: {},
435
+ }));
436
+ return { id: `${processId}_laneSet`, lanes };
437
+ }
438
+ }
298
439
  function makeFlowElement(id, type, options) {
299
440
  const el = createFlowElement(id, type, options);
441
+ if (options?.lane !== undefined)
442
+ laneOverride.set(el, options.lane);
300
443
  el.extensionElements = [...el.extensionElements];
444
+ if (options?.messageName &&
445
+ options.correlationKey &&
446
+ (type === "endEvent" || type === "intermediateThrowEvent")) {
447
+ el.extensionElements.push(...zeebeExtensionsToXmlElements({ subscription: { correlationKey: options.correlationKey } }));
448
+ }
301
449
  if (options?.taskType !== undefined && MESSAGE_JOB_TYPES.has(type)) {
302
450
  el.extensionElements.push(...zeebeExtensionsToXmlElements({ taskDefinition: { type: options.taskType } }));
303
451
  }
@@ -601,6 +749,7 @@ function makeServiceTaskEl(id, options) {
601
749
  unknownAttributes["zeebe:modelerTemplateIcon"] = options.modelerTemplateIcon;
602
750
  const el = makeFlowElement(id, "serviceTask", {
603
751
  name: options.name,
752
+ lane: options.lane,
604
753
  documentation: options.documentation,
605
754
  extensionElements: buildServiceTaskExtensions(options),
606
755
  executionListeners: options.executionListeners,
@@ -615,6 +764,7 @@ function makeServiceTaskEl(id, options) {
615
764
  function makeScriptTaskEl(id, options) {
616
765
  const el = makeFlowElement(id, "scriptTask", {
617
766
  name: options.name,
767
+ lane: options.lane,
618
768
  documentation: options.documentation,
619
769
  executionListeners: options.executionListeners,
620
770
  extensionElements: zeebeExtensionsToXmlElements({
@@ -641,10 +791,15 @@ function applyModelerTemplate(el, options) {
641
791
  el.unknownAttributes["zeebe:modelerTemplateIcon"] = options.modelerTemplateIcon;
642
792
  }
643
793
  }
794
+ /** Only decision gateways give their branches a flow label; a parallel or event-based split's flows are unconditioned. */
795
+ function branchesAreNamed(gateway) {
796
+ return gateway?.type !== "parallelGateway" && gateway?.type !== "eventBasedGateway";
797
+ }
644
798
  /** Start-event shell shared by all three builders; the caller adds event definitions. */
645
799
  function makeStartEventEl(id, options) {
646
800
  const el = makeFlowElement(id, "startEvent", {
647
801
  name: options?.name,
802
+ lane: options?.lane,
648
803
  documentation: options?.documentation,
649
804
  executionListeners: options?.executionListeners,
650
805
  extensionElements: zeebeExtensionsToXmlElements({
@@ -707,6 +862,7 @@ function makeUserTaskEl(id, options) {
707
862
  });
708
863
  const el = makeFlowElement(id, "userTask", {
709
864
  name: options?.name,
865
+ lane: options?.lane,
710
866
  documentation: options?.documentation,
711
867
  executionListeners: options?.executionListeners,
712
868
  taskListeners: options?.taskListeners,
@@ -761,6 +917,7 @@ function makeBusinessRuleTaskEl(id, options) {
761
917
  }
762
918
  const el = makeFlowElement(id, "businessRuleTask", {
763
919
  name: options?.name,
920
+ lane: options?.lane,
764
921
  documentation: options?.documentation,
765
922
  executionListeners: options?.executionListeners,
766
923
  extensionElements: ext,
@@ -788,6 +945,7 @@ function makeCallActivityEl(id, options) {
788
945
  };
789
946
  const el = makeFlowElement(id, "callActivity", {
790
947
  name: options.name,
948
+ lane: options.lane,
791
949
  documentation: options.documentation,
792
950
  executionListeners: options.executionListeners,
793
951
  extensionElements: zeebeExtensionsToXmlElements(extensions),
@@ -980,6 +1138,81 @@ function insertJoinGateways(elements, flows) {
980
1138
  }
981
1139
  }
982
1140
  }
1141
+ /**
1142
+ * Puts an exclusive merge gateway (`<target>_merge`) in front of every
1143
+ * non-gateway node that still has several incoming flows once join inference
1144
+ * has run — typically a `connectTo()` looping back to a task, or a boundary
1145
+ * path rejoining the main flow. Several flows into a task already mean "each
1146
+ * arriving token starts it", which is exactly what an exclusive merge does, so
1147
+ * this changes how the diagram reads (and lints), not how it runs.
1148
+ *
1149
+ * `sourceFlows` holds the flows of a document being continued: they must keep
1150
+ * their id and target, so at most one of them may enter the node, and that one
1151
+ * becomes `merge → node` (only its source moves, as with `insertAfter`) while a
1152
+ * new flow takes its old source into the merge. Nodes with two or more of them
1153
+ * were already like that in the document and are left alone. The ids of flows
1154
+ * whose source moved are returned so the rewiring guard can allow it.
1155
+ */
1156
+ function insertMergeGateways(elements, flows, sourceFlows) {
1157
+ const moved = new Set();
1158
+ const taken = new Set(elements.map((el) => el.id));
1159
+ const incoming = new Map();
1160
+ for (const flow of flows) {
1161
+ const arr = incoming.get(flow.targetRef);
1162
+ if (arr)
1163
+ arr.push(flow);
1164
+ else
1165
+ incoming.set(flow.targetRef, [flow]);
1166
+ }
1167
+ for (const el of [...elements]) {
1168
+ if (isGatewayType(el.type) || el.type === "startEvent")
1169
+ continue;
1170
+ const inFlows = incoming.get(el.id) ?? [];
1171
+ if (inFlows.length < 2)
1172
+ continue;
1173
+ const kept = inFlows.filter((flow) => sourceFlows?.has(flow.id));
1174
+ if (kept.length > 1)
1175
+ continue;
1176
+ // A kept flow carrying a gateway's condition (or being its default) cannot
1177
+ // have its source moved without moving the decision; leave that node as is.
1178
+ const fixed = kept[0];
1179
+ if (fixed !== undefined &&
1180
+ (fixed.conditionExpression !== undefined ||
1181
+ elements.some((e) => "default" in e && e.default === fixed.id))) {
1182
+ continue;
1183
+ }
1184
+ let mergeId = `${el.id}_merge`;
1185
+ for (let n = 2; taken.has(mergeId); n++)
1186
+ mergeId = `${el.id}_merge_${n}`;
1187
+ taken.add(mergeId);
1188
+ elements.push(makeFlowElement(mergeId, "exclusiveGateway", {}));
1189
+ const anchor = kept[0];
1190
+ for (const flow of inFlows) {
1191
+ if (flow !== anchor)
1192
+ flow.targetRef = mergeId;
1193
+ }
1194
+ if (anchor === undefined) {
1195
+ flows.push({
1196
+ id: generateId("Flow"),
1197
+ sourceRef: mergeId,
1198
+ targetRef: el.id,
1199
+ extensionElements: [],
1200
+ unknownAttributes: {},
1201
+ });
1202
+ continue;
1203
+ }
1204
+ flows.push({
1205
+ id: generateId("Flow"),
1206
+ sourceRef: anchor.sourceRef,
1207
+ targetRef: mergeId,
1208
+ extensionElements: [],
1209
+ unknownAttributes: {},
1210
+ });
1211
+ anchor.sourceRef = mergeId;
1212
+ moved.add(anchor.id);
1213
+ }
1214
+ return moved;
1215
+ }
983
1216
  /**
984
1217
  * Settles a finished scope: infer the joins its branches imply, name its
985
1218
  * sequence flows after what they connect, then rebuild the `incoming`/
@@ -992,6 +1225,7 @@ function finalizeScope(elements, flows) {
992
1225
  assignEventDefinitionIds(el.id, el.eventDefinitions);
993
1226
  }
994
1227
  insertJoinGateways(elements, flows);
1228
+ insertMergeGateways(elements, flows);
995
1229
  assignStableFlowIds(elements, flows);
996
1230
  recomputeIncomingOutgoing(elements, flows);
997
1231
  }
@@ -1023,6 +1257,15 @@ function traceBackToSplit(nodeId, splitGateways, flows) {
1023
1257
  * Use `.condition(expr)` to set a FEEL condition on the outgoing sequence
1024
1258
  * flow from the gateway, or `.defaultFlow()` to mark it as the default path.
1025
1259
  */
1260
+ /**
1261
+ * A branch that adds nothing and connects nowhere leaves an unconditioned flow from
1262
+ * the gateway to whatever comes next, which is never what the author meant.
1263
+ */
1264
+ function assertBranchAddedSomething(b, name, gatewayId) {
1265
+ if (b._elements.length > 0 || b._connected)
1266
+ return;
1267
+ throw new Error(`branch("${name}") on gateway "${gatewayId}" added no elements: add a node, end it with .endEvent(id), or route it with .connectTo(id)`);
1268
+ }
1026
1269
  export class BranchBuilder {
1027
1270
  /** @internal */
1028
1271
  _elements = [];
@@ -1035,6 +1278,8 @@ export class BranchBuilder {
1035
1278
  lastNodeId;
1036
1279
  gatewayId;
1037
1280
  branchName;
1281
+ /** False after a parallel or event-based gateway, whose outgoing flows Camunda lints as `superfluous-label` when named. */
1282
+ nameFlow;
1038
1283
  isFirstElement = true;
1039
1284
  pendingCondition;
1040
1285
  pendingLabel;
@@ -1056,10 +1301,14 @@ export class BranchBuilder {
1056
1301
  rootSignals;
1057
1302
  rootEscalations;
1058
1303
  rootLayoutHints;
1304
+ /** Absent inside a sub-process, whose nodes are not lane members. */
1305
+ lanes;
1059
1306
  /** @internal */
1060
- constructor(gatewayId, branchName, rootErrors = [], rootMessages = [], rootSignals = [], rootEscalations = [], rootLayoutHints = emptyLayoutHints()) {
1307
+ constructor(gatewayId, branchName, rootErrors = [], rootMessages = [], rootSignals = [], rootEscalations = [], rootLayoutHints = emptyLayoutHints(), lanes, nameFlow = true) {
1308
+ this.lanes = lanes;
1061
1309
  this.gatewayId = gatewayId;
1062
1310
  this.branchName = branchName;
1311
+ this.nameFlow = nameFlow;
1063
1312
  this.lastNodeId = gatewayId;
1064
1313
  this.rootErrors = rootErrors;
1065
1314
  this.rootMessages = rootMessages;
@@ -1105,9 +1354,17 @@ export class BranchBuilder {
1105
1354
  if (this.pendingFlowId !== undefined)
1106
1355
  markExplicitFlowId(flow);
1107
1356
  }
1357
+ /** Moves the rest of this branch (and branches nested in it) to a lane; undone when the branch ends. */
1358
+ inLane(id, options) {
1359
+ if (!this.lanes)
1360
+ throw new Error("inLane() is not available inside a sub-process.");
1361
+ this.lanes.enter(id, options?.name);
1362
+ return this;
1363
+ }
1108
1364
  addElement(element) {
1109
1365
  this._elements.push(element);
1110
1366
  this._ids.add(element.id);
1367
+ this.lanes?.record(element);
1111
1368
  if (isLinkEvent(element, "intermediateCatchEvent")) {
1112
1369
  this.isFirstElement = false;
1113
1370
  this.lastNodeId = element.id;
@@ -1122,7 +1379,9 @@ export class BranchBuilder {
1122
1379
  id: flowId,
1123
1380
  sourceRef: this.lastNodeId,
1124
1381
  targetRef: element.id,
1125
- name: this.isFirstElement ? (this.pendingLabel ?? this.branchName) : undefined,
1382
+ name: this.isFirstElement
1383
+ ? (this.pendingLabel ?? (this.nameFlow ? this.branchName : undefined))
1384
+ : undefined,
1126
1385
  conditionExpression: this.isFirstElement && this.pendingCondition
1127
1386
  ? makeConditionExpression(this.pendingCondition)
1128
1387
  : undefined,
@@ -1179,7 +1438,9 @@ export class BranchBuilder {
1179
1438
  id: flowId,
1180
1439
  sourceRef: this.lastNodeId,
1181
1440
  targetRef: targetId,
1182
- name: this.isFirstElement ? (this.pendingLabel ?? this.branchName) : undefined,
1441
+ name: this.isFirstElement
1442
+ ? (this.pendingLabel ?? (this.nameFlow ? this.branchName : undefined))
1443
+ : undefined,
1183
1444
  conditionExpression: this.isFirstElement && this.pendingCondition
1184
1445
  ? makeConditionExpression(this.pendingCondition)
1185
1446
  : undefined,
@@ -1208,7 +1469,7 @@ export class BranchBuilder {
1208
1469
  // ---- Data elements (beside the chain; no sequence flows) ----
1209
1470
  /** Declares a data object. Link it to an activity via a `dataObjectReference()`. */
1210
1471
  dataObject(id, options) {
1211
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObject", undefined, options));
1472
+ addDataObject(this._elements, this._ids, id, options);
1212
1473
  return this;
1213
1474
  }
1214
1475
  /** Draws a reference to the data object `dataObjectRef`. */
@@ -1452,6 +1713,7 @@ export class BranchBuilder {
1452
1713
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1453
1714
  const element = makeFlowElement(id, "adHocSubProcess", {
1454
1715
  name: resolved.options?.name,
1716
+ lane: resolved.options?.lane,
1455
1717
  documentation: resolved.options?.documentation,
1456
1718
  executionListeners: resolved.options?.executionListeners,
1457
1719
  extensionElements,
@@ -1494,8 +1756,13 @@ export class BranchBuilder {
1494
1756
  if (!this.currentGatewayId) {
1495
1757
  throw new Error("branch() must be called after a gateway element");
1496
1758
  }
1497
- const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints);
1498
- callback(b);
1759
+ const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints, this.lanes, branchesAreNamed(this._elements.find((n) => n.id === this.currentGatewayId)));
1760
+ // Inside a sub-process there is no lane state, but the callback must still run.
1761
+ if (this.lanes)
1762
+ this.lanes.scoped(() => callback(b));
1763
+ else
1764
+ callback(b);
1765
+ assertBranchAddedSomething(b, name, this.currentGatewayId);
1499
1766
  for (const el of b._elements) {
1500
1767
  if (this._ids.has(el.id)) {
1501
1768
  throw new Error(`Duplicate element ID "${el.id}"`);
@@ -1744,7 +2011,7 @@ export class SubProcessContentBuilder {
1744
2011
  // ---- Data elements (beside the chain; no sequence flows) ----
1745
2012
  /** Declares a data object. Link it to an activity via a `dataObjectReference()`. */
1746
2013
  dataObject(id, options) {
1747
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObject", undefined, options));
2014
+ addDataObject(this._elements, this._ids, id, options);
1748
2015
  return this;
1749
2016
  }
1750
2017
  /** Draws a reference to the data object `dataObjectRef`. */
@@ -1792,8 +2059,9 @@ export class SubProcessContentBuilder {
1792
2059
  if (!this.currentGatewayId) {
1793
2060
  throw new Error("branch() must be called after a gateway element");
1794
2061
  }
1795
- const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints);
2062
+ const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints, undefined, branchesAreNamed(this._elements.find((n) => n.id === this.currentGatewayId)));
1796
2063
  callback(b);
2064
+ assertBranchAddedSomething(b, name, this.currentGatewayId);
1797
2065
  for (const el of b._elements) {
1798
2066
  if (this._ids.has(el.id)) {
1799
2067
  throw new Error(`Duplicate element ID "${el.id}"`);
@@ -1947,6 +2215,7 @@ export class SubProcessContentBuilder {
1947
2215
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1948
2216
  const element = makeFlowElement(id, "adHocSubProcess", {
1949
2217
  name: resolved.options?.name,
2218
+ lane: resolved.options?.lane,
1950
2219
  documentation: resolved.options?.documentation,
1951
2220
  executionListeners: resolved.options?.executionListeners,
1952
2221
  extensionElements,
@@ -2017,6 +2286,7 @@ export class ProcessBuilder {
2017
2286
  _pendingSpliceFlowId;
2018
2287
  /** Flows the caller deliberately spliced, exempt from the rewiring guard. */
2019
2288
  _splicedFlowIds = new Set();
2289
+ lanes = new LaneState();
2020
2290
  constructor(processId) {
2021
2291
  this.processId = processId;
2022
2292
  }
@@ -2540,8 +2810,9 @@ export class ProcessBuilder {
2540
2810
  if (!this.currentGatewayId) {
2541
2811
  throw new Error("branch() must be called after a gateway element");
2542
2812
  }
2543
- const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints);
2544
- callback(b);
2813
+ const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints, this.lanes, branchesAreNamed(this.flowElements.find((n) => n.id === this.currentGatewayId)));
2814
+ this.lanes.scoped(() => callback(b));
2815
+ assertBranchAddedSomething(b, name, this.currentGatewayId);
2545
2816
  for (const el of b._elements) {
2546
2817
  if (this.elementIds.has(el.id)) {
2547
2818
  throw new Error(`Duplicate element ID "${el.id}"`);
@@ -2631,6 +2902,7 @@ export class ProcessBuilder {
2631
2902
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
2632
2903
  const element = makeFlowElement(id, "adHocSubProcess", {
2633
2904
  name: resolved.options?.name,
2905
+ lane: resolved.options?.lane,
2634
2906
  documentation: resolved.options?.documentation,
2635
2907
  executionListeners: resolved.options?.executionListeners,
2636
2908
  extensionElements,
@@ -2693,7 +2965,7 @@ export class ProcessBuilder {
2693
2965
  // ---- Data elements (beside the chain; no sequence flows) ----
2694
2966
  /** Declares a data object. Link it to an activity via a `dataObjectReference()`. */
2695
2967
  dataObject(id, options) {
2696
- addDataElement(this.flowElements, this.elementIds, makeDataElement(id, "dataObject", undefined, options));
2968
+ addDataObject(this.flowElements, this.elementIds, id, options);
2697
2969
  return this;
2698
2970
  }
2699
2971
  /** Draws a reference to the data object `dataObjectRef`. */
@@ -2795,23 +3067,32 @@ export class ProcessBuilder {
2795
3067
  .join(", ");
2796
3068
  throw new Error(`Inferred join gateways: ${inserted}. Declare them with .connectTo(joinId), or drop { explicitJoins: true } to keep the inference.`);
2797
3069
  }
3070
+ const sourceFlowIds = this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys());
3071
+ const movedFlowIds = insertMergeGateways(elements, flows, sourceFlowIds);
2798
3072
  assertElementIdsUnique(elements, this.processId);
2799
3073
  this.validate(elements, flows);
2800
- this.assertSourceTopologyIntact(flows);
3074
+ this.assertSourceTopologyIntact(flows, movedFlowIds);
2801
3075
  // Flows the document already had keep their ids: continuing a model must
2802
3076
  // not renumber the part the caller did not touch.
2803
- assignStableFlowIds(elements, flows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
3077
+ assignStableFlowIds(elements, flows, sourceFlowIds);
2804
3078
  assertExplicitFlowIdsUnique(elements, flows);
2805
- // A continued document keeps its untouched part byte-for-byte, ids included.
2806
- if (this._source === undefined) {
2807
- for (const el of elements) {
2808
- if ("eventDefinitions" in el)
2809
- assignEventDefinitionIds(el.id, el.eventDefinitions);
2810
- }
3079
+ // A continued document keeps its untouched part byte-for-byte, ids included,
3080
+ // so only the elements this builder added get event definition ids there.
3081
+ const sourceElementIds = new Set(this._source?.process.flowElements.map((el) => el.id));
3082
+ for (const el of elements) {
3083
+ if (sourceElementIds.has(el.id))
3084
+ continue;
3085
+ if ("eventDefinitions" in el)
3086
+ assignEventDefinitionIds(el.id, el.eventDefinitions);
2811
3087
  }
2812
3088
  recomputeIncomingOutgoing(elements, flows);
2813
- if (this._source !== undefined)
3089
+ if (this._source !== undefined) {
3090
+ if (this.lanes.names.size > 0) {
3091
+ throw new Error("inLane() and { lane } build new lanes; they cannot be combined with ProcessBuilder.from(), which keeps the document's own lanes.");
3092
+ }
2814
3093
  return this.buildOntoSource(this._source, elements, flows);
3094
+ }
3095
+ const laneSet = this.lanes.toLaneSet(this.processId, elements, beforeCount);
2815
3096
  const extensionElements = embeddedFormElements(elements);
2816
3097
  if (this._versionTag) {
2817
3098
  extensionElements.push({
@@ -2832,6 +3113,8 @@ export class ProcessBuilder {
2832
3113
  groups: [],
2833
3114
  unknownAttributes: {},
2834
3115
  };
3116
+ if (laneSet)
3117
+ process.laneSet = laneSet;
2835
3118
  const defs = {
2836
3119
  id: "Definitions_1",
2837
3120
  targetNamespace: "http://bpmn.io/schema/bpmn",
@@ -2871,7 +3154,7 @@ export class ProcessBuilder {
2871
3154
  ]
2872
3155
  : [],
2873
3156
  };
2874
- return hoistMessageSubscriptions(this._autoLayout ? applyAutoLayout(defs, "semantic", this.rootLayoutHints) : defs);
3157
+ return finishDocument(this._autoLayout ? applyAutoLayout(defs, "semantic", this.rootLayoutHints) : defs);
2875
3158
  }
2876
3159
  /**
2877
3160
  * Writes this process's contents back into the document it came from.
@@ -2928,7 +3211,7 @@ export class ProcessBuilder {
2928
3211
  * document would come back with edges the caller never touched pointing
2929
3212
  * somewhere else. Continuing a model has to leave the model alone.
2930
3213
  */
2931
- assertSourceTopologyIntact(flows) {
3214
+ assertSourceTopologyIntact(flows, mergedFlowIds) {
2932
3215
  if (this._source === undefined)
2933
3216
  return;
2934
3217
  const rewired = [];
@@ -2941,7 +3224,7 @@ export class ProcessBuilder {
2941
3224
  }
2942
3225
  // A spliced flow was moved on purpose, but only its source may move:
2943
3226
  // `insertAfter` inserts into a path, it does not redirect one.
2944
- if (this._splicedFlowIds.has(id)) {
3227
+ if (this._splicedFlowIds.has(id) || mergedFlowIds.has(id)) {
2945
3228
  if (flow.targetRef !== target) {
2946
3229
  rewired.push(`${id} (spliced flow now targets ${flow.targetRef}, not ${target})`);
2947
3230
  }
@@ -2976,10 +3259,27 @@ export class ProcessBuilder {
2976
3259
  }
2977
3260
  }
2978
3261
  }
3262
+ /**
3263
+ * Puts the nodes that follow in lane `id`, declaring it on first use (top to
3264
+ * bottom in first-use order); a later call may name it. Inside a `branch()`
3265
+ * callback it changes the lane for that branch only. Once any lane is used,
3266
+ * every top-level flow node needs one, or `build()` throws.
3267
+ *
3268
+ * @example
3269
+ * ```ts
3270
+ * Bpmn.createProcess("p").inLane("sales", { name: "Sales" }).startEvent("s")
3271
+ * .inLane("ops").serviceTask("t", { taskType: "x" }).endEvent("e").build()
3272
+ * ```
3273
+ */
3274
+ inLane(id, options) {
3275
+ this.lanes.enter(id, options?.name);
3276
+ return this;
3277
+ }
2979
3278
  addFlowElement(element) {
2980
3279
  if (this.elementIds.has(element.id)) {
2981
3280
  throw new Error(`Duplicate element ID "${element.id}" in process "${this.processId}"`);
2982
3281
  }
3282
+ this.lanes.record(element);
2983
3283
  this.flowElements.push(element);
2984
3284
  this.elementIds.add(element.id);
2985
3285
  // Compensation handlers are outside the normal token flow: link via association
@@ -3048,6 +3348,22 @@ function mergeRootDefinitions(into, incoming) {
3048
3348
  into.push(definition);
3049
3349
  }
3050
3350
  }
3351
+ function remapMessageRefs(elements, to) {
3352
+ for (const el of elements) {
3353
+ if ("messageRef" in el && typeof el.messageRef === "string") {
3354
+ el.messageRef = to.get(el.messageRef) ?? el.messageRef;
3355
+ }
3356
+ if ("eventDefinitions" in el) {
3357
+ for (const d of el.eventDefinitions) {
3358
+ if (d.type === "message" && d.messageRef !== undefined) {
3359
+ d.messageRef = to.get(d.messageRef) ?? d.messageRef;
3360
+ }
3361
+ }
3362
+ }
3363
+ if ("flowElements" in el && Array.isArray(el.flowElements))
3364
+ remapMessageRefs(el.flowElements, to);
3365
+ }
3366
+ }
3051
3367
  /**
3052
3368
  * A message two pools share keeps the correlation key a later pool hoisted onto
3053
3369
  * its copy when the first copy has none; dropping it would leave that pool's
@@ -3069,6 +3385,18 @@ function adoptMessageSubscriptions(into, incoming) {
3069
3385
  * Builder for a complete BPMN definitions document containing one or more processes.
3070
3386
  * Use `Bpmn.createDiagram(id?)` to obtain an instance.
3071
3387
  */
3388
+ /** A "did you mean" suffix naming up to three existing ids close to `ref`. */
3389
+ function closeIds(ref, existing) {
3390
+ const lower = ref.toLowerCase();
3391
+ const close = existing
3392
+ .filter((id) => id.length >= 3)
3393
+ .map((id) => ({ id, d: levenshtein(lower, id.toLowerCase()) }))
3394
+ .filter(({ id, d }) => d <= Math.max(2, Math.floor(ref.length / 3)) || id.includes(ref) || ref.includes(id))
3395
+ .sort((a, b) => a.d - b.d)
3396
+ .slice(0, 3)
3397
+ .map(({ id }) => `"${id}"`);
3398
+ return close.length > 0 ? `; did you mean ${close.join(", ")}?` : "";
3399
+ }
3072
3400
  export class DiagramBuilder {
3073
3401
  _id;
3074
3402
  _processes = [];
@@ -3096,6 +3424,23 @@ export class DiagramBuilder {
3096
3424
  // two pools declaring the same one produce the same definition twice. The
3097
3425
  // document needs it once.
3098
3426
  mergeRootDefinitions(this._errors, defs.errors);
3427
+ const remap = new Map();
3428
+ for (const incoming of defs.messages) {
3429
+ const declared = this._messages.find((m) => m.id !== incoming.id && m.name !== undefined && m.name === incoming.name);
3430
+ if (!declared)
3431
+ continue;
3432
+ remap.set(incoming.id, declared.id);
3433
+ // message() ran first under another id: point this pool at that message.
3434
+ const sub = incoming.extensionElements?.find((x) => x.name === "zeebe:subscription");
3435
+ if (sub && !declared.extensionElements?.some((x) => x.name === "zeebe:subscription")) {
3436
+ declared.extensionElements = [...(declared.extensionElements ?? []), sub];
3437
+ }
3438
+ }
3439
+ if (remap.size > 0) {
3440
+ for (const process of defs.processes)
3441
+ remapMessageRefs(process.flowElements, remap);
3442
+ defs.messages = defs.messages.filter((m) => !remap.has(m.id));
3443
+ }
3099
3444
  mergeRootDefinitions(this._messages, defs.messages);
3100
3445
  adoptMessageSubscriptions(this._messages, defs.messages);
3101
3446
  return this;
@@ -3134,12 +3479,36 @@ export class DiagramBuilder {
3134
3479
  * @param id - The message's element id, used verbatim.
3135
3480
  */
3136
3481
  message(id, options = {}) {
3137
- const message = { id, unknownAttributes: {} };
3138
- if (options.name !== undefined)
3139
- message.name = options.name;
3482
+ const keepOthers = (x) => x.name !== "zeebe:subscription";
3140
3483
  const extensions = zeebeExtensionsToXmlElements(options.correlationKey === undefined
3141
3484
  ? {}
3142
3485
  : { subscription: { correlationKey: options.correlationKey } });
3486
+ // A process that already named the message created it as Message_<name>; a
3487
+ // second definition with that id or name would be a duplicate in the XML.
3488
+ const existing = this._messages.find((m) => m.id === id) ??
3489
+ (options.name === undefined ? undefined : this._messages.find((m) => m.name === options.name));
3490
+ if (existing) {
3491
+ if (existing.id !== id) {
3492
+ // The declared id wins, as it does when message() runs first: message
3493
+ // flows name it, so the pools built so far are re-pointed at it.
3494
+ const renamed = new Map([[existing.id, id]]);
3495
+ for (const process of this._processes)
3496
+ remapMessageRefs(process.flowElements, renamed);
3497
+ existing.id = id;
3498
+ }
3499
+ if (options.name !== undefined)
3500
+ existing.name = options.name;
3501
+ if (extensions.length > 0) {
3502
+ existing.extensionElements = [
3503
+ ...(existing.extensionElements ?? []).filter(keepOthers),
3504
+ ...extensions,
3505
+ ];
3506
+ }
3507
+ return this;
3508
+ }
3509
+ const message = { id, unknownAttributes: {} };
3510
+ if (options.name !== undefined)
3511
+ message.name = options.name;
3143
3512
  if (extensions.length > 0)
3144
3513
  message.extensionElements = extensions;
3145
3514
  this._messages.push(message);
@@ -3184,6 +3553,35 @@ export class DiagramBuilder {
3184
3553
  problems.push(`Duplicate element ID "${id}"`);
3185
3554
  seen.add(id);
3186
3555
  }
3556
+ // Ids are global in a collaboration, so the same id in two pools is a
3557
+ // raw XSD error otherwise; name both pools and the fix.
3558
+ const idOwner = new Map();
3559
+ const claimId = (id, processId) => {
3560
+ const first = idOwner.get(id);
3561
+ if (first === undefined)
3562
+ idOwner.set(id, processId);
3563
+ else if (first !== processId) {
3564
+ problems.push(`Duplicate element ID "${id}" in processes "${first}" and "${processId}": ids are global in a collaboration; prefix them per pool (e.g. "${processId}_${id}")`);
3565
+ }
3566
+ };
3567
+ const claimScope = (scope, processId) => {
3568
+ for (const element of scope) {
3569
+ claimId(element.id, processId);
3570
+ if ("flowElements" in element && Array.isArray(element.flowElements)) {
3571
+ claimScope(element.flowElements, processId);
3572
+ }
3573
+ for (const flow of "sequenceFlows" in element && Array.isArray(element.sequenceFlows)
3574
+ ? element.sequenceFlows
3575
+ : []) {
3576
+ claimId(flow.id, processId);
3577
+ }
3578
+ }
3579
+ };
3580
+ for (const process of this._processes) {
3581
+ claimScope(process.flowElements, process.id);
3582
+ for (const flow of process.sequenceFlows)
3583
+ claimId(flow.id, process.id);
3584
+ }
3187
3585
  const processIds = new Set(this._processes.map((process) => process.id));
3188
3586
  const claimed = new Map();
3189
3587
  for (const participant of this._participants) {
@@ -3208,7 +3606,7 @@ export class DiagramBuilder {
3208
3606
  ["target", flow.targetRef],
3209
3607
  ]) {
3210
3608
  if (!owningParticipant.has(ref)) {
3211
- problems.push(`Message flow "${flow.id}" names ${role} "${ref}", which is not a participant or a flow node in one`);
3609
+ problems.push(`Message flow "${flow.id}" names ${role} "${ref}", which is not a participant or a flow node in one${closeIds(ref, [...owningParticipant.keys()])}`);
3212
3610
  }
3213
3611
  }
3214
3612
  const from = owningParticipant.get(flow.sourceRef);
@@ -3256,7 +3654,7 @@ export class DiagramBuilder {
3256
3654
  return gateBuild(this.buildModel(), options);
3257
3655
  }
3258
3656
  buildModel() {
3259
- return hoistMessageSubscriptions({
3657
+ return finishDocument({
3260
3658
  id: this._id,
3261
3659
  targetNamespace: "http://bpmn.io/schema/bpmn",
3262
3660
  exporter: "@bpmnkit/core",