@bpmnkit/core 1.15.0 → 1.17.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 (60) hide show
  1. package/builder-reference.md +2 -1
  2. package/dist/bpmn/auto-layout.d.ts +0 -8
  3. package/dist/bpmn/auto-layout.js +605 -98
  4. package/dist/bpmn/bpmn-builder.d.ts +120 -14
  5. package/dist/bpmn/bpmn-builder.js +411 -152
  6. package/dist/bpmn/bpmn-model.d.ts +15 -0
  7. package/dist/bpmn/bpmn-parser.js +32 -6
  8. package/dist/bpmn/bpmn-serializer.js +9 -2
  9. package/dist/bpmn/compact-stream.d.ts +7 -0
  10. package/dist/bpmn/compact-stream.js +7 -0
  11. package/dist/bpmn/compact.d.ts +124 -9
  12. package/dist/bpmn/compact.js +295 -27
  13. package/dist/bpmn/full-operations.d.ts +19 -0
  14. package/dist/bpmn/full-operations.js +191 -7
  15. package/dist/bpmn/make-room.js +114 -0
  16. package/dist/bpmn/place-new-shapes.js +4 -2
  17. package/dist/bpmn/preserving-writer.d.ts +1 -1
  18. package/dist/bpmn/preserving-writer.js +1 -1
  19. package/dist/bpmn/process-delta.d.ts +32 -1
  20. package/dist/bpmn/process-delta.js +62 -1
  21. package/dist/bpmn/process-text-writer.d.ts +18 -7
  22. package/dist/bpmn/process-text-writer.js +105 -22
  23. package/dist/bpmn/process-text.d.ts +27 -1
  24. package/dist/bpmn/process-text.js +350 -2
  25. package/dist/bpmn/swimlanes.d.ts +178 -0
  26. package/dist/bpmn/swimlanes.js +774 -0
  27. package/dist/index.d.ts +5 -4
  28. package/dist/index.js +3 -2
  29. package/dist/layout/collaboration/crossings.d.ts +13 -0
  30. package/dist/layout/collaboration/crossings.js +37 -0
  31. package/dist/layout/collaboration/docked-labels.d.ts +21 -0
  32. package/dist/layout/collaboration/docked-labels.js +65 -0
  33. package/dist/layout/collaboration/message-tracks.d.ts +20 -0
  34. package/dist/layout/collaboration/message-tracks.js +78 -0
  35. package/dist/layout/collaboration/stack-crossings.d.ts +38 -0
  36. package/dist/layout/collaboration/stack-crossings.js +155 -0
  37. package/dist/layout/grid/edge-labels.js +21 -10
  38. package/dist/layout/layered/coords.d.ts +13 -0
  39. package/dist/layout/layered/coords.js +211 -0
  40. package/dist/layout/layered/index.d.ts +21 -0
  41. package/dist/layout/layered/index.js +288 -0
  42. package/dist/layout/layered/layers.d.ts +60 -0
  43. package/dist/layout/layered/layers.js +374 -0
  44. package/dist/layout/layered/route.d.ts +66 -0
  45. package/dist/layout/layered/route.js +369 -0
  46. package/dist/layout/layout-engine.d.ts +6 -2
  47. package/dist/layout/layout-engine.js +4 -2
  48. package/dist/layout/semantic/bands.js +8 -2
  49. package/dist/layout/semantic/graph.d.ts +33 -1
  50. package/dist/layout/semantic/graph.js +200 -4
  51. package/dist/layout/semantic/index.d.ts +8 -2
  52. package/dist/layout/semantic/index.js +114 -14
  53. package/dist/layout/semantic/lanes.d.ts +40 -0
  54. package/dist/layout/semantic/lanes.js +198 -0
  55. package/dist/layout/semantic/place.d.ts +46 -2
  56. package/dist/layout/semantic/place.js +248 -30
  57. package/dist/layout/semantic/route.js +35 -2
  58. package/dist/layout/types.d.ts +0 -8
  59. package/dist/xml/xml-patch.d.ts +1 -1
  60. package/package.json +2 -2
@@ -5,9 +5,9 @@ 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";
9
8
  import { REST_CONNECTOR_TEMPLATE_VERSION, restConnectorRetries, restConnectorTaskType, restConnectorToIoMappingInputs, restConnectorToTaskHeaders, } from "./rest-connector.js";
10
9
  import { assertExplicitFlowIdsUnique, assignEventDefinitionIds, assignStableFlowIds, copyFlowTags, markExplicitFlowId, rootDefinitionId, setFlowDiscriminatorSource, } from "./stable-ids.js";
10
+ import { allLanes, assignLane, buildLaneSet, collaborationProblems, freshId, laneForNewNode, laneProblems, poolLanedProcesses, } from "./swimlanes.js";
11
11
  import { assertRetriesOption, assertXsdValues } from "./xsd-guards.js";
12
12
  import { assertZeebePlacement, bpmnElementName, ensureZeebeExtension, makeConditionalDefinition, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
13
13
  import { assertDeployable, targetsCamunda8 } from "./zeebe-validate/gate.js";
@@ -1026,6 +1026,124 @@ function resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions) {
1026
1026
  function emptyLayoutHints() {
1027
1027
  return { grids: new Map(), annotationSides: new Map() };
1028
1028
  }
1029
+ /** Copies every hint of `from` into `into`; ids are document-wide, so nothing clashes. */
1030
+ function mergeLayoutHints(into, from) {
1031
+ for (const [id, grid] of from.grids)
1032
+ into.grids.set(id, grid);
1033
+ for (const [id, side] of from.annotationSides)
1034
+ into.annotationSides.set(id, side);
1035
+ }
1036
+ /**
1037
+ * Every id `process` already uses at any depth: the process, its flow elements
1038
+ * (sub-process children included), sequence flows, annotations and associations.
1039
+ * A new lane or pool id must not take one of them.
1040
+ *
1041
+ * @throws Error when one element object is reached twice, the only way an
1042
+ * element tree assembled by hand can loop.
1043
+ */
1044
+ function processIds(process) {
1045
+ const ids = new Set([process.id]);
1046
+ const seen = new Set();
1047
+ const visit = (scope) => {
1048
+ for (const item of [
1049
+ ...scope.sequenceFlows,
1050
+ ...(scope.textAnnotations ?? []),
1051
+ ...(scope.associations ?? []),
1052
+ ]) {
1053
+ ids.add(item.id);
1054
+ }
1055
+ for (const element of scope.flowElements) {
1056
+ if (seen.has(element)) {
1057
+ throw new Error(`Flow element "${element.id}" appears twice in one element tree`);
1058
+ }
1059
+ seen.add(element);
1060
+ ids.add(element.id);
1061
+ if ("flowElements" in element)
1062
+ visit(element);
1063
+ }
1064
+ };
1065
+ visit(process);
1066
+ return ids;
1067
+ }
1068
+ /**
1069
+ * The lane set a fresh build writes for `declarations`, and every reason the
1070
+ * build must refuse it: a lane id already in `usedIds` or declared twice (the
1071
+ * second declaration is dropped), an undeclared or looping `parent`, flow nodes
1072
+ * on a lane that has child lanes, and a node listed in two lanes. Lanes cut off
1073
+ * from the tree by a bad `parent` are left out. What the lane set itself gets
1074
+ * wrong (unknown refs, unassigned nodes) is for {@link laneProblems}.
1075
+ */
1076
+ function declaredLaneSet(process, declarations, usedIds) {
1077
+ const problems = [];
1078
+ const byId = new Map();
1079
+ for (const lane of declarations) {
1080
+ if (byId.has(lane.id) || usedIds.has(lane.id)) {
1081
+ problems.push(`Lane id "${lane.id}" is already used in process "${process.id}"`);
1082
+ continue;
1083
+ }
1084
+ byId.set(lane.id, lane);
1085
+ }
1086
+ const roots = [];
1087
+ const childrenOf = new Map();
1088
+ for (const lane of byId.values()) {
1089
+ if (lane.parent === undefined)
1090
+ roots.push(lane);
1091
+ else if (!byId.has(lane.parent)) {
1092
+ problems.push(`Lane "${lane.id}" names parent "${lane.parent}", which is not declared`);
1093
+ }
1094
+ else
1095
+ childrenOf.set(lane.parent, [...(childrenOf.get(lane.parent) ?? []), lane]);
1096
+ }
1097
+ for (const lane of byId.values()) {
1098
+ // A chain longer than the number of lanes has revisited one.
1099
+ let current = lane;
1100
+ for (let steps = 0; current?.parent !== undefined; steps++) {
1101
+ if (steps > byId.size) {
1102
+ problems.push(`Lane "${lane.id}" has a parent chain that loops back on itself`);
1103
+ break;
1104
+ }
1105
+ current = byId.get(current.parent);
1106
+ }
1107
+ }
1108
+ // Every lane reached from a root has a parent chain ending at that root, so
1109
+ // none of them sits on a loop and this recursion terminates.
1110
+ const inTree = new Set();
1111
+ const toSpec = (lane) => {
1112
+ inTree.add(lane.id);
1113
+ const spec = { id: lane.id };
1114
+ if (lane.name !== undefined)
1115
+ spec.name = lane.name;
1116
+ const children = childrenOf.get(lane.id) ?? [];
1117
+ if (children.length > 0)
1118
+ spec.lanes = children.map(toSpec);
1119
+ return spec;
1120
+ };
1121
+ const specs = roots.map(toSpec);
1122
+ const leafOf = new Map();
1123
+ for (const lane of byId.values()) {
1124
+ const nodes = lane.flowNodes ?? [];
1125
+ if (!inTree.has(lane.id) || nodes.length === 0)
1126
+ continue;
1127
+ if (childrenOf.has(lane.id)) {
1128
+ problems.push(`Lane "${lane.id}" has child lanes; its flow nodes (${nodes.map((id) => `"${id}"`).join(", ")}) must go in one of its leaf lanes`);
1129
+ continue;
1130
+ }
1131
+ for (const nodeId of nodes) {
1132
+ const owner = leafOf.get(nodeId);
1133
+ if (owner === undefined)
1134
+ leafOf.set(nodeId, lane.id);
1135
+ else if (owner !== lane.id) {
1136
+ problems.push(`Flow node "${nodeId}" is listed in lanes "${owner}" and "${lane.id}"; a node belongs to one leaf lane`);
1137
+ }
1138
+ }
1139
+ }
1140
+ return { laneSet: buildLaneSet(process, specs, leafOf), problems };
1141
+ }
1142
+ /**
1143
+ * Assigned in `ProcessBuilder`'s static block, the one place allowed to read its
1144
+ * private fields, so `DiagramBuilder` can see them without making them public API.
1145
+ */
1146
+ let processBuilderInternals;
1029
1147
  /** Remembers an ad-hoc sub-process's `toolGrid` for the layout. */
1030
1148
  function recordToolGrid(hints, id, options) {
1031
1149
  const grid = options?.toolGrid;
@@ -2286,6 +2404,16 @@ export class ProcessBuilder {
2286
2404
  _pendingSpliceFlowId;
2287
2405
  /** Flows the caller deliberately spliced, exempt from the rewiring guard. */
2288
2406
  _splicedFlowIds = new Set();
2407
+ /** `lane()` calls, in call order. */
2408
+ _lanes = [];
2409
+ /** Set by `participant()`: the pool this process is drawn in. */
2410
+ _participant;
2411
+ static {
2412
+ processBuilderInternals = (builder) => ({
2413
+ executableSet: builder._executableSet,
2414
+ layoutHints: builder.rootLayoutHints,
2415
+ });
2416
+ }
2289
2417
  lanes = new LaneState();
2290
2418
  constructor(processId) {
2291
2419
  this.processId = processId;
@@ -2447,7 +2575,11 @@ export class ProcessBuilder {
2447
2575
  this.processName = name;
2448
2576
  return this;
2449
2577
  }
2450
- /** Set whether this process is executable. */
2578
+ /**
2579
+ * Set whether this process is executable. Pass `false` for a partner pool the
2580
+ * engine must not deploy: Flowable reads an absent `isExecutable` as
2581
+ * executable, so a partner process has to say so explicitly.
2582
+ */
2451
2583
  executable(value) {
2452
2584
  this._isExecutable = value;
2453
2585
  this._executableSet = true;
@@ -3008,6 +3140,192 @@ export class ProcessBuilder {
3008
3140
  });
3009
3141
  return this;
3010
3142
  }
3143
+ // ---- Lanes and pool ----
3144
+ /**
3145
+ * Declares a swimlane, or a child lane of `options.parent`.
3146
+ *
3147
+ * Once any lane is declared, a fresh build puts every top-level flow node in
3148
+ * exactly one leaf lane and refuses otherwise, listing every problem at once
3149
+ * (`Invalid lanes:` …): an unknown or sub-process ref, a node listed twice,
3150
+ * flow nodes on a lane with child lanes, an undeclared or looping parent, a
3151
+ * lane id already in use, an unassigned node. Boundary events follow their
3152
+ * host, and an inferred join gateway the lane of its first predecessor.
3153
+ * Parent lanes list the union of their descendants' refs. Lanes imply a
3154
+ * pool: without {@link participant} the build adds `Participant_<processId>`,
3155
+ * named after the process.
3156
+ *
3157
+ * Continuing a document ({@link ProcessBuilder.from}) instead names one of its
3158
+ * existing leaf lanes: the listed nodes move there, `name` renames it, and a
3159
+ * new lane or a `parent` is refused. Nodes added in continue mode join the lane
3160
+ * of their predecessor (see `laneForNewNode`) without any `lane()` call.
3161
+ *
3162
+ * @param id - The lane's element id, used verbatim.
3163
+ * @example
3164
+ * ```typescript
3165
+ * Bpmn.createProcess("order")
3166
+ * .startEvent("start").userTask("review").serviceTask("ship", { taskType: "ship" }).endEvent("end")
3167
+ * .lane("Lane_sales", { name: "Sales", flowNodes: ["start", "review"] })
3168
+ * .lane("Lane_ops", { name: "Operations", flowNodes: ["ship", "end"] })
3169
+ * ```
3170
+ */
3171
+ lane(id, options = {}) {
3172
+ this._lanes.push({ ...options, id });
3173
+ return this;
3174
+ }
3175
+ /**
3176
+ * Names the pool this process is drawn in: the build writes a collaboration
3177
+ * with one participant `id` referencing this process, named `options.name`,
3178
+ * else the process name, else the process id. Without this call a process
3179
+ * gets a pool only when it has lanes.
3180
+ *
3181
+ * Continuing a document, `id` must be the process's existing pool, which
3182
+ * `name` renames; adding or replacing a pool there is refused.
3183
+ *
3184
+ * @param id - The participant's element id, used verbatim.
3185
+ */
3186
+ participant(id, options = {}) {
3187
+ this._participant = { id, ...options };
3188
+ return this;
3189
+ }
3190
+ /**
3191
+ * Lanes and pool of a fresh build: `process` with its lane set, and the
3192
+ * collaboration `participant()` asked for. Both are returned untouched when
3193
+ * neither `lane()` nor `participant()` was called.
3194
+ *
3195
+ * @throws Error listing every lane and pool problem at once.
3196
+ */
3197
+ freshSwimlanes(process, inferredIds) {
3198
+ const pool = this._participant;
3199
+ if (this._lanes.length === 0 && pool === undefined)
3200
+ return { process, collaborations: [] };
3201
+ const used = processIds(process);
3202
+ const problems = [];
3203
+ if (pool !== undefined) {
3204
+ if (used.has(pool.id)) {
3205
+ problems.push(`Participant id "${pool.id}" is already used in process "${process.id}"`);
3206
+ }
3207
+ used.add(pool.id);
3208
+ }
3209
+ let laned = process;
3210
+ if (this._lanes.length > 0) {
3211
+ const plan = declaredLaneSet(process, this._lanes, used);
3212
+ problems.push(...plan.problems);
3213
+ laned = { ...process, laneSet: plan.laneSet };
3214
+ // The caller never saw an inferred join gateway, so could not list it.
3215
+ for (const id of inferredIds) {
3216
+ const lane = laneForNewNode(laned, id);
3217
+ if (lane !== undefined)
3218
+ laned = assignLane(laned, id, lane.id);
3219
+ }
3220
+ problems.push(...laneProblems(laned));
3221
+ }
3222
+ if (problems.length > 0) {
3223
+ const what = this._lanes.length > 0 ? "lanes" : "pool";
3224
+ throw new Error(`Invalid ${what}:\n ${problems.join("\n ")}`);
3225
+ }
3226
+ if (pool === undefined)
3227
+ return { process: laned, collaborations: [] };
3228
+ const participant = {
3229
+ id: pool.id,
3230
+ // A pool without a label is a lint finding; the process name is what a reader expects there.
3231
+ name: pool.name ?? process.name ?? process.id,
3232
+ processRef: process.id,
3233
+ unknownAttributes: {},
3234
+ };
3235
+ // The caller's ids are theirs: the collaboration steps around every one, lane sets included.
3236
+ const taken = new Set(used);
3237
+ for (const set of [laned.laneSet, ...allLanes(laned.laneSet).map((l) => l.childLaneSet)]) {
3238
+ if (set?.id !== undefined)
3239
+ taken.add(set.id);
3240
+ }
3241
+ for (const lane of allLanes(laned.laneSet))
3242
+ taken.add(lane.id);
3243
+ const collaboration = {
3244
+ id: freshId("Collaboration_1", (n) => `Collaboration_${n}`, taken),
3245
+ participants: [participant],
3246
+ messageFlows: [],
3247
+ textAnnotations: [],
3248
+ associations: [],
3249
+ groups: [],
3250
+ extensionElements: [],
3251
+ unknownAttributes: {},
3252
+ };
3253
+ return { process: laned, collaborations: [collaboration] };
3254
+ }
3255
+ /**
3256
+ * Continue mode: new nodes join the lane `laneForNewNode` picks, then each
3257
+ * `lane()` call moves its nodes into, and renames, an existing leaf lane.
3258
+ * Existing refs are kept as they are, even ones a fresh build would refuse:
3259
+ * the document is the caller's.
3260
+ *
3261
+ * @throws Error listing every `lane()` call that cannot be applied.
3262
+ */
3263
+ continueLanes(process, sourceIds) {
3264
+ let next = process;
3265
+ for (const element of this.flowElements) {
3266
+ if (sourceIds.has(element.id))
3267
+ continue;
3268
+ const lane = laneForNewNode(next, element.id);
3269
+ if (lane !== undefined)
3270
+ next = assignLane(next, element.id, lane.id);
3271
+ }
3272
+ const problems = [];
3273
+ for (const declaration of this._lanes) {
3274
+ if (!allLanes(next.laneSet).some((lane) => lane.id === declaration.id)) {
3275
+ problems.push(`Lane "${declaration.id}" is not declared in process "${process.id}"; continuing a document moves nodes between its lanes but does not add lanes`);
3276
+ continue;
3277
+ }
3278
+ if (declaration.parent !== undefined) {
3279
+ problems.push(`Lane "${declaration.id}": its parent cannot be changed when continuing a document`);
3280
+ }
3281
+ for (const nodeId of declaration.flowNodes ?? []) {
3282
+ if (!this.elementIds.has(nodeId)) {
3283
+ problems.push(`Lane "${declaration.id}" lists "${nodeId}", which is not a flow node of process "${process.id}"`);
3284
+ continue;
3285
+ }
3286
+ try {
3287
+ next = assignLane(next, nodeId, declaration.id);
3288
+ }
3289
+ catch (error) {
3290
+ // Collected so one build reports every bad lane() call; the rest of this
3291
+ // call's nodes would fail for the same reason.
3292
+ problems.push(error.message);
3293
+ break;
3294
+ }
3295
+ }
3296
+ }
3297
+ if (problems.length > 0)
3298
+ throw new Error(`Invalid lanes:\n ${problems.join("\n ")}`);
3299
+ if (next.laneSet !== undefined)
3300
+ process.laneSet = next.laneSet;
3301
+ for (const declaration of this._lanes) {
3302
+ const lane = allLanes(process.laneSet).find((candidate) => candidate.id === declaration.id);
3303
+ if (lane !== undefined && declaration.name !== undefined)
3304
+ lane.name = declaration.name;
3305
+ }
3306
+ }
3307
+ /**
3308
+ * Continue mode: `participant()` renames the pool that already references this
3309
+ * process.
3310
+ *
3311
+ * @throws Error when the process has no pool, or one with another id.
3312
+ */
3313
+ continuePool(definitions) {
3314
+ const pool = this._participant;
3315
+ if (pool === undefined)
3316
+ return;
3317
+ const existing = definitions.collaborations
3318
+ .flatMap((collaboration) => collaboration.participants)
3319
+ .find((participant) => participant.processRef === this.processId);
3320
+ if (existing === undefined) {
3321
+ throw new Error(`Process "${this.processId}" has no pool; continuing a document can rename a pool but not add one`);
3322
+ }
3323
+ if (existing.id !== pool.id) {
3324
+ throw new Error(`Process "${this.processId}" is drawn in pool "${existing.id}"; continuing a document can rename it with participant("${existing.id}", { name }) but not replace it`);
3325
+ }
3326
+ if (pool.name !== undefined)
3327
+ existing.name = pool.name;
3328
+ }
3011
3329
  // ---- Build ----
3012
3330
  /**
3013
3331
  * Build the complete BPMN definitions model.
@@ -3093,6 +3411,9 @@ export class ProcessBuilder {
3093
3411
  return this.buildOntoSource(this._source, elements, flows);
3094
3412
  }
3095
3413
  const laneSet = this.lanes.toLaneSet(this.processId, elements, beforeCount);
3414
+ if (laneSet && this._lanes.length > 0) {
3415
+ throw new Error("inLane() and { lane } cannot be combined with lane(): use one way of declaring this process's lanes.");
3416
+ }
3096
3417
  const extensionElements = embeddedFormElements(elements);
3097
3418
  if (this._versionTag) {
3098
3419
  extensionElements.push({
@@ -3101,7 +3422,8 @@ export class ProcessBuilder {
3101
3422
  children: [],
3102
3423
  });
3103
3424
  }
3104
- const process = {
3425
+ const { process, collaborations } = this.freshSwimlanes({
3426
+ ...(laneSet ? { laneSet } : {}),
3105
3427
  id: this.processId,
3106
3428
  name: this.processName,
3107
3429
  isExecutable: this._isExecutable,
@@ -3112,9 +3434,11 @@ export class ProcessBuilder {
3112
3434
  associations: structuredClone(this._associations),
3113
3435
  groups: [],
3114
3436
  unknownAttributes: {},
3115
- };
3116
- if (laneSet)
3117
- process.laneSet = laneSet;
3437
+ },
3438
+ // What the join inference added: the caller never saw those ids.
3439
+ elements
3440
+ .slice(beforeCount)
3441
+ .map((element) => element.id));
3118
3442
  const defs = {
3119
3443
  id: "Definitions_1",
3120
3444
  targetNamespace: "http://bpmn.io/schema/bpmn",
@@ -3137,32 +3461,35 @@ export class ProcessBuilder {
3137
3461
  escalations: structuredClone(this.rootEscalations),
3138
3462
  messages: structuredClone(this.rootMessages),
3139
3463
  signals: structuredClone(this.rootSignals),
3140
- collaborations: [],
3464
+ collaborations,
3141
3465
  processes: [process],
3142
- // Seed diagram stub so applyAutoLayout preserves process-specific IDs.
3143
- diagrams: this._autoLayout
3144
- ? [
3145
- {
3146
- id: `${this.processId}_di`,
3147
- plane: {
3148
- id: `${this.processId}_di_plane`,
3149
- bpmnElement: this.processId,
3150
- shapes: [],
3151
- edges: [],
3152
- },
3153
- },
3154
- ]
3155
- : [],
3466
+ diagrams: [],
3467
+ };
3468
+ const pooled = poolLanedProcesses(defs);
3469
+ if (!this._autoLayout)
3470
+ return finishDocument(pooled);
3471
+ // Seed diagram stub so applyAutoLayout preserves process-specific IDs. A
3472
+ // pooled diagram's plane draws the collaboration, not the process.
3473
+ const stub = {
3474
+ id: `${this.processId}_di`,
3475
+ plane: {
3476
+ id: `${this.processId}_di_plane`,
3477
+ bpmnElement: pooled.collaborations[0]?.id ?? this.processId,
3478
+ shapes: [],
3479
+ edges: [],
3480
+ },
3156
3481
  };
3157
- return finishDocument(this._autoLayout ? applyAutoLayout(defs, "semantic", this.rootLayoutHints) : defs);
3482
+ return finishDocument(applyAutoLayout({ ...pooled, diagrams: [stub] }, "semantic", this.rootLayoutHints));
3158
3483
  }
3159
3484
  /**
3160
3485
  * Writes this process's contents back into the document it came from.
3161
3486
  *
3162
3487
  * Everything not listed here is kept by identity — other processes, the
3163
- * collaboration, diagram interchange, root elements, the process's own lanes,
3164
- * documentation, extensions and unmodelled content. That is the whole point of
3165
- * continuing rather than regenerating.
3488
+ * collaboration, diagram interchange, root elements, the process's existing
3489
+ * lane refs, documentation, extensions and unmodelled content. That is the
3490
+ * whole point of continuing rather than regenerating. The lanes change only
3491
+ * where nodes were added (each joins its predecessor's lane) or moved with
3492
+ * `lane()`; the pool only where `participant()` renames it.
3166
3493
  *
3167
3494
  * Diagram interchange is *not* regenerated: existing shapes keep their
3168
3495
  * positions, and elements added here have none until `placeNewShapes()` draws
@@ -3172,15 +3499,16 @@ export class ProcessBuilder {
3172
3499
  buildOntoSource(source, elements, flows) {
3173
3500
  const definitions = structuredClone(source.definitions);
3174
3501
  const process = definitions.processes[source.definitions.processes.indexOf(source.process)];
3502
+ const sourceIds = new Set(process.flowElements.map((element) => element.id));
3175
3503
  process.flowElements = elements;
3176
3504
  process.sequenceFlows = flows;
3177
3505
  process.textAnnotations = structuredClone(this._textAnnotations);
3178
3506
  process.associations = structuredClone(this._associations);
3179
3507
  if (this.processName !== undefined)
3180
3508
  process.name = this.processName;
3181
- // Only when asked. BPMN reads an absent `isExecutable` as false, so writing
3182
- // the builder's `true` default onto a process that never carried it makes a
3183
- // non-executable process executable — a change nobody requested.
3509
+ // Only when asked. Engines disagree on an absent `isExecutable` (Camunda:
3510
+ // not executable, Flowable: executable), so writing the builder's `true`
3511
+ // default onto a process that never carried it is a change nobody requested.
3184
3512
  if (this._executableSet)
3185
3513
  process.isExecutable = this._isExecutable;
3186
3514
  if (this._versionTag !== undefined) {
@@ -3195,6 +3523,8 @@ export class ProcessBuilder {
3195
3523
  else
3196
3524
  process.extensionElements.push(form);
3197
3525
  }
3526
+ this.continueLanes(process, sourceIds);
3527
+ this.continuePool(definitions);
3198
3528
  definitions.errors = structuredClone(this.rootErrors);
3199
3529
  definitions.messages = structuredClone(this.rootMessages);
3200
3530
  definitions.signals = structuredClone(this.rootSignals);
@@ -3385,18 +3715,6 @@ function adoptMessageSubscriptions(into, incoming) {
3385
3715
  * Builder for a complete BPMN definitions document containing one or more processes.
3386
3716
  * Use `Bpmn.createDiagram(id?)` to obtain an instance.
3387
3717
  */
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
- }
3400
3718
  export class DiagramBuilder {
3401
3719
  _id;
3402
3720
  _processes = [];
@@ -3404,6 +3722,10 @@ export class DiagramBuilder {
3404
3722
  _messages = [];
3405
3723
  _participants = [];
3406
3724
  _messageFlows = [];
3725
+ /** Pools the processes brought along: `participant()` on the process, or the one lanes imply. */
3726
+ _processPools = [];
3727
+ _layoutHints = emptyLayoutHints();
3728
+ _autoLayout = false;
3407
3729
  _collaborationId = "Collaboration_1";
3408
3730
  _executionPlatformVersion = "8.10.0";
3409
3731
  constructor(id) {
@@ -3414,12 +3736,34 @@ export class DiagramBuilder {
3414
3736
  this._executionPlatformVersion = version;
3415
3737
  return this;
3416
3738
  }
3739
+ /**
3740
+ * Adds a process built by `callback`.
3741
+ *
3742
+ * The process keeps its lanes, and its pool: the one `participant()` named on
3743
+ * the process builder, or the one its lanes imply. A `participant()` on this
3744
+ * diagram that references the same process replaces that pool.
3745
+ *
3746
+ * A process with no flow elements and no lanes, whose builder never called
3747
+ * `executable()`, is written `isExecutable: false`: it can only be the
3748
+ * process of a black-box partner pool, and Flowable would otherwise deploy
3749
+ * it, since it reads an absent attribute as executable. Every other process
3750
+ * keeps the builder's default, `true`; call `.executable(false)` on a partner
3751
+ * that has content.
3752
+ */
3417
3753
  process(id, callback) {
3418
3754
  const builder = new ProcessBuilder(id);
3419
3755
  callback(builder);
3420
3756
  // The document is gated as a whole in build(): a pool may only deploy next to the others.
3421
3757
  const defs = builder.build({ validate: false });
3758
+ const internals = processBuilderInternals(builder);
3759
+ for (const process of defs.processes) {
3760
+ const empty = process.flowElements.length === 0 && process.laneSet === undefined;
3761
+ if (empty && !internals.executableSet)
3762
+ process.isExecutable = false;
3763
+ }
3422
3764
  this._processes.push(...defs.processes);
3765
+ this._processPools.push(...(defs.collaborations[0]?.participants ?? []));
3766
+ mergeLayoutHints(this._layoutHints, internals.layoutHints);
3423
3767
  // Root definitions are named after the message or error code they carry, so
3424
3768
  // two pools declaring the same one produce the same definition twice. The
3425
3769
  // document needs it once.
@@ -3539,110 +3883,13 @@ export class DiagramBuilder {
3539
3883
  return this;
3540
3884
  }
3541
3885
  /**
3542
- * Reports every way the declared collaboration would not survive contact with
3543
- * a modeler, so `build()` can refuse rather than emit a file that opens broken.
3886
+ * Enable auto-layout: `build()` lays out the whole diagram (pools, lanes,
3887
+ * message flows and every process) and writes its diagram interchange, using
3888
+ * the layout hints each process builder recorded.
3544
3889
  */
3545
- collaborationProblems() {
3546
- const problems = [];
3547
- const seen = new Set();
3548
- for (const id of [
3549
- ...this._participants.map((p) => p.id),
3550
- ...this._messageFlows.map((f) => f.id),
3551
- ]) {
3552
- if (seen.has(id))
3553
- problems.push(`Duplicate element ID "${id}"`);
3554
- seen.add(id);
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
- }
3585
- const processIds = new Set(this._processes.map((process) => process.id));
3586
- const claimed = new Map();
3587
- for (const participant of this._participants) {
3588
- const processId = participant.processRef;
3589
- if (processId === undefined)
3590
- continue;
3591
- if (!processIds.has(processId)) {
3592
- problems.push(`Participant "${participant.id}" references process "${processId}", which this diagram does not contain`);
3593
- continue;
3594
- }
3595
- const owner = claimed.get(processId);
3596
- if (owner !== undefined) {
3597
- problems.push(`Participants "${owner}" and "${participant.id}" both reference process "${processId}"; a process belongs to one pool`);
3598
- }
3599
- claimed.set(processId, participant.id);
3600
- }
3601
- const owningParticipant = this.participantIndex();
3602
- const messageIds = new Set(this._messages.map((message) => message.id));
3603
- for (const flow of this._messageFlows) {
3604
- for (const [role, ref] of [
3605
- ["source", flow.sourceRef],
3606
- ["target", flow.targetRef],
3607
- ]) {
3608
- if (!owningParticipant.has(ref)) {
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()])}`);
3610
- }
3611
- }
3612
- const from = owningParticipant.get(flow.sourceRef);
3613
- const to = owningParticipant.get(flow.targetRef);
3614
- if (from !== undefined && from === to) {
3615
- problems.push(`Message flow "${flow.id}" starts and ends in participant "${from}"; a message flow crosses pools, a sequence flow stays inside one`);
3616
- }
3617
- if (flow.messageRef !== undefined && !messageIds.has(flow.messageRef)) {
3618
- problems.push(`Message flow "${flow.id}" references message "${flow.messageRef}", which this diagram does not declare`);
3619
- }
3620
- }
3621
- return problems;
3622
- }
3623
- /** Maps every participant id and every flow node id to its owning participant. */
3624
- participantIndex() {
3625
- const index = new Map();
3626
- const byProcess = new Map();
3627
- for (const participant of this._participants) {
3628
- index.set(participant.id, participant.id);
3629
- if (participant.processRef !== undefined)
3630
- byProcess.set(participant.processRef, participant.id);
3631
- }
3632
- const walk = (elements, owner) => {
3633
- for (const element of elements) {
3634
- index.set(element.id, owner);
3635
- if ("flowElements" in element && Array.isArray(element.flowElements)) {
3636
- walk(element.flowElements, owner);
3637
- }
3638
- }
3639
- };
3640
- for (const process of this._processes) {
3641
- const owner = byProcess.get(process.id);
3642
- if (owner !== undefined)
3643
- walk(process.flowElements, owner);
3644
- }
3645
- return index;
3890
+ withAutoLayout() {
3891
+ this._autoLayout = true;
3892
+ return this;
3646
3893
  }
3647
3894
  /**
3648
3895
  * Build the document. Gated like {@link ProcessBuilder.build}: see
@@ -3654,7 +3901,7 @@ export class DiagramBuilder {
3654
3901
  return gateBuild(this.buildModel(), options);
3655
3902
  }
3656
3903
  buildModel() {
3657
- return finishDocument({
3904
+ const defs = {
3658
3905
  id: this._id,
3659
3906
  targetNamespace: "http://bpmn.io/schema/bpmn",
3660
3907
  exporter: "@bpmnkit/core",
@@ -3679,7 +3926,8 @@ export class DiagramBuilder {
3679
3926
  collaborations: this.buildCollaborations(),
3680
3927
  processes: this._processes,
3681
3928
  diagrams: [],
3682
- });
3929
+ };
3930
+ return finishDocument(this._autoLayout ? applyAutoLayout(defs, "semantic", this._layoutHints) : defs);
3683
3931
  }
3684
3932
  /**
3685
3933
  * A document with no participants has no collaboration — an empty
@@ -3687,16 +3935,17 @@ export class DiagramBuilder {
3687
3935
  * pool-less participant in a modeler.
3688
3936
  */
3689
3937
  buildCollaborations() {
3690
- if (this._participants.length === 0 && this._messageFlows.length === 0)
3938
+ const declared = new Set(this._participants.map((participant) => participant.processRef));
3939
+ const participants = [
3940
+ ...this._processPools.filter((pool) => !declared.has(pool.processRef)),
3941
+ ...this._participants,
3942
+ ];
3943
+ if (participants.length === 0 && this._messageFlows.length === 0)
3691
3944
  return [];
3692
- const problems = this.collaborationProblems();
3693
- if (problems.length > 0) {
3694
- throw new Error(`Invalid collaboration:\n ${problems.join("\n ")}`);
3695
- }
3696
- return [
3945
+ const collaborations = [
3697
3946
  {
3698
3947
  id: this._collaborationId,
3699
- participants: this._participants,
3948
+ participants,
3700
3949
  messageFlows: this._messageFlows,
3701
3950
  textAnnotations: [],
3702
3951
  associations: [],
@@ -3705,6 +3954,16 @@ export class DiagramBuilder {
3705
3954
  unknownAttributes: {},
3706
3955
  },
3707
3956
  ];
3957
+ // Refuse rather than emit a file that opens broken in a modeler.
3958
+ const problems = collaborationProblems({
3959
+ collaborations,
3960
+ processes: this._processes,
3961
+ messages: this._messages,
3962
+ });
3963
+ if (problems.length > 0) {
3964
+ throw new Error(`Invalid collaboration:\n ${problems.join("\n ")}`);
3965
+ }
3966
+ return collaborations;
3708
3967
  }
3709
3968
  }
3710
3969
  //# sourceMappingURL=bpmn-builder.js.map