@bpmnkit/core 1.4.1 → 1.6.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 (42) 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 +99 -5
  6. package/dist/bpmn/bpmn-builder.js +203 -69
  7. package/dist/bpmn/compact.d.ts +24 -0
  8. package/dist/bpmn/compact.js +78 -4
  9. package/dist/bpmn/full-operations.js +20 -0
  10. package/dist/bpmn/optimize/patterns.js +2 -2
  11. package/dist/bpmn/optimize/variable-flow.d.ts +1 -0
  12. package/dist/bpmn/optimize/variable-flow.js +1 -1
  13. package/dist/bpmn/process-delta.d.ts +21 -1
  14. package/dist/bpmn/process-delta.js +33 -3
  15. package/dist/bpmn/process-text-writer.js +80 -6
  16. package/dist/bpmn/process-text.d.ts +22 -1
  17. package/dist/bpmn/process-text.js +268 -9
  18. package/dist/bpmn/stable-ids.d.ts +11 -0
  19. package/dist/bpmn/stable-ids.js +76 -10
  20. package/dist/connectors/apply-many.d.ts +49 -0
  21. package/dist/connectors/apply-many.js +162 -0
  22. package/dist/connectors/index.d.ts +2 -0
  23. package/dist/connectors/index.js +1 -0
  24. package/dist/connectors/lines.d.ts +1 -1
  25. package/dist/connectors/lines.js +13 -3
  26. package/dist/connectors/select.d.ts +2 -0
  27. package/dist/connectors/select.js +11 -0
  28. package/dist/index.d.ts +3 -3
  29. package/dist/layout/annotations.d.ts +3 -1
  30. package/dist/layout/annotations.js +11 -4
  31. package/dist/layout/index.d.ts +1 -1
  32. package/dist/layout/layout-engine.d.ts +4 -2
  33. package/dist/layout/layout-engine.js +4 -2
  34. package/dist/layout/semantic/bands.d.ts +10 -1
  35. package/dist/layout/semantic/bands.js +16 -8
  36. package/dist/layout/semantic/index.d.ts +9 -3
  37. package/dist/layout/semantic/index.js +119 -24
  38. package/dist/layout/semantic/place.d.ts +23 -3
  39. package/dist/layout/semantic/place.js +127 -7
  40. package/dist/layout/semantic/route.js +23 -12
  41. package/dist/layout/types.d.ts +18 -0
  42. package/package.json +2 -2
@@ -28,6 +28,13 @@ export interface CompactElement {
28
28
  * optionally `headers`, `queryParameters`, `body`, `authentication.type`.
29
29
  */
30
30
  inputs?: Record<string, string>;
31
+ /** Zeebe output mappings (target→source), read like {@link inputs}. */
32
+ outputs?: Record<string, string>;
33
+ /**
34
+ * Marks a user task as a Camunda 8 native one (`zeebe:userTask`), which a linked
35
+ * form needs from Camunda 8.10.
36
+ */
37
+ nativeUserTask?: boolean;
31
38
  /** The element template applied to this element (`zeebe:modelerTemplate`). */
32
39
  modelerTemplate?: {
33
40
  id: string;
@@ -97,6 +104,12 @@ export interface CompactFlow {
97
104
  */
98
105
  isDefault?: boolean;
99
106
  }
107
+ /** A text annotation and the element it is associated with. */
108
+ export interface CompactNote {
109
+ /** The annotated element, at any depth of the process. */
110
+ elementId: string;
111
+ text: string;
112
+ }
100
113
  /** A single process in compact form. */
101
114
  export interface CompactProcess {
102
115
  id: string;
@@ -105,6 +118,12 @@ export interface CompactProcess {
105
118
  documentation?: string;
106
119
  elements: CompactElement[];
107
120
  flows: CompactFlow[];
121
+ /**
122
+ * Text annotations, each tied to an element by an association. {@link expand}
123
+ * puts them on the process and lays them out; {@link compactify} does not
124
+ * produce them.
125
+ */
126
+ notes?: CompactNote[];
108
127
  }
109
128
  /**
110
129
  * Token-efficient representation of a {@link BpmnDefinitions} document.
@@ -123,6 +142,11 @@ export interface CompactProcess {
123
142
  */
124
143
  export interface CompactDiagram {
125
144
  id: string;
145
+ /**
146
+ * The Camunda 8 version the diagram targets, such as `8.10.0`. {@link expand}
147
+ * writes it as `modeler:executionPlatformVersion`; without it none is written.
148
+ */
149
+ executionPlatformVersion?: string;
126
150
  processes: CompactProcess[];
127
151
  }
128
152
  /**
@@ -1,5 +1,7 @@
1
+ import { packAnnotations } from "../layout/annotations.js";
1
2
  import { layoutProcess } from "../layout/index.js";
2
3
  import { assertBpmnDefinitions, assertCompactDiagram } from "./argument-guards.js";
4
+ import { addAnnotationShapes } from "./auto-layout.js";
3
5
  import { restConnectorTaskType } from "./rest-connector.js";
4
6
  // ── Default flows ────────────────────────────────────────────────────────────
5
7
  /**
@@ -115,6 +117,18 @@ function compactifyElement(el) {
115
117
  }
116
118
  if (Object.keys(inputs).length > 0)
117
119
  result.inputs = inputs;
120
+ // `source: "= response"` is the job worker's result, which expand writes back from `resultVariable`.
121
+ const outputs = {};
122
+ for (const output of ext.find((e) => e.name === "zeebe:ioMapping")?.children ?? []) {
123
+ const { source, target } = output.attributes;
124
+ if (output.name !== "zeebe:output" || source === undefined || target === undefined)
125
+ continue;
126
+ if (result.jobType !== undefined && source === "= response")
127
+ continue;
128
+ outputs[target] = source;
129
+ }
130
+ if (Object.keys(outputs).length > 0)
131
+ result.outputs = outputs;
118
132
  const template = el.unknownAttributes["zeebe:modelerTemplate"];
119
133
  if (template) {
120
134
  const version = Number.parseInt(el.unknownAttributes["zeebe:modelerTemplateVersion"] ?? "", 10);
@@ -238,6 +252,8 @@ const EVENT_TYPES = new Set([
238
252
  function compactProblems(compact) {
239
253
  const problems = [];
240
254
  const seen = new Set();
255
+ /** Every element id, at any depth: what a note may name. */
256
+ const elementIds = new Set();
241
257
  const claim = (id, what) => {
242
258
  if (seen.has(id))
243
259
  problems.push(`duplicate id "${id}" (${what})`);
@@ -252,6 +268,7 @@ function compactProblems(compact) {
252
268
  }
253
269
  claim(el.id, el.type);
254
270
  ids.add(el.id);
271
+ elementIds.add(el.id);
255
272
  if (el.eventType !== undefined && !EVENT_TYPES.has(el.eventType)) {
256
273
  problems.push(`element "${el.id}" has unknown eventType "${el.eventType}" (expected one of ${[...EVENT_TYPES].join(", ")})`);
257
274
  }
@@ -280,6 +297,11 @@ function compactProblems(compact) {
280
297
  for (const process of compact.processes) {
281
298
  claim(process.id, "process");
282
299
  checkScope(process.elements, process.flows, `process "${process.id}"`);
300
+ for (const note of process.notes ?? []) {
301
+ if (!elementIds.has(note.elementId)) {
302
+ problems.push(`a note is on "${note.elementId}", which is not an element in the diagram`);
303
+ }
304
+ }
283
305
  }
284
306
  return problems;
285
307
  }
@@ -375,6 +397,9 @@ export function makeExtensions(el) {
375
397
  children: [],
376
398
  });
377
399
  }
400
+ if (el.nativeUserTask && el.type === "userTask") {
401
+ ext.push({ name: "zeebe:userTask", attributes: {}, children: [] });
402
+ }
378
403
  if (el.formId) {
379
404
  ext.push({ name: "zeebe:formDefinition", attributes: { formId: el.formId }, children: [] });
380
405
  }
@@ -400,7 +425,14 @@ export function makeExtensions(el) {
400
425
  attributes: { source, target },
401
426
  children: [],
402
427
  }));
403
- if (el.resultVariable && el.jobType && !el.decisionId && !isConnectorJobType(el.jobType)) {
428
+ for (const [target, source] of Object.entries(el.outputs ?? {})) {
429
+ ioMapping.push({ name: "zeebe:output", attributes: { source, target }, children: [] });
430
+ }
431
+ if (el.resultVariable &&
432
+ el.jobType &&
433
+ !el.decisionId &&
434
+ !isConnectorJobType(el.jobType) &&
435
+ el.outputs?.[el.resultVariable] === undefined) {
404
436
  // A job worker's result: map its `response` variable to the result variable
405
437
  ioMapping.push({
406
438
  name: "zeebe:output",
@@ -588,6 +620,24 @@ function buildDiagram(processId, process) {
588
620
  waypoints: e.waypoints,
589
621
  unknownAttributes: {},
590
622
  }));
623
+ if (process.textAnnotations.length > 0) {
624
+ // An annotation may sit above the topmost shape; the plane keeps to the positive quadrant.
625
+ const placed = packAnnotations(process, layout.nodes, layout.edges);
626
+ addAnnotationShapes(process, layout.nodes, placed, shapes, edges, 0, 0);
627
+ const dx = -Math.min(0, ...shapes.map((s) => s.bounds.x));
628
+ const dy = -Math.min(0, ...shapes.map((s) => s.bounds.y));
629
+ if (dx !== 0 || dy !== 0) {
630
+ for (const shape of shapes) {
631
+ shape.bounds = { ...shape.bounds, x: shape.bounds.x + dx, y: shape.bounds.y + dy };
632
+ const label = shape.label?.bounds;
633
+ if (label)
634
+ shape.label = { bounds: { ...label, x: label.x + dx, y: label.y + dy } };
635
+ }
636
+ for (const edge of edges) {
637
+ edge.waypoints = edge.waypoints.map((w) => ({ x: w.x + dx, y: w.y + dy }));
638
+ }
639
+ }
640
+ }
591
641
  return {
592
642
  id: `BPMNDiagram_${processId}`,
593
643
  plane: {
@@ -620,6 +670,23 @@ function expandProcess(compact) {
620
670
  extensionElements: [],
621
671
  unknownAttributes: {},
622
672
  }));
673
+ // Ids as the builder's `annotate` makes them, numbered per element
674
+ const textAnnotations = [];
675
+ const associations = [];
676
+ const noted = new Map();
677
+ for (const note of compact.notes ?? []) {
678
+ const n = (noted.get(note.elementId) ?? 0) + 1;
679
+ noted.set(note.elementId, n);
680
+ const id = `TextAnnotation_${note.elementId}_${n}`;
681
+ textAnnotations.push({ id, text: note.text, unknownAttributes: {} });
682
+ associations.push({
683
+ id: `Association_${note.elementId}_${n}`,
684
+ sourceRef: note.elementId,
685
+ targetRef: id,
686
+ associationDirection: "None",
687
+ unknownAttributes: {},
688
+ });
689
+ }
623
690
  const process = {
624
691
  id: compact.id,
625
692
  name: compact.name,
@@ -628,8 +695,8 @@ function expandProcess(compact) {
628
695
  extensionElements: [],
629
696
  flowElements,
630
697
  sequenceFlows,
631
- textAnnotations: [],
632
- associations: [],
698
+ textAnnotations,
699
+ associations,
633
700
  groups: [],
634
701
  unknownAttributes: {},
635
702
  };
@@ -664,6 +731,7 @@ export function expand(compact) {
664
731
  processes.push(process);
665
732
  diagrams.push(diagram);
666
733
  }
734
+ const platform = compact.executionPlatformVersion;
667
735
  return {
668
736
  id: compact.id,
669
737
  targetNamespace: "http://bpmn.io/schema/bpmn",
@@ -673,8 +741,14 @@ export function expand(compact) {
673
741
  dc: "http://www.omg.org/spec/DD/20100524/DC",
674
742
  di: "http://www.omg.org/spec/DD/20100524/DI",
675
743
  zeebe: "http://camunda.org/schema/zeebe/1.0",
744
+ ...(platform === undefined ? {} : { modeler: "http://camunda.org/schema/modeler/1.0" }),
676
745
  },
677
- unknownAttributes: {},
746
+ unknownAttributes: platform === undefined
747
+ ? {}
748
+ : {
749
+ "modeler:executionPlatform": "Camunda Cloud",
750
+ "modeler:executionPlatformVersion": platform,
751
+ },
678
752
  errors: [],
679
753
  escalations: [],
680
754
  messages: [],
@@ -92,6 +92,9 @@ const PATCH_EXTENSIONS = [
92
92
  ["calledProcess", "zeebe:calledElement"],
93
93
  ["decisionId", "zeebe:calledDecision"],
94
94
  ["script", "zeebe:script"],
95
+ ["inputs", "zeebe:ioMapping"],
96
+ ["outputs", "zeebe:ioMapping"],
97
+ ["nativeUserTask", "zeebe:userTask"],
95
98
  ["taskHeaders", "zeebe:taskHeaders"],
96
99
  ];
97
100
  /**
@@ -134,6 +137,17 @@ function setTaskHeaders(element, headers) {
134
137
  children: [],
135
138
  }));
136
139
  }
140
+ /** Sets the named mappings of one kind, keeping the others of the `zeebe:ioMapping`. */
141
+ function setMappings(element, kind, mappings) {
142
+ const ioMapping = ensureExtension(element, "zeebe:ioMapping");
143
+ for (const [target, source] of Object.entries(mappings)) {
144
+ const existing = ioMapping.children.find((child) => child.name === kind && child.attributes.target === target);
145
+ if (existing)
146
+ existing.attributes.source = source;
147
+ else
148
+ ioMapping.children.push({ name: kind, attributes: { source, target }, children: [] });
149
+ }
150
+ }
137
151
  /**
138
152
  * Points a service task's result at a variable, keeping the rest of its
139
153
  * `zeebe:ioMapping`. On a business rule task the result variable lives on
@@ -208,6 +222,12 @@ function patchElement(element, patch) {
208
222
  }
209
223
  if (patch.resultVariable !== undefined)
210
224
  setResultVariable(element, patch.resultVariable);
225
+ if (patch.inputs !== undefined)
226
+ setMappings(element, "zeebe:input", patch.inputs);
227
+ if (patch.outputs !== undefined)
228
+ setMappings(element, "zeebe:output", patch.outputs);
229
+ if (patch.nativeUserTask && element.type === "userTask")
230
+ ensureExtension(element, "zeebe:userTask");
211
231
  if (patch.taskHeaders !== undefined)
212
232
  setTaskHeaders(element, patch.taskHeaders);
213
233
  if (patch.eventType !== undefined && "eventDefinitions" in element) {
@@ -75,7 +75,7 @@ export function analyzePatterns(p) {
75
75
  findings.push({
76
76
  id: "pattern/gateway-no-default-flow",
77
77
  category: "pattern",
78
- severity: "error",
78
+ severity: "warning",
79
79
  message: `Exclusive gateway "${el.name ?? el.id}" has no default sequence flow.`,
80
80
  suggestion: "Add a default flow to ensure the process does not get stuck when no condition matches.",
81
81
  processId,
@@ -91,7 +91,7 @@ export function analyzePatterns(p) {
91
91
  findings.push({
92
92
  id: "pattern/subprocess-no-error-boundary",
93
93
  category: "pattern",
94
- severity: "error",
94
+ severity: "warning",
95
95
  message: `Sub-process "${el.name ?? el.id}" has no error boundary event.`,
96
96
  suggestion: "Add an error boundary event to catch unhandled errors thrown inside the sub-process.",
97
97
  processId,
@@ -2,5 +2,6 @@ import type { BpmnProcess } from "../bpmn-model.js";
2
2
  import type { OptimizationFinding } from "./types.js";
3
3
  /** Extract variable names referenced in a FEEL expression string. */
4
4
  export declare function extractFeelIdentifiers(expression: string): string[];
5
+ export declare function levenshtein(a: string, b: string): number;
5
6
  export declare function analyzeVariableFlow(p: BpmnProcess): OptimizationFinding[];
6
7
  //# sourceMappingURL=variable-flow.d.ts.map
@@ -199,7 +199,7 @@ export function extractFeelIdentifiers(expression) {
199
199
  // ---------------------------------------------------------------------------
200
200
  // Levenshtein distance (for typo suggestions)
201
201
  // ---------------------------------------------------------------------------
202
- function levenshtein(a, b) {
202
+ export function levenshtein(a, b) {
203
203
  const m = a.length;
204
204
  const n = b.length;
205
205
  // Flat row buffers — avoids noUncheckedIndexedAccess issues with 2D arrays
@@ -29,7 +29,7 @@ export declare const FIXED_KINDS: Readonly<Record<string, BpmnElementType>>;
29
29
  * after {@link PROCESS_TEXT_GUIDE}. A test parses its example and expects no
30
30
  * problems.
31
31
  */
32
- export declare const PROCESS_DELTA_GUIDE = "Change script \u2014 write only what changes, one line each:\na > new[kind Name] > b add nodes and flows; an existing node is written by its id only\na >(Label: condition) b add a flow; restating an existing flow with a new label changes it\nx[kind Name] an existing id declared again changes its kind or name\n- a > b remove the flow from a to b\n- x remove node x and its flows\n@2 x y feedback item 2 is answered by the changes to x and y\nRules:\n- Use the ids of the diagram you were given. Never repeat a line that changes nothing.\n- A new node written between two connected nodes (a > new > b) replaces the flow a > b.\n- Removing a node with one way in and one way out joins the two.\n- End with one @ line for each feedback item you answered.\n\nExample:\ncheck > second[user Second approval] > pay\nreview[user Review application]\n- notify\n@1 second\n@2 review";
32
+ export declare const PROCESS_DELTA_GUIDE = "Change script \u2014 write only what changes, one line each:\na > new[kind Name] > b add nodes and flows; an existing node is written by its id only\na >(Label: condition) b add a flow; restating an existing flow with a new label changes it\nx[kind Name] an existing id declared again changes its kind or name\nx[user Name | form=f in.a=b] form and in./out. mappings (FEEL; write a = 1 with spaces) go after the bar\n- a > b remove the flow from a to b\n- x remove node x and its flows\n@2 x y feedback item 2 is answered by the changes to x and y\nRules:\n- Use the ids of the diagram you were given. Never repeat a line that changes nothing.\n- A new node written between two connected nodes (a > new > b) replaces the flow a > b.\n- Removing a node with one way in and one way out joins the two.\n- End with one @ line for each feedback item you answered.\n\nExample:\ncheck > second[user Second approval] > pay\nreview[user Review application]\n- notify\n@1 second\n@2 review";
33
33
  /** A node the script declares: a new one, or a change to an existing one. */
34
34
  export interface DeltaNode {
35
35
  /** The id as written. */
@@ -47,6 +47,14 @@ export interface DeltaNode {
47
47
  script?: string;
48
48
  /** The variable a script task's or a job's result goes to, from `result=`. */
49
49
  resultVariable?: string;
50
+ /** The linked form, from `form=`. */
51
+ formId?: string;
52
+ /** Input mappings (target to FEEL with its leading `=`), from `in.<target>=`. */
53
+ inputs?: Record<string, string>;
54
+ /** Output mappings, from `out.<target>=`. */
55
+ outputs?: Record<string, string>;
56
+ /** The ad-hoc sub-process the node lives in, from `inside=`. */
57
+ inside?: string;
50
58
  /** `nonint`: a non-interrupting boundary or start event. */
51
59
  interrupting?: false;
52
60
  line: number;
@@ -81,6 +89,18 @@ export interface ProcessDelta {
81
89
  }[];
82
90
  /** `with` lines: connector configuration for a node, existing or new. */
83
91
  connectors: ConnectorLine[];
92
+ /** `note` lines: a text annotation for a node, existing or new. */
93
+ notes: {
94
+ id: string;
95
+ text: string;
96
+ line: number;
97
+ }[];
98
+ /** `doc` lines: the documentation of a node, existing or new. */
99
+ docs: {
100
+ id: string;
101
+ text: string;
102
+ line: number;
103
+ }[];
84
104
  /** Lines, or parts of lines, that were left out. */
85
105
  problems: ProcessTextProblem[];
86
106
  }
@@ -16,14 +16,13 @@
16
16
  * @packageDocumentation
17
17
  */
18
18
  import { CONNECTOR_LINE, parseConnectorLine } from "./connector-line.js";
19
- import { ALIASES, KINDS, TRIGGERS, edgeLabel, splitFeel, tokenizePath, } from "./process-text.js";
19
+ import { ALIASES, DOC_LINE, KINDS, NOTE_LINE, TRIGGERS, edgeLabel, splitFeel, splitMappings, tokenizePath, } from "./process-text.js";
20
20
  /**
21
21
  * Kind words the writer uses for element types the line format cannot create.
22
22
  * A script may restate them on an existing node; it cannot declare a new one.
23
23
  */
24
24
  export const FIXED_KINDS = {
25
25
  sub: "subProcess",
26
- adhoc: "adHocSubProcess",
27
26
  transaction: "transaction",
28
27
  complex: "complexGateway",
29
28
  };
@@ -36,6 +35,7 @@ export const PROCESS_DELTA_GUIDE = `Change script — write only what changes, o
36
35
  a > new[kind Name] > b add nodes and flows; an existing node is written by its id only
37
36
  a >(Label: condition) b add a flow; restating an existing flow with a new label changes it
38
37
  x[kind Name] an existing id declared again changes its kind or name
38
+ x[user Name | form=f in.a=b] form and in./out. mappings (FEEL; write a = 1 with spaces) go after the bar
39
39
  - a > b remove the flow from a to b
40
40
  - x remove node x and its flows
41
41
  @2 x y feedback item 2 is answered by the changes to x and y
@@ -85,7 +85,13 @@ function readSpec(id, spec, line, problems) {
85
85
  problems.push({ line, message: `unknown trigger "${trigger}" for "${id}"; ignored` });
86
86
  }
87
87
  }
88
- const { plain, feel } = splitFeel(attrs);
88
+ const split = splitFeel(attrs);
89
+ const { feel } = split;
90
+ const { plain, mappings } = splitMappings(split.plain);
91
+ for (const { direction, target, value } of mappings) {
92
+ const key = direction === "in" ? "inputs" : "outputs";
93
+ node[key] = { ...node[key], [target]: value.startsWith("=") ? value : `=${value}` };
94
+ }
89
95
  if (feel !== undefined) {
90
96
  // A step that evaluates FEEL is a script task
91
97
  if (node.type === undefined || node.type === "task")
@@ -100,6 +106,10 @@ function readSpec(id, spec, line, problems) {
100
106
  node.jobType = value;
101
107
  else if (key === "result" && value)
102
108
  node.resultVariable = value;
109
+ else if (key === "form" && value)
110
+ node.formId = value;
111
+ else if (key === "inside" && value)
112
+ node.inside = value;
103
113
  else if (key === "nonint" && value === undefined)
104
114
  node.interrupting = false;
105
115
  else
@@ -122,6 +132,8 @@ export function parseProcessDelta(text) {
122
132
  removedFlows: [],
123
133
  addressed: [],
124
134
  connectors: [],
135
+ notes: [],
136
+ docs: [],
125
137
  problems: [],
126
138
  };
127
139
  const declared = new Map();
@@ -243,6 +255,24 @@ export function parseProcessDelta(text) {
243
255
  delta.connectors.push(connector);
244
256
  return;
245
257
  }
258
+ const note = NOTE_LINE.exec(line);
259
+ if (note) {
260
+ const text = (note[2] ?? "").trim();
261
+ if (text === "")
262
+ delta.problems.push({ line: n, message: `note ${note[1]}: has no text; ignored` });
263
+ else
264
+ delta.notes.push({ id: note[1], text, line: n });
265
+ return;
266
+ }
267
+ const doc = DOC_LINE.exec(line);
268
+ if (doc) {
269
+ const text = (doc[2] ?? "").trim();
270
+ if (text === "")
271
+ delta.problems.push({ line: n, message: `doc ${doc[1]}: has no text; ignored` });
272
+ else
273
+ delta.docs.push({ id: doc[1], text, line: n });
274
+ return;
275
+ }
246
276
  // `- x` removes; `-> x` is an arrow a model wrote at the start of a line.
247
277
  const removed = /^-(?![->])\s*(.*)$/.exec(line);
248
278
  if (removed) {
@@ -18,7 +18,7 @@
18
18
  import { assertBpmnDefinitions } from "./argument-guards.js";
19
19
  import { compactify } from "./compact.js";
20
20
  import { FIXED_KINDS } from "./process-delta.js";
21
- import { KINDS } from "./process-text.js";
21
+ import { KINDS, splitMappings } from "./process-text.js";
22
22
  const KIND_WORDS = new Map([...Object.entries(KINDS), ...Object.entries(FIXED_KINDS)].map(([word, type]) => [type, word]));
23
23
  /** Ids kept as they are: short, lowercase, and readable. */
24
24
  const READABLE_ID = /^[a-z][a-z0-9_]{0,23}$/;
@@ -45,6 +45,19 @@ export function writableLabel(name) {
45
45
  export function writableCondition(condition) {
46
46
  return condition.replace(/^\s*=/, "").replace(/\s+/g, " ").trim();
47
47
  }
48
+ /** A mapping source as FEEL on one line; a literal (no leading `=`) is written as a string. */
49
+ function writableMapping(source) {
50
+ if (!source.startsWith("="))
51
+ return JSON.stringify(source);
52
+ return source.replace(/^=\s*/, "").replace(/\s+/g, " ").trim();
53
+ }
54
+ function platformVersion(definitions) {
55
+ const platform = definitions.unknownAttributes["modeler:executionPlatform"];
56
+ if (!platform?.toLowerCase().includes("cloud"))
57
+ return undefined;
58
+ const version = /^\s*(\d+\.\d+)/.exec(definitions.unknownAttributes["modeler:executionPlatformVersion"] ?? "");
59
+ return version?.[1];
60
+ }
48
61
  function aliasFor(element, taken) {
49
62
  if (READABLE_ID.test(element.id) && !taken.has(element.id)) {
50
63
  taken.add(element.id);
@@ -65,17 +78,34 @@ function aliasFor(element, taken) {
65
78
  taken.add(alias);
66
79
  return alias;
67
80
  }
68
- function spec(element, host) {
81
+ function spec(element, host, container) {
69
82
  const word = KIND_WORDS.get(element.type) ?? "task";
70
83
  const trigger = element.eventType ? `:${element.eventType}` : "";
71
84
  const name = element.name ? ` ${writableName(element.name)}` : "";
72
85
  const attrs = [];
73
86
  if (host !== undefined)
74
87
  attrs.push(`on=${host}`);
88
+ if (container !== undefined)
89
+ attrs.push(`inside=${container}`);
75
90
  if (element.interrupting === false)
76
91
  attrs.push("nonint");
77
92
  if (element.jobType)
78
93
  attrs.push(`job=${element.jobType}`);
94
+ if (element.formId)
95
+ attrs.push(`form=${element.formId}`);
96
+ // Mapping values run to the next ` word=`, so they are written before result= and feel=
97
+ for (const [direction, mappings] of [
98
+ ["in", element.inputs],
99
+ ["out", element.outputs],
100
+ ]) {
101
+ for (const [target, source] of Object.entries(mappings ?? {})) {
102
+ const written = `${direction}.${target}=${writableMapping(source)}`;
103
+ // A target with a space, or a value that reads back as another attribute, cannot be written
104
+ const back = splitMappings(written);
105
+ if (back.plain.trim() === "" && back.mappings.length === 1)
106
+ attrs.push(written);
107
+ }
108
+ }
79
109
  if (element.script) {
80
110
  // Last: feel= takes the rest of the attributes
81
111
  if (element.resultVariable)
@@ -120,13 +150,25 @@ export function writeProcessText(definitions, options = {}) {
120
150
  const outgoing = new Map();
121
151
  for (const flow of flows)
122
152
  outgoing.set(flow.from, [...(outgoing.get(flow.from) ?? []), flow]);
153
+ // Tasks inside an ad-hoc sub-process: written on lines of their own, without flows.
154
+ const inner = new Map();
155
+ for (const el of elements) {
156
+ if (el.type !== "adHocSubProcess")
157
+ continue;
158
+ for (const child of el.children?.elements ?? []) {
159
+ if (KIND_WORDS.has(child.type) && child.type !== "boundaryEvent" && !byId.has(child.id)) {
160
+ inner.set(child.id, { element: child, container: el.id });
161
+ }
162
+ }
163
+ }
123
164
  const taken = new Set();
124
165
  const alias = new Map();
125
166
  // Readable ids first, so a name-derived alias never takes one of them.
126
- for (const el of elements)
167
+ const named = [...elements, ...[...inner.values()].map((child) => child.element)];
168
+ for (const el of named)
127
169
  if (READABLE_ID.test(el.id))
128
170
  alias.set(el.id, aliasFor(el, taken));
129
- for (const el of elements)
171
+ for (const el of named)
130
172
  if (!alias.has(el.id))
131
173
  alias.set(el.id, aliasFor(el, taken));
132
174
  const declared = new Set();
@@ -138,9 +180,20 @@ export function writeProcessText(definitions, options = {}) {
138
180
  declared.add(id);
139
181
  return `${written}${spec(el, el.attachedTo === undefined ? undefined : alias.get(el.attachedTo))}`;
140
182
  };
183
+ /** A task inside an ad-hoc sub-process, declared with `inside=` on a line of its own. */
184
+ const inside = (id) => {
185
+ const child = inner.get(id);
186
+ if (!child || declared.has(id))
187
+ return alias.get(id) ?? id;
188
+ declared.add(id);
189
+ return `${alias.get(id)}${spec(child.element, undefined, alias.get(child.container))}`;
190
+ };
141
191
  const lines = [];
142
- if (process.name)
143
- lines.push(`# ${writableName(process.name)}`);
192
+ const camunda = platformVersion(definitions);
193
+ if (process.name || camunda) {
194
+ const title = process.name ? writableName(process.name) : "";
195
+ lines.push(`#${title ? ` ${title}` : ""}${camunda ? ` | camunda=${camunda}` : ""}`);
196
+ }
144
197
  const written = new Set();
145
198
  const expanded = new Set();
146
199
  const queue = [];
@@ -191,6 +244,27 @@ export function writeProcessText(definitions, options = {}) {
191
244
  if (!declared.has(el.id))
192
245
  lines.push(ref(el.id));
193
246
  }
247
+ for (const id of inner.keys())
248
+ lines.push(inside(id));
249
+ // Documentation, on one line like a note: it is the tool description of an agent's tool
250
+ for (const el of named) {
251
+ const text = el.documentation?.replace(/\s+/g, " ").trim();
252
+ if (text)
253
+ lines.push(`doc ${alias.get(el.id)}: ${text}`);
254
+ }
255
+ // A note names an element it is associated with; one tied to nothing the format writes has no line.
256
+ const source = definitions.processes[0];
257
+ const annotations = new Map((source?.textAnnotations ?? []).map((a) => [a.id, a.text ?? ""]));
258
+ for (const assoc of source?.associations ?? []) {
259
+ const [annotation, target] = annotations.has(assoc.targetRef)
260
+ ? [assoc.targetRef, assoc.sourceRef]
261
+ : [assoc.sourceRef, assoc.targetRef];
262
+ const text = (annotations.get(annotation) ?? "").replace(/\s+/g, " ").trim();
263
+ const written = alias.get(target);
264
+ if (annotations.has(annotation) && written !== undefined && text !== "") {
265
+ lines.push(`note ${written}: ${text}`);
266
+ }
267
+ }
194
268
  if (options.connectorLine) {
195
269
  const real = new Map((definitions.processes[0]?.flowElements ?? []).map((el) => [el.id, el]));
196
270
  for (const el of elements) {
@@ -29,7 +29,7 @@ import { type ConnectorLine } from "./connector-line.js";
29
29
  * It lives beside the parser so the two cannot drift: a test parses its example
30
30
  * and expects no problems.
31
31
  */
32
- export declare const PROCESS_TEXT_GUIDE = "Format \u2014 one path per line, nothing else:\n# Process name (first line)\na > b > c sequence flow\nid[kind Name] declare a node the first time it appears; afterwards write only id\ngw >(Label: condition) x conditional branch, condition in FEEL (amount > 1000, status = \"ok\")\ngw >(Label: default) y branch taken when no condition holds\nKinds: 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\nEvents take a trigger: start:message end:error catch:timer boundary:error (timer message signal error escalation terminate conditional compensate cancel)\nAttributes 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)\nRules:\n- One start event. Every node is on a path from it to an end event: never a node nothing leads to.\n- An xor has two or more branches: exactly one is (Label: default), each other has a FEEL condition.\n- A boundary starts its own line, on a task you declared, and leads to a task that handles it; never draw an arrow into a boundary.\n- A boundary leads only to the handling. What happens next when nothing fails follows the task itself (read > count), never the boundary.\n- A step that only works on process data (count, sum, filter, compare, pick, format a message) is a script task, never a service or plain task: its FEEL reads the variables earlier steps set with result=. read[service Read issues | result=issues] > count[script Count open issues | result=openCount feel=count(issues[state = \"open\"])]\n- Branches that meet again are joined automatically; join parallel branches with an and node.\n- Steps done at the same time start from an and node and meet at another. A deadline is a boundary:timer with after= on the task that may run late. A step done for every item of a list takes each=<list>; use it only when the description says every or each.\n\nExample:\n# Expense approval\nstart[start Expense submitted] > check[xor Amount over 1000?]\ncheck >(Yes: amount > 1000) review[user Review expense] > pay[service Pay expense] > done[end Expense paid]\ncheck >(No: default) auto[service Approve automatically] > pay\nfailed[boundary:error Payment failed | on=pay] > notify[send Notify submitter] > notice[end Payment failed]";
32
+ export declare const PROCESS_TEXT_GUIDE = "Format \u2014 one path per line, nothing else:\n# Process name (first line; add \" | camunda=8.10\" to target a Camunda version)\na > b > c sequence flow\nid[kind Name] declare a node the first time it appears; afterwards write only id\ngw >(Label: condition) x conditional branch, condition in FEEL (amount > 1000, status = \"ok\")\ngw >(Label: default) y branch taken when no condition holds\nKinds: 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)\nEvents take a trigger: start:message end:error catch:timer boundary:error (timer message signal error escalation terminate conditional compensate cancel)\nAttributes 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)\nAlso 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)\nAd-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\ndoc <id>: text the element's documentation; for a tool inside an ad-hoc agent it is the description the agent chooses the tool by\nAd-hoc example:\nask[start Question asked] > agent[adhoc Answer with tools] > review[user Review answer] > done[end Answered]\nusers[service Look up users | inside=agent]\ndoc users: Returns the list of sample users\nnote agent: Picks a tool by its description\nRules:\n- One start event. Every node is on a path from it to an end event: never a node nothing leads to.\n- An xor has two or more branches: exactly one is (Label: default), each other has a FEEL condition.\n- A boundary starts its own line, on a task you declared, and leads to a task that handles it; never draw an arrow into a boundary.\n- A boundary leads only to the handling. What happens next when nothing fails follows the task itself (read > count), never the boundary.\n- A step that only works on process data (count, sum, filter, compare, pick, format a message) is a script task, never a service or plain task: its FEEL reads the variables earlier steps set with result=. read[service Read issues | result=issues] > count[script Count open issues | result=openCount feel=count(issues[state = \"open\"])]\n- Branches that meet again are joined automatically; join parallel branches with an and node.\n- Steps done at the same time start from an and node and meet at another. A deadline is a boundary:timer with after= on the task that may run late. A step done for every item of a list takes each=<list>; use it only when the description says every or each.\n\nExample:\n# Expense approval\nstart[start Expense submitted] > check[xor Amount over 1000?]\ncheck >(Yes: amount > 1000) review[user Review expense] > pay[service Pay expense] > done[end Expense paid]\ncheck >(No: default) auto[service Approve automatically] > pay\nfailed[boundary:error Payment failed | on=pay] > notify[send Notify submitter] > notice[end Payment failed]";
33
33
  /** A line, or part of one, that {@link parseProcessText} could not use. */
34
34
  export interface ProcessTextProblem {
35
35
  /** 1-based line number in the text. */
@@ -83,6 +83,10 @@ export declare const KINDS: Record<string, BpmnElementType>;
83
83
  export declare const ALIASES: Record<string, BpmnElementType>;
84
84
  export declare const TRIGGERS: Set<string>;
85
85
  export declare const EVENTS: Set<BpmnElementType>;
86
+ /** `note <id>: text`, which is not a path and may hold any characters. */
87
+ export declare const NOTE_LINE: RegExp;
88
+ /** `doc <id>: text`, the element's documentation; free text like a note. */
89
+ export declare const DOC_LINE: RegExp;
86
90
  /**
87
91
  * Splits `feel=` off a declaration's attributes. A FEEL expression has spaces and
88
92
  * commas, so it takes the rest of them: `| result=open feel=count(issues[state = "open"])`.
@@ -93,6 +97,23 @@ export declare function splitFeel(attrs: string): {
93
97
  plain: string;
94
98
  feel?: string;
95
99
  };
100
+ /**
101
+ * Takes the `in.<target>=<FEEL>` and `out.<target>=<FEEL>` mappings off a declaration's
102
+ * attributes. A value runs up to the next ` <word>=` or the end, so it may hold spaces,
103
+ * commas and `=` spaced as FEEL comparison is written (`if a = 1 then …`); an unspaced
104
+ * ` a=1` inside it reads as the next attribute. Call {@link splitFeel} first: `feel=`
105
+ * is last and takes the rest, mappings included.
106
+ *
107
+ * @returns The other attributes, and each mapping's target and FEEL, in order.
108
+ */
109
+ export declare function splitMappings(attrs: string): {
110
+ plain: string;
111
+ mappings: {
112
+ direction: "in" | "out";
113
+ target: string;
114
+ value: string;
115
+ }[];
116
+ };
96
117
  /** A path line split into its parts. */
97
118
  export interface PathTokens {
98
119
  /** The nodes in the order written, each with the bracket text it was declared with, if any. */