@bpmnkit/core 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/bpmn/agentic.d.ts +9 -2
  2. package/dist/bpmn/agentic.js +8 -3
  3. package/dist/bpmn/auto-layout.d.ts +7 -2
  4. package/dist/bpmn/auto-layout.js +111 -7
  5. package/dist/bpmn/bpmn-builder.d.ts +65 -4
  6. package/dist/bpmn/bpmn-builder.js +126 -45
  7. package/dist/bpmn/compact.d.ts +24 -0
  8. package/dist/bpmn/compact.js +81 -4
  9. package/dist/bpmn/full-operations.js +20 -0
  10. package/dist/bpmn/optimize/flow.js +2 -0
  11. package/dist/bpmn/optimize/patterns.js +2 -2
  12. package/dist/bpmn/optimize/variable-flow.d.ts +1 -0
  13. package/dist/bpmn/optimize/variable-flow.js +1 -1
  14. package/dist/bpmn/process-delta.d.ts +21 -1
  15. package/dist/bpmn/process-delta.js +33 -3
  16. package/dist/bpmn/process-text-writer.js +80 -6
  17. package/dist/bpmn/process-text.d.ts +22 -1
  18. package/dist/bpmn/process-text.js +268 -9
  19. package/dist/bpmn/stable-ids.d.ts +11 -0
  20. package/dist/bpmn/stable-ids.js +76 -10
  21. package/dist/connectors/apply-many.d.ts +49 -0
  22. package/dist/connectors/apply-many.js +162 -0
  23. package/dist/connectors/index.d.ts +2 -0
  24. package/dist/connectors/index.js +1 -0
  25. package/dist/connectors/lines.d.ts +1 -1
  26. package/dist/connectors/lines.js +13 -3
  27. package/dist/connectors/select.d.ts +2 -0
  28. package/dist/connectors/select.js +11 -0
  29. package/dist/index.d.ts +3 -3
  30. package/dist/layout/annotations.d.ts +3 -1
  31. package/dist/layout/annotations.js +11 -4
  32. package/dist/layout/index.d.ts +1 -1
  33. package/dist/layout/layout-engine.d.ts +4 -2
  34. package/dist/layout/layout-engine.js +4 -2
  35. package/dist/layout/semantic/index.d.ts +7 -3
  36. package/dist/layout/semantic/index.js +11 -7
  37. package/dist/layout/semantic/place.d.ts +4 -2
  38. package/dist/layout/semantic/place.js +12 -9
  39. package/dist/layout/types.d.ts +18 -0
  40. package/package.json +2 -2
@@ -31,14 +31,22 @@ import { CONNECTOR_LINE, parseConnectorLine } from "./connector-line.js";
31
31
  * and expects no problems.
32
32
  */
33
33
  export const PROCESS_TEXT_GUIDE = `Format — one path per line, nothing else:
34
- # Process name (first line)
34
+ # Process name (first line; add " | camunda=8.10" to target a Camunda version)
35
35
  a > b > c sequence flow
36
36
  id[kind Name] declare a node the first time it appears; afterwards write only id
37
37
  gw >(Label: condition) x conditional branch, condition in FEEL (amount > 1000, status = "ok")
38
38
  gw >(Label: default) y branch taken when no condition holds
39
- Kinds: start end task user service rule (DMN decision) send receive script manual call xor and or eventgw catch (wait for message or timer) throw boundary
39
+ Kinds: start end task user service rule (DMN decision) send receive script manual call xor and or eventgw catch (wait for message or timer) throw boundary adhoc (an AI agent that chooses among tools)
40
40
  Events take a trigger: start:message end:error catch:timer boundary:error (timer message signal error escalation terminate conditional compensate cancel)
41
41
  Attributes after |: on=<task id> (required on boundary), nonint (non-interrupting), job=<job type>, each=<list variable> (once per item), after=<ISO duration> (timer), result=<variable>, feel=<FEEL expression> (last)
42
+ Also after |: form=<form id> (start, user), in.<name>=<FEEL> and out.<name>=<FEEL> map variables in and out of a step (value runs to the next word=; write comparisons with spaces: a = 1)
43
+ Ad-hoc: agent[adhoc Name] is a container with flows like any node; tool[service Name | inside=agent] has no flows of its own; note <id>: text annotates a node
44
+ doc <id>: text the element's documentation; for a tool inside an ad-hoc agent it is the description the agent chooses the tool by
45
+ Ad-hoc example:
46
+ ask[start Question asked] > agent[adhoc Answer with tools] > review[user Review answer] > done[end Answered]
47
+ users[service Look up users | inside=agent]
48
+ doc users: Returns the list of sample users
49
+ note agent: Picks a tool by its description
42
50
  Rules:
43
51
  - One start event. Every node is on a path from it to an end event: never a node nothing leads to.
44
52
  - An xor has two or more branches: exactly one is (Label: default), each other has a FEEL condition.
@@ -66,6 +74,7 @@ export const KINDS = {
66
74
  script: "scriptTask",
67
75
  manual: "manualTask",
68
76
  call: "callActivity",
77
+ adhoc: "adHocSubProcess",
69
78
  xor: "exclusiveGateway",
70
79
  and: "parallelGateway",
71
80
  or: "inclusiveGateway",
@@ -119,6 +128,12 @@ const CONDITIONAL = new Set(["exclusiveGateway", "inclusiveGateway"]);
119
128
  /** Task types that need a `zeebe:taskDefinition` to deploy; the id stands in when none is given. */
120
129
  const JOB_TASKS = new Set(["serviceTask", "sendTask"]);
121
130
  const ID = /^[A-Za-z_][\w.-]*/;
131
+ /** `note <id>: text`, which is not a path and may hold any characters. */
132
+ export const NOTE_LINE = /^note\s+([A-Za-z_][\w.-]*)\s*:\s*(.*)$/i;
133
+ /** `doc <id>: text`, the element's documentation; free text like a note. */
134
+ export const DOC_LINE = /^doc\s+([A-Za-z_][\w.-]*)\s*:\s*(.*)$/i;
135
+ /** A title segment that is only attributes of a known key: `camunda=8.10`. */
136
+ const HEADER_SEGMENT = /^[\s,]*(?:camunda=[^\s,|]*[\s,]*)+$/;
122
137
  /** A line that ends in an arrow, with or without a branch label: the path goes on below. */
123
138
  const DANGLING = /\s*-{0,2}>\s*(\([^()]*\))?\s*$/;
124
139
  /**
@@ -156,6 +171,37 @@ export function splitFeel(attrs) {
156
171
  return { plain: attrs.slice(0, at.index) };
157
172
  return { plain: attrs.slice(0, at.index), feel: feel.startsWith("=") ? feel : `= ${feel}` };
158
173
  }
174
+ /**
175
+ * Takes the `in.<target>=<FEEL>` and `out.<target>=<FEEL>` mappings off a declaration's
176
+ * attributes. A value runs up to the next ` <word>=` or the end, so it may hold spaces,
177
+ * commas and `=` spaced as FEEL comparison is written (`if a = 1 then …`); an unspaced
178
+ * ` a=1` inside it reads as the next attribute. Call {@link splitFeel} first: `feel=`
179
+ * is last and takes the rest, mappings included.
180
+ *
181
+ * @returns The other attributes, and each mapping's target and FEEL, in order.
182
+ */
183
+ export function splitMappings(attrs) {
184
+ const mappings = [];
185
+ let plain = attrs;
186
+ for (;;) {
187
+ const at = /(?:^|[\s,|])(in|out)\.([A-Za-z_][\w.-]*)=/.exec(plain);
188
+ if (!at)
189
+ return { plain, mappings };
190
+ const start = at.index + at[0].length;
191
+ const next = /\s[A-Za-z_][\w.-]*=/.exec(plain.slice(start));
192
+ const end = next ? start + next.index : plain.length;
193
+ mappings.push({
194
+ direction: at[1],
195
+ target: at[2],
196
+ // FEEL never ends in `|` or `,`: that is the separator before the next attribute
197
+ value: plain
198
+ .slice(start, end)
199
+ .replace(/[\s,|]+$/, "")
200
+ .trim(),
201
+ });
202
+ plain = `${plain.slice(0, at.index)} ${plain.slice(end)}`;
203
+ }
204
+ }
159
205
  /** Words that name the handling of a failure, a timeout or a cancellation. */
160
206
  const HANDLING = /\b(?:fail\w*|error\w*|handle\w*|alert\w*|notify\w*|retr(?:y|ies)|escalat\w*|cancel\w*|reject\w*|abort\w*|roll\s?back|compensat\w*|timeout|timed out|late)\b/i;
161
207
  /** Whether `element` reads as the handling of what a boundary catches. */
@@ -343,13 +389,32 @@ class Reader {
343
389
  fixes = [];
344
390
  /** `with` lines, with the written id resolved to the node it meant when read. */
345
391
  connectors = [];
392
+ /** `note` lines, with the written id resolved to the node it meant when read. */
393
+ notes = [];
394
+ /** `doc` lines, with the written id resolved to the node it meant when read. */
395
+ docs = [];
346
396
  /** Catch and boundary events written without a trigger, and made message events. */
347
397
  guessedMessage = new Set();
348
398
  title;
399
+ /** `executionPlatformVersion` from `# Name | camunda=8.10`. */
400
+ platformVersion;
349
401
  /** A line that ended in an arrow, waiting for the line that continues it. */
350
402
  carry;
351
403
  /** The last node of the last path read, which a line starting with an arrow continues. */
352
404
  tail;
405
+ /** Reads the attributes after the bar of the title line. */
406
+ header(attrs, n) {
407
+ for (const attr of attrs.split(/[\s,|]+/).filter(Boolean)) {
408
+ const [key, value = ""] = attr.split("=", 2);
409
+ const version = /^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(value);
410
+ if (key === "camunda" && version) {
411
+ this.platformVersion = `${version[1]}.${version[2]}.${version[3] ?? "0"}`;
412
+ }
413
+ else {
414
+ this.problems.push({ line: n, message: `unknown title attribute "${attr}"; ignored` });
415
+ }
416
+ }
417
+ }
353
418
  /** Reads one line. Returns whether it added anything. */
354
419
  line(raw, n) {
355
420
  let text = raw.trim();
@@ -362,8 +427,16 @@ class Reader {
362
427
  if (text === "" || text.startsWith("```") || text.startsWith("//"))
363
428
  return false;
364
429
  if (text.startsWith("#")) {
365
- if (this.title === undefined)
366
- this.title = text.replace(/^#+/, "").trim() || undefined;
430
+ if (this.title === undefined) {
431
+ const parts = text.replace(/^#+/, "").split("|");
432
+ // Peel segments off the end while they are all `camunda=…`; anything else is
433
+ // part of the name (`# Order | Payment flow`).
434
+ let keep = parts.length;
435
+ while (keep > 1 && HEADER_SEGMENT.test(parts[keep - 1] ?? ""))
436
+ keep--;
437
+ this.title = parts.slice(0, keep).join("|").trim() || undefined;
438
+ this.header(parts.slice(keep).join("|"), n);
439
+ }
367
440
  return false;
368
441
  }
369
442
  if (CONNECTOR_LINE.test(text)) {
@@ -376,6 +449,28 @@ class Reader {
376
449
  }
377
450
  return false;
378
451
  }
452
+ const note = NOTE_LINE.exec(text);
453
+ if (note) {
454
+ const written = note[1];
455
+ this.notes.push({
456
+ elementId: this.current.get(written) ?? written,
457
+ written,
458
+ text: (note[2] ?? "").trim(),
459
+ line: n,
460
+ });
461
+ return true;
462
+ }
463
+ const doc = DOC_LINE.exec(text);
464
+ if (doc) {
465
+ const written = doc[1];
466
+ this.docs.push({
467
+ elementId: this.current.get(written) ?? written,
468
+ written,
469
+ text: (doc[2] ?? "").trim(),
470
+ line: n,
471
+ });
472
+ return true;
473
+ }
379
474
  // `> stop[end Done]`: the path above wrapped before its arrow
380
475
  if (/^-{0,2}>/.test(text) && this.tail !== undefined) {
381
476
  this.problems.push({
@@ -494,7 +589,7 @@ class Reader {
494
589
  // host is the earlier `pay`.
495
590
  const meant = (ref) => this.current.get(ref) ?? ref;
496
591
  const hostOf = new Map();
497
- for (const match of spec.matchAll(/\bon=([\w.-]+)/g)) {
592
+ for (const match of spec.matchAll(/\b(?:on|inside)=([\w.-]+)/g)) {
498
593
  if (match[1])
499
594
  hostOf.set(match[1], meant(match[1]));
500
595
  }
@@ -588,16 +683,44 @@ class Reader {
588
683
  });
589
684
  }
590
685
  const node = { element, line: n, spec };
591
- const { plain, feel } = splitFeel(attrs);
686
+ const split = splitFeel(attrs);
687
+ const { feel } = split;
688
+ const { plain, mappings } = splitMappings(split.plain);
689
+ for (const { direction, target, value } of mappings) {
690
+ const source = value.startsWith("=") ? value : `=${value}`;
691
+ if (value === "" || parseExpression(source.slice(1)).errors.length > 0) {
692
+ this.problems.push({
693
+ line: n,
694
+ message: `${direction}.${target}= on "${id}" is not FEEL; kept for the reader to correct`,
695
+ });
696
+ }
697
+ const key = direction === "in" ? "inputs" : "outputs";
698
+ element[key] = { ...element[key], [target]: source };
699
+ }
592
700
  // `| on=pay | nonint`: a second bar is only another separator.
593
701
  for (const attr of plain.split(/[\s,|]+/).filter(Boolean)) {
594
702
  const [key, value] = attr.split("=", 2);
595
703
  if (key === "on" && value)
596
704
  node.on = hostOf.get(value) ?? value;
705
+ else if (key === "inside" && value)
706
+ node.inside = hostOf.get(value) ?? value;
597
707
  else if (key === "job" && value)
598
708
  element.jobType = value;
599
709
  else if (key === "nonint" && value === undefined)
600
710
  element.interrupting = false;
711
+ else if (key === "form" &&
712
+ value &&
713
+ (element.type === "startEvent" || element.type === "userTask")) {
714
+ element.formId = value;
715
+ if (element.type === "userTask")
716
+ element.nativeUserTask = true;
717
+ }
718
+ else if (key === "form" && value) {
719
+ this.problems.push({
720
+ line: n,
721
+ message: `form= takes a start or user node; ignored on "${id}"`,
722
+ });
723
+ }
601
724
  else if (key === "each" && value && GATEWAYS.has(element.type) && element.name) {
602
725
  // `and[and Process every recipient | each=recipients]`: a step, run per item
603
726
  this.problems.push({
@@ -820,6 +943,80 @@ function assemble(reader, final) {
820
943
  }
821
944
  }
822
945
  }
946
+ // `inside=<adhoc>`: a task that lives in an ad-hoc sub-process and takes no part in the flow, so
947
+ // it is taken out of the flow rules below. One that cannot live there stays where it is written.
948
+ const childNodes = [];
949
+ for (const [id, node] of [...nodes]) {
950
+ let parentId = node.inside;
951
+ if (parentId === undefined)
952
+ continue;
953
+ let parent = nodes.get(parentId);
954
+ const type = node.element.type;
955
+ if (parent === undefined && !final) {
956
+ nodes.delete(id); // container still to come
957
+ continue;
958
+ }
959
+ // `inside=agnet`: with one ad-hoc sub-process in the diagram there is no doubt which was meant
960
+ const only = [...nodes.values()].filter((n) => n.element.type === "adHocSubProcess");
961
+ const sole = only.length === 1 ? only[0] : undefined;
962
+ if (parent === undefined && sole !== undefined && !sole.inside) {
963
+ const written = parentId;
964
+ const name = node.element.name ?? nameFromId(id);
965
+ node.inside = parentId = sole.element.id;
966
+ parent = sole;
967
+ fixes.push(`read inside=${written} on "${id}" as inside="${parentId}", the only ad-hoc sub-process`);
968
+ asks.push({
969
+ line: node.line,
970
+ ask: () => ({
971
+ elementId: id,
972
+ text: `inside=${written} on "${name}" names no ad-hoc sub-process, so it was put in "${nameOf(parentId ?? "")}", the only one. Is that where it belongs?`,
973
+ options: [],
974
+ draft: `Move "${name}" to `,
975
+ }),
976
+ });
977
+ }
978
+ const why = parent === undefined
979
+ ? `"${parentId}" is never declared`
980
+ : parent.element.type !== "adHocSubProcess"
981
+ ? `"${parentId}" is not an ad-hoc sub-process`
982
+ : parent.inside !== undefined
983
+ ? `"${parentId}" is itself inside another sub-process`
984
+ : EVENTS.has(type) || GATEWAYS.has(type) || type === "adHocSubProcess"
985
+ ? `only a task can be inside an ad-hoc sub-process, not ${type}`
986
+ : undefined;
987
+ if (why !== undefined) {
988
+ // A node nothing leads to is dropped later as unconnected; say so rather than "stays"
989
+ const drawn = reader.edges.some((edge) => edge.from === id || edge.to === id);
990
+ problems.push({
991
+ line: node.line,
992
+ message: `inside=${parentId} on "${id}": ${why}; "${id}" ${drawn ? "stays at the top level" : "has no flows, so it is left out"}`,
993
+ });
994
+ node.inside = undefined;
995
+ continue;
996
+ }
997
+ nodes.delete(id);
998
+ childNodes.push(node);
999
+ }
1000
+ const insideIds = new Set(childNodes.map((node) => node.element.id));
1001
+ // Flows would make the task run in the main path, which an ad-hoc tool does not
1002
+ const flowing = [];
1003
+ const outside = [];
1004
+ for (const edge of reader.edges) {
1005
+ if (insideIds.has(edge.from) || insideIds.has(edge.to))
1006
+ flowing.push(edge);
1007
+ else
1008
+ outside.push(edge);
1009
+ }
1010
+ if (final) {
1011
+ for (const edge of flowing) {
1012
+ const child = insideIds.has(edge.from) ? edge.from : edge.to;
1013
+ const parent = reader.nodes.get(child)?.inside;
1014
+ problems.push({
1015
+ line: edge.line,
1016
+ message: `"${child}" is inside "${parent}", where a task has no flows; flow ${edge.from} > ${edge.to} left out`,
1017
+ });
1018
+ }
1019
+ }
823
1020
  // Boundary events: a host that is an activity, in this process.
824
1021
  for (const [id, node] of nodes) {
825
1022
  if (node.element.type !== "boundaryEvent")
@@ -855,7 +1052,7 @@ function assemble(reader, final) {
855
1052
  // A branch drawn into a boundary event (`check >(No) failed[boundary:error … |
856
1053
  // on=pay] > notify`) means the path that boundary leads to. Nothing can flow
857
1054
  // into a boundary, so the branch goes to its handler instead of being lost.
858
- const written = reader.edges.flatMap((edge) => {
1055
+ const written = outside.flatMap((edge) => {
859
1056
  const target = reader.nodes.get(edge.to);
860
1057
  if (target?.element.type !== "boundaryEvent")
861
1058
  return [edge];
@@ -1480,6 +1677,12 @@ function assemble(reader, final) {
1480
1677
  element.name = GATEWAYS.has(element.type) ? `${nameFromId(id)}?` : nameFromId(id);
1481
1678
  named++;
1482
1679
  }
1680
+ for (const { element } of childNodes) {
1681
+ if (element.name?.trim())
1682
+ continue;
1683
+ element.name = nameFromId(element.id);
1684
+ named++;
1685
+ }
1483
1686
  if (named > 0)
1484
1687
  fixes.push(`named ${named} unnamed element(s) from their ids`);
1485
1688
  for (const id of reader.guessedMessage) {
@@ -1507,7 +1710,7 @@ function assemble(reader, final) {
1507
1710
  });
1508
1711
  }
1509
1712
  }
1510
- for (const node of nodes.values()) {
1713
+ for (const node of [...nodes.values(), ...childNodes]) {
1511
1714
  if (JOB_TASKS.has(node.element.type) && node.element.jobType === undefined) {
1512
1715
  node.element.jobType = node.element.id;
1513
1716
  }
@@ -1534,11 +1737,65 @@ function assemble(reader, final) {
1534
1737
  }
1535
1738
  return flow;
1536
1739
  });
1740
+ for (const child of childNodes) {
1741
+ const parent = nodes.get(child.inside ?? "");
1742
+ if (parent === undefined) {
1743
+ // Its container was left out above; a child alone would be drawn loose
1744
+ if (final) {
1745
+ problems.push({
1746
+ line: child.line,
1747
+ message: `"${child.element.id}" is inside "${child.inside}", which was left out; left out`,
1748
+ });
1749
+ }
1750
+ continue;
1751
+ }
1752
+ const content = parent.element.children ?? { elements: [], flows: [] };
1753
+ content.elements.push(child.element);
1754
+ parent.element.children = content;
1755
+ }
1756
+ const notes = [];
1757
+ for (const note of reader.notes) {
1758
+ const present = nodes.has(note.elementId) ||
1759
+ childNodes.some((child) => child.element.id === note.elementId && nodes.has(child.inside ?? ""));
1760
+ if (present && note.text !== "")
1761
+ notes.push({ elementId: note.elementId, text: note.text });
1762
+ else if (final) {
1763
+ problems.push({
1764
+ line: note.line,
1765
+ message: note.text === ""
1766
+ ? `note ${note.written}: has no text; ignored`
1767
+ : `note ${note.written}: names no node of the diagram; ignored`,
1768
+ });
1769
+ }
1770
+ }
1771
+ // Documentation goes on the element itself, a tool inside an ad-hoc sub-process included
1772
+ const everyElement = new Map();
1773
+ for (const node of nodes.values())
1774
+ everyElement.set(node.element.id, node.element);
1775
+ for (const child of childNodes) {
1776
+ if (nodes.has(child.inside ?? ""))
1777
+ everyElement.set(child.element.id, child.element);
1778
+ }
1779
+ for (const doc of reader.docs) {
1780
+ const element = everyElement.get(doc.elementId);
1781
+ if (element !== undefined && doc.text !== "")
1782
+ element.documentation = doc.text;
1783
+ else if (final) {
1784
+ problems.push({
1785
+ line: doc.line,
1786
+ message: doc.text === ""
1787
+ ? `doc ${doc.written}: has no text; ignored`
1788
+ : `doc ${doc.written}: names no node of the diagram; ignored`,
1789
+ });
1790
+ }
1791
+ }
1537
1792
  // A `with` line configures a node of the diagram; one whose node was left out, or
1538
1793
  // never written, has nothing to configure.
1539
1794
  const connectors = [];
1540
1795
  for (const ref of reader.connectors) {
1541
- if (nodes.has(ref.elementId))
1796
+ // A tool inside an ad-hoc sub-process is a node too, though it is not in `nodes`
1797
+ const tool = childNodes.some((child) => child.element.id === ref.elementId && nodes.has(child.inside ?? ""));
1798
+ if (nodes.has(ref.elementId) || tool)
1542
1799
  connectors.push(ref);
1543
1800
  else if (final) {
1544
1801
  problems.push({
@@ -1550,12 +1807,14 @@ function assemble(reader, final) {
1550
1807
  return {
1551
1808
  diagram: {
1552
1809
  id: "Definitions_1",
1810
+ ...(reader.platformVersion ? { executionPlatformVersion: reader.platformVersion } : {}),
1553
1811
  processes: [
1554
1812
  {
1555
1813
  id: processId,
1556
1814
  ...(reader.title ? { name: reader.title } : {}),
1557
1815
  elements: [...nodes.values()].map((node) => node.element),
1558
1816
  flows,
1817
+ ...(notes.length > 0 ? { notes } : {}),
1559
1818
  },
1560
1819
  ],
1561
1820
  },
@@ -1,4 +1,15 @@
1
1
  import type { BpmnFlowElement, BpmnSequenceFlow } from "./bpmn-model.js";
2
+ /** Records the branch id to build `flow`'s discriminator from, instead of its label. */
3
+ export declare function setFlowDiscriminatorSource(flow: BpmnSequenceFlow, branchId: string): void;
4
+ /** Marks `flow.id` as caller-chosen: `assignStableFlowIds` keeps it and reserves it. */
5
+ export declare function markExplicitFlowId(flow: BpmnSequenceFlow): void;
6
+ /**
7
+ * Throws when a caller-chosen flow id is also the id of another element or
8
+ * flow anywhere in the process, nested sub-processes included.
9
+ * `assignStableFlowIds` only sees one scope, and BPMN ids are unique per
10
+ * document; run this once the outermost scope is final.
11
+ */
12
+ export declare function assertExplicitFlowIdsUnique(elements: BpmnFlowElement[], flows: BpmnSequenceFlow[]): void;
2
13
  /**
3
14
  * Replaces generated sequence-flow ids in one scope (a process or a
4
15
  * sub-process) with ids derived from the flows themselves, and rewrites the
@@ -42,6 +42,61 @@ function capLength(id) {
42
42
  const suffix = `_${shortHash(id)}`;
43
43
  return id.slice(0, MAX_ID_LENGTH - suffix.length) + suffix;
44
44
  }
45
+ /**
46
+ * Builder-side facts about a flow that must not leak into the XML: the branch
47
+ * id a branch flow is told apart by (its label is free text and may change
48
+ * without renaming the flow), and ids the caller chose. Keyed by the flow
49
+ * object, which the builder pushes into the scope by reference.
50
+ */
51
+ const branchIds = new WeakMap();
52
+ const explicitIds = new WeakSet();
53
+ /** Records the branch id to build `flow`'s discriminator from, instead of its label. */
54
+ export function setFlowDiscriminatorSource(flow, branchId) {
55
+ branchIds.set(flow, branchId);
56
+ }
57
+ /** Marks `flow.id` as caller-chosen: `assignStableFlowIds` keeps it and reserves it. */
58
+ export function markExplicitFlowId(flow) {
59
+ explicitIds.add(flow);
60
+ }
61
+ function isIdScope(element) {
62
+ return "flowElements" in element && "sequenceFlows" in element;
63
+ }
64
+ /**
65
+ * Throws when a caller-chosen flow id is also the id of another element or
66
+ * flow anywhere in the process, nested sub-processes included.
67
+ * `assignStableFlowIds` only sees one scope, and BPMN ids are unique per
68
+ * document; run this once the outermost scope is final.
69
+ */
70
+ export function assertExplicitFlowIdsUnique(elements, flows) {
71
+ const owners = new Map();
72
+ const add = (id, owner, label) => {
73
+ const list = owners.get(id);
74
+ if (list)
75
+ list.push({ owner, label });
76
+ else
77
+ owners.set(id, [{ owner, label }]);
78
+ };
79
+ const explicit = [];
80
+ const walk = (scopeElements, scopeFlows) => {
81
+ for (const element of scopeElements) {
82
+ add(element.id, element, `element "${element.id}"`);
83
+ if (isIdScope(element))
84
+ walk(element.flowElements, element.sequenceFlows);
85
+ }
86
+ for (const flow of scopeFlows) {
87
+ add(flow.id, flow, `the flow ${flow.sourceRef} -> ${flow.targetRef}`);
88
+ if (explicitIds.has(flow))
89
+ explicit.push(flow);
90
+ }
91
+ };
92
+ walk(elements, flows);
93
+ for (const flow of explicit) {
94
+ const other = owners.get(flow.id)?.find((entry) => entry.owner !== flow);
95
+ if (other) {
96
+ throw new Error(`Flow id "${flow.id}" (${flow.sourceRef} -> ${flow.targetRef}) is already used by ${other.label}. Pick a different flowId().`);
97
+ }
98
+ }
99
+ }
45
100
  /** The id a flow gets when it is the only one between its two endpoints. */
46
101
  function baseId(flow) {
47
102
  return capLength(`Flow_${ncName(flow.sourceRef)}_${ncName(flow.targetRef)}`);
@@ -52,8 +107,9 @@ function baseId(flow) {
52
107
  * `uniqueId` to number genuinely identical edges.
53
108
  */
54
109
  function discriminator(flow) {
55
- if (flow.name !== undefined && flow.name.trim().length > 0)
56
- return ncName(slugify(flow.name));
110
+ const source = branchIds.get(flow) ?? flow.name;
111
+ if (source !== undefined && source.trim().length > 0)
112
+ return ncName(slugify(source));
57
113
  const condition = flow.conditionExpression?.text;
58
114
  if (condition !== undefined && condition.trim().length > 0)
59
115
  return `c${shortHash(condition)}`;
@@ -74,17 +130,27 @@ function discriminator(flow) {
74
130
  * continuing a parsed document must not renumber what it was handed.
75
131
  */
76
132
  export function assignStableFlowIds(elements, flows, preserve) {
77
- const renamable = preserve === undefined ? flows : flows.filter((flow) => !preserve.has(flow.id));
78
- if (renamable.length === 0)
79
- return;
133
+ const isFixed = (flow) => explicitIds.has(flow) || preserve?.has(flow.id);
80
134
  // Reserved up front so a derived id can never land on an element id or on a
81
135
  // flow id this pass is not allowed to touch.
82
- const taken = new Set(elements.map((element) => element.id));
83
- if (preserve !== undefined) {
84
- for (const flow of flows)
85
- if (preserve.has(flow.id))
86
- taken.add(flow.id);
136
+ const taken = new Set();
137
+ const owners = new Map();
138
+ for (const element of elements) {
139
+ taken.add(element.id);
140
+ owners.set(element.id, `element "${element.id}"`);
87
141
  }
142
+ for (const flow of flows) {
143
+ if (!isFixed(flow))
144
+ continue;
145
+ if (explicitIds.has(flow) && taken.has(flow.id)) {
146
+ throw new Error(`Flow id "${flow.id}" (${flow.sourceRef} -> ${flow.targetRef}) is already used by ${owners.get(flow.id) ?? "another flow"}. Pick a different flowId().`);
147
+ }
148
+ taken.add(flow.id);
149
+ owners.set(flow.id, `the flow ${flow.sourceRef} -> ${flow.targetRef}`);
150
+ }
151
+ const renamable = flows.filter((flow) => !isFixed(flow));
152
+ if (renamable.length === 0)
153
+ return;
88
154
  // Flows sharing a base id all get a discriminator, so which one was built
89
155
  // first — and so the order branches were declared in — does not decide who
90
156
  // keeps the short id.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Applying several element templates in one call, from values a caller wrote
3
+ * by hand — an agent's script, not a property panel. Where
4
+ * {@link applyTemplateToElement} takes a resolved template and string values,
5
+ * this takes the names people and models actually use (`HttpJson.v2@18`,
6
+ * `http`), lets numbers and booleans stand for themselves, and answers a
7
+ * misspelt key with the key the template meant.
8
+ */
9
+ import type { BpmnDefinitions } from "../index.js";
10
+ import type { ElementTemplate } from "./template-types.js";
11
+ export interface TemplateApplication {
12
+ elementId: string;
13
+ /** "io.camunda.connectors.HttpJson.v2", "io.camunda.connectors.HttpJson.v2@18", or an alias such as "http" */
14
+ template: string | ElementTemplate;
15
+ values: Record<string, string | number | boolean>;
16
+ }
17
+ export interface TemplateApplicationProblem {
18
+ elementId: string;
19
+ message: string;
20
+ key?: string;
21
+ /** The template property id the key was most likely meant to be. */
22
+ suggestion?: string;
23
+ }
24
+ /**
25
+ * Applies each entry in order with {@link applyTemplateToElement} and gathers
26
+ * what went wrong, each problem naming its element.
27
+ *
28
+ * - **Templates.** An id, `id@version`, an alias from `CONNECTOR_ALIASES`, or
29
+ * a template object. The catalogue holds one version of each id, so a
30
+ * different `@version` is a problem naming the available one and the
31
+ * element is left as it was.
32
+ * - **Values.** Keyed by template property id, as in `applyTemplateToElement`;
33
+ * numbers and booleans become their string form. Strings are written
34
+ * verbatim — a real newline stays a newline. Properties left out keep the
35
+ * template's default.
36
+ * - **Unknown keys.** Reported with a `suggestion` when a property id or
37
+ * binding name is close; the rest of the entry is still applied.
38
+ * - **Switched-off keys.** A value for a property whose `condition` does not
39
+ * hold for the entry's values is not written, and is reported naming the
40
+ * condition.
41
+ *
42
+ * @param definitions - The model; not mutated.
43
+ * @param entries - Elements anywhere in the model, nested ones included.
44
+ */
45
+ export declare function applyTemplates(definitions: BpmnDefinitions, entries: TemplateApplication[]): {
46
+ definitions: BpmnDefinitions;
47
+ problems: TemplateApplicationProblem[];
48
+ };
49
+ //# sourceMappingURL=apply-many.d.ts.map