@bpmnkit/core 0.7.1 → 1.0.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.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  [![license](https://img.shields.io/npm/l/@bpmnkit/core?style=flat-square)](https://github.com/bpmnkit/monorepo/blob/main/LICENSE)
8
8
  [![typescript](https://img.shields.io/badge/TypeScript-strict-6244d7?style=flat-square&logo=typescript&logoColor=white)](https://github.com/bpmnkit/monorepo)
9
9
  [![ai-assisted](https://img.shields.io/badge/AI--assisted-claude-8b5cf6?style=flat-square)](https://github.com/bpmnkit/monorepo)
10
- [![experimental](https://img.shields.io/badge/status-experimental-f59e0b?style=flat-square)](https://github.com/bpmnkit/monorepo)
10
+ [![stable](https://img.shields.io/badge/status-stable-16a34a?style=flat-square)](https://bpmnkit.com/docs/getting-started/stability)
11
11
 
12
12
  [Website](https://bpmnkit.com) · [Documentation](https://bpmnkit.com/docs) · [GitHub](https://github.com/bpmnkit/monorepo) · [Changelog](https://github.com/bpmnkit/monorepo/blob/main/packages/core/CHANGELOG.md)
13
13
  </div>
@@ -205,6 +205,29 @@ const restored = expand(JSON.parse(json))
205
205
  const outXml = Bpmn.export(restored)
206
206
  ```
207
207
 
208
+ ### Rendering while the model is still writing
209
+
210
+ A model emits a diagram one token at a time, and the outermost `}` — the one
211
+ `JSON.parse` waits for — is the last character it sends. `createCompactStream`
212
+ reads the elements out of the text as their own literals close, so there is
213
+ something to draw long before the document is finished:
214
+
215
+ ```typescript
216
+ import { createCompactStream } from "@bpmnkit/core"
217
+
218
+ // `base` is the diagram being edited, so a frame shows the whole thing rather
219
+ // than the fragment the model is adding to it. Omit it to build from nothing.
220
+ const diagramStream = createCompactStream({ base: null })
221
+
222
+ function onModelChunk(chunk: string): void {
223
+ const frame = diagramStream.push(chunk) // null until the frame changes
224
+ if (frame) console.log("elements so far:", frame.processes[0]?.flowElements.length)
225
+ }
226
+ ```
227
+
228
+ Frames are a guess at an unfinished document: `push` never throws, drops what it
229
+ cannot place, and expects the caller to have an authoritative result coming.
230
+
208
231
  ## API Reference
209
232
 
210
233
  ### BPMN
@@ -301,6 +324,7 @@ const { semanticHash, changes } = await writeBpmn(defs, { output: "flow.bpmn" })
301
324
  | `optimize(defs)` | Run all optimization rules; returns `OptimizeReport` |
302
325
  | `compactify(defs)` | Convert to compact `CompactDiagram` |
303
326
  | `expand(compact)` | Restore full `BpmnDefinitions` |
327
+ | `createCompactStream(opts?)` | Read a diagram out of a model's token stream, frame by frame |
304
328
  | `generateId(prefix)` | Generate a unique short ID |
305
329
 
306
330
  ---
@@ -159,16 +159,6 @@ export interface BuildOptions {
159
159
  * that cannot see what it did not emit.
160
160
  */
161
161
  explicitJoins?: boolean;
162
- /**
163
- * The former name for {@link BuildOptions.explicitJoins}, still honoured.
164
- *
165
- * Renamed because "strict" says nothing about what it is strict *about*, and
166
- * because `applyBpmnOperations` takes a `strict` that means something else
167
- * entirely — whether to throw or report problems.
168
- *
169
- * @deprecated Use `explicitJoins`.
170
- */
171
- strict?: boolean;
172
162
  }
173
163
  /** Options for a collaboration participant (a pool). */
174
164
  export interface ParticipantOptions {
@@ -842,8 +832,7 @@ export declare class ProcessBuilder {
842
832
  * says: inference reads the whole topology, and on a document you were handed
843
833
  * that means rewriting edges you never touched.
844
834
  *
845
- * @param options - `explicitJoins` refuses inferred join gateways. `strict` is
846
- * the former name for it and still works.
835
+ * @param options - `explicitJoins` refuses inferred join gateways.
847
836
  */
848
837
  build(options?: BuildOptions): BpmnDefinitions;
849
838
  /**
@@ -2161,8 +2161,7 @@ export class ProcessBuilder {
2161
2161
  * says: inference reads the whole topology, and on a document you were handed
2162
2162
  * that means rewriting edges you never touched.
2163
2163
  *
2164
- * @param options - `explicitJoins` refuses inferred join gateways. `strict` is
2165
- * the former name for it and still works.
2164
+ * @param options - `explicitJoins` refuses inferred join gateways.
2166
2165
  */
2167
2166
  build(options) {
2168
2167
  this.resolvePendingSplice();
@@ -2174,7 +2173,7 @@ export class ProcessBuilder {
2174
2173
  // that needs a join here means saying so with `.connectTo(joinId)`.
2175
2174
  if (this._source === undefined)
2176
2175
  insertJoinGateways(this.flowElements, this.sequenceFlows);
2177
- const explicitJoins = options?.explicitJoins ?? options?.strict ?? false;
2176
+ const explicitJoins = options?.explicitJoins ?? false;
2178
2177
  if (explicitJoins && this.flowElements.length > beforeCount) {
2179
2178
  const inserted = this.flowElements
2180
2179
  .slice(beforeCount)
@@ -1343,7 +1343,7 @@ class ShapeFrame extends Frame {
1343
1343
  finish() {
1344
1344
  const attrs = this.attrs;
1345
1345
  if (!this.bounds)
1346
- throw new Error(`Missing <dc:Bounds> in shape "${attr(attrs, "id")}"`);
1346
+ throw new ParseError(`Missing <dc:Bounds> in shape "${attr(attrs, "id")}"`);
1347
1347
  this.target.push({
1348
1348
  id: requiredAttr(attrs, "id", this.name),
1349
1349
  bpmnElement: requiredAttr(attrs, "bpmnElement", this.name),
@@ -1451,7 +1451,7 @@ class DiagramFrame extends Frame {
1451
1451
  finish() {
1452
1452
  const plane = this.plane;
1453
1453
  if (!plane)
1454
- throw new Error("Missing <bpmndi:BPMNPlane> in diagram");
1454
+ throw new ParseError("Missing <bpmndi:BPMNPlane> in diagram");
1455
1455
  this.target.push({
1456
1456
  id: requiredAttr(this.attrs, "id", this.name),
1457
1457
  plane: {
@@ -1596,9 +1596,9 @@ class BpmnSink {
1596
1596
  export function parseBpmn(xml) {
1597
1597
  const sink = new BpmnSink();
1598
1598
  if (!scanXml(xml, sink))
1599
- throw new Error("Failed to parse XML: no root element found");
1599
+ throw new ParseError("Failed to parse XML: no root element found");
1600
1600
  if (sink.rootName !== undefined) {
1601
- throw new Error(`Expected <definitions> root element, got <${sink.rootName}>`);
1601
+ throw new ParseError(`Expected <definitions> root element, got <${sink.rootName}>`);
1602
1602
  }
1603
1603
  return sink.result;
1604
1604
  }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The diagram a model is writing, read out of the tokens as they arrive.
3
+ *
4
+ * A language model emits a diagram one character at a time, so the shape of a
5
+ * process is knowable long before its last token. Nothing downstream can use a
6
+ * half-written document, though: `JSON.parse` wants the closing brace, and the
7
+ * outermost one — the tool argument's own wrapper — is the very last character
8
+ * sent.
9
+ *
10
+ * So this does not parse the document. It picks complete `{…}` object literals
11
+ * out of the text as they close and keeps the ones shaped like a
12
+ * {@link CompactElement} or a {@link CompactFlow}, which are the innermost
13
+ * objects and therefore the first to finish. That is also what makes it
14
+ * indifferent to what it is reading: a `replace_diagram` argument, a ```json
15
+ * block in an assistant's prose, or the body of a `compose_diagram` snippet all
16
+ * carry the same literals, and none of them have to be valid as a whole.
17
+ *
18
+ * **Frames are advisory.** Everything here is a guess at an unfinished
19
+ * document, and the caller is expected to have an authoritative result coming.
20
+ * That is what lets it drop what it cannot place instead of reporting an error,
21
+ * and why it never throws on input.
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+ import type { BpmnDefinitions } from "./bpmn-model.js";
26
+ import type { CompactDiagram } from "./compact.js";
27
+ /** Options for {@link createCompactStream}. */
28
+ export interface CompactStreamOptions {
29
+ /**
30
+ * The diagram being edited.
31
+ *
32
+ * A model changing an existing process streams only what it is adding, so
33
+ * without this a frame is a disconnected fragment rather than the diagram
34
+ * with the fragment in it. Only the first process is previewed; a frame is
35
+ * one process, whatever the document turns out to hold.
36
+ */
37
+ base?: CompactDiagram | null;
38
+ }
39
+ /** A diagram assembled from a text stream. See {@link createCompactStream}. */
40
+ export interface CompactStream {
41
+ /**
42
+ * Adds the next piece of text.
43
+ *
44
+ * @returns The diagram as it now stands, or `null` when this chunk added
45
+ * nothing renderable — no new element, or not enough for a diagram yet.
46
+ */
47
+ push(chunk: string): BpmnDefinitions | null;
48
+ }
49
+ /**
50
+ * Reads a diagram out of a stream of text.
51
+ *
52
+ * @param options - See {@link CompactStreamOptions}.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const stream = createCompactStream({ base: currentDiagram })
57
+ * for await (const chunk of tokens) {
58
+ * const defs = stream.push(chunk)
59
+ * if (defs) render(defs)
60
+ * }
61
+ * ```
62
+ */
63
+ export declare function createCompactStream(options?: CompactStreamOptions): CompactStream;
64
+ //# sourceMappingURL=compact-stream.d.ts.map
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The diagram a model is writing, read out of the tokens as they arrive.
3
+ *
4
+ * A language model emits a diagram one character at a time, so the shape of a
5
+ * process is knowable long before its last token. Nothing downstream can use a
6
+ * half-written document, though: `JSON.parse` wants the closing brace, and the
7
+ * outermost one — the tool argument's own wrapper — is the very last character
8
+ * sent.
9
+ *
10
+ * So this does not parse the document. It picks complete `{…}` object literals
11
+ * out of the text as they close and keeps the ones shaped like a
12
+ * {@link CompactElement} or a {@link CompactFlow}, which are the innermost
13
+ * objects and therefore the first to finish. That is also what makes it
14
+ * indifferent to what it is reading: a `replace_diagram` argument, a ```json
15
+ * block in an assistant's prose, or the body of a `compose_diagram` snippet all
16
+ * carry the same literals, and none of them have to be valid as a whole.
17
+ *
18
+ * **Frames are advisory.** Everything here is a guess at an unfinished
19
+ * document, and the caller is expected to have an authoritative result coming.
20
+ * That is what lets it drop what it cannot place instead of reporting an error,
21
+ * and why it never throws on input.
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+ import { expand } from "./compact.js";
26
+ import { ELEMENT_TYPE_GROUPS } from "./element-catalog.js";
27
+ function isRecord(value) {
28
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29
+ }
30
+ /**
31
+ * Reads a diagram out of a stream of text.
32
+ *
33
+ * @param options - See {@link CompactStreamOptions}.
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * const stream = createCompactStream({ base: currentDiagram })
38
+ * for await (const chunk of tokens) {
39
+ * const defs = stream.push(chunk)
40
+ * if (defs) render(defs)
41
+ * }
42
+ * ```
43
+ */
44
+ export function createCompactStream(options) {
45
+ const baseProcess = options?.base?.processes[0];
46
+ const elements = new Map();
47
+ const flows = new Map();
48
+ for (const element of baseProcess?.elements ?? [])
49
+ elements.set(element.id, element);
50
+ for (const flow of baseProcess?.flows ?? [])
51
+ flows.set(flow.id, flow);
52
+ const documentId = options?.base?.id ?? "Definitions_1";
53
+ const processId = baseProcess?.id ?? "Process_1";
54
+ const processName = baseProcess?.name;
55
+ let text = "";
56
+ /** How far `scan` has read. Every character is looked at exactly once. */
57
+ let read = 0;
58
+ /** Offsets of the `{`s that are still open, outermost first. */
59
+ const open = [];
60
+ let inString = false;
61
+ let escaped = false;
62
+ let changed = false;
63
+ /** Drops a container's contents from the top level — they belong to it. */
64
+ function forget(children) {
65
+ for (const child of children?.elements ?? []) {
66
+ elements.delete(child.id);
67
+ forget(child.children);
68
+ }
69
+ for (const flow of children?.flows ?? [])
70
+ flows.delete(flow.id);
71
+ }
72
+ /** Keeps `value` if it is an element or a flow. */
73
+ function take(value) {
74
+ if (!isRecord(value) || typeof value.id !== "string" || value.id === "")
75
+ return;
76
+ if (typeof value.type === "string" && Object.hasOwn(ELEMENT_TYPE_GROUPS, value.type)) {
77
+ const element = value;
78
+ forget(element.children);
79
+ elements.set(element.id, element);
80
+ changed = true;
81
+ return;
82
+ }
83
+ if (typeof value.from === "string" && typeof value.to === "string") {
84
+ // `isDefault` is dropped rather than carried: `expand` throws when a flow
85
+ // claims a gateway that has not been written yet, which during a stream is
86
+ // most of the time. A preview without the marker beats no preview.
87
+ const { isDefault: _dropped, ...flow } = value;
88
+ flows.set(flow.id, flow);
89
+ changed = true;
90
+ }
91
+ }
92
+ /**
93
+ * Reads the new text once, taking each literal at the `}` that closes it.
94
+ *
95
+ * A brace stack rather than a re-scan: every character is looked at exactly
96
+ * once across the whole stream, and each literal is considered exactly once,
97
+ * innermost first — so a container is seen after the children it has to
98
+ * reclaim, and the tool argument's own wrapper is not waited on.
99
+ */
100
+ function scan() {
101
+ for (; read < text.length; read++) {
102
+ const ch = text[read];
103
+ if (escaped) {
104
+ escaped = false;
105
+ continue;
106
+ }
107
+ if (ch === "\\") {
108
+ escaped = true;
109
+ continue;
110
+ }
111
+ if (ch === '"') {
112
+ inString = !inString;
113
+ continue;
114
+ }
115
+ if (inString)
116
+ continue;
117
+ if (ch === "{") {
118
+ open.push(read);
119
+ continue;
120
+ }
121
+ if (ch !== "}")
122
+ continue;
123
+ const start = open.pop();
124
+ if (start === undefined)
125
+ continue; // a stray brace in prose
126
+ try {
127
+ take(JSON.parse(text.slice(start, read + 1)));
128
+ }
129
+ catch {
130
+ /* not a literal we can read */
131
+ }
132
+ }
133
+ }
134
+ return {
135
+ push(chunk) {
136
+ text += chunk;
137
+ scan();
138
+ if (!changed)
139
+ return null;
140
+ changed = false;
141
+ const kept = [...elements.values()];
142
+ if (kept.length === 0)
143
+ return null;
144
+ const known = new Set(kept.map((element) => element.id));
145
+ const diagram = {
146
+ id: documentId,
147
+ processes: [
148
+ {
149
+ id: processId,
150
+ name: processName,
151
+ elements: kept,
152
+ // A flow whose other end has not been written yet lays out as
153
+ // nothing; one naming an element that never arrives would too.
154
+ flows: [...flows.values()].filter((flow) => known.has(flow.from) && known.has(flow.to)),
155
+ },
156
+ ],
157
+ };
158
+ try {
159
+ return expand(diagram);
160
+ }
161
+ catch {
162
+ return null; // an element whose fields have not all arrived
163
+ }
164
+ },
165
+ };
166
+ }
167
+ //# sourceMappingURL=compact-stream.js.map
@@ -57,6 +57,17 @@ export interface CompactFlow {
57
57
  name?: string;
58
58
  /** FEEL condition expression */
59
59
  condition?: string;
60
+ /**
61
+ * Marks this flow as its gateway's default — the path taken when no other
62
+ * condition is true. Only an exclusive, inclusive or complex gateway has one,
63
+ * and it has at most one.
64
+ *
65
+ * It sits on the flow rather than on the gateway because that is where its
66
+ * alternative, `condition`, sits: a model writing the branches of a decision
67
+ * marks one of them instead of having to point back at a flow id. `expand`
68
+ * turns it into the gateway's `bpmn:default` attribute.
69
+ */
70
+ isDefault?: boolean;
60
71
  }
61
72
  /** A single process in compact form. */
62
73
  export interface CompactProcess {
@@ -86,6 +97,14 @@ export interface CompactDiagram {
86
97
  id: string;
87
98
  processes: CompactProcess[];
88
99
  }
100
+ /**
101
+ * The flow each gateway marks as its default, keyed by the gateway's id.
102
+ *
103
+ * Both failures throw rather than being dropped: a diagram whose default went
104
+ * missing is one whose gateway deadlocks the first time every condition is
105
+ * false, and that is a runtime failure with no trace back to here.
106
+ */
107
+ export declare function defaultFlows(elements: readonly CompactElement[], flows: readonly CompactFlow[]): Map<string, string>;
89
108
  /**
90
109
  * Converts a {@link BpmnDefinitions} model into a token-efficient
91
110
  * {@link CompactDiagram} representation suitable for AI contexts (LLM prompts,
@@ -108,7 +127,9 @@ export interface CompactDiagram {
108
127
  export declare function compactify(defs: BpmnDefinitions): CompactDiagram;
109
128
  export declare function makeEventDef(eventType: string): BpmnEventDefinition | undefined;
110
129
  export declare function makeExtensions(el: CompactElement): XmlElement[];
111
- export declare function buildFlowElement(el: CompactElement, incoming: string[], outgoing: string[]): BpmnFlowElement;
130
+ export declare function buildFlowElement(el: CompactElement, incoming: string[], outgoing: string[],
131
+ /** Id of the outgoing flow marked `isDefault`, for a gateway that has one. */
132
+ defaultFlow?: string): BpmnFlowElement;
112
133
  /**
113
134
  * Restores a {@link CompactDiagram} (produced by {@link compactify} or an AI
114
135
  * model) back to a full {@link BpmnDefinitions} with auto-generated layout.
@@ -1,5 +1,40 @@
1
1
  import { layoutProcess } from "../layout/index.js";
2
2
  import { assertBpmnDefinitions, assertCompactDiagram } from "./argument-guards.js";
3
+ // ── Default flows ────────────────────────────────────────────────────────────
4
+ /**
5
+ * The gateway types that carry a `bpmn:default`. No other element in this model
6
+ * has the attribute, so a flow marked default anywhere else has nowhere to go.
7
+ */
8
+ const DEFAULTABLE = new Set([
9
+ "exclusiveGateway",
10
+ "inclusiveGateway",
11
+ "complexGateway",
12
+ ]);
13
+ /**
14
+ * The flow each gateway marks as its default, keyed by the gateway's id.
15
+ *
16
+ * Both failures throw rather than being dropped: a diagram whose default went
17
+ * missing is one whose gateway deadlocks the first time every condition is
18
+ * false, and that is a runtime failure with no trace back to here.
19
+ */
20
+ export function defaultFlows(elements, flows) {
21
+ const types = new Map(elements.map((element) => [element.id, element.type]));
22
+ const defaults = new Map();
23
+ for (const flow of flows) {
24
+ if (!flow.isDefault)
25
+ continue;
26
+ const type = types.get(flow.from);
27
+ if (type === undefined || !DEFAULTABLE.has(type)) {
28
+ throw new Error(`flow "${flow.id}" is marked isDefault but leaves ${type === undefined ? `unknown element "${flow.from}"` : `a ${type}`}. Only an exclusive, inclusive or complex gateway has a default flow.`);
29
+ }
30
+ const already = defaults.get(flow.from);
31
+ if (already !== undefined) {
32
+ throw new Error(`gateway "${flow.from}" marks two flows as default, "${already}" and "${flow.id}". A gateway has at most one.`);
33
+ }
34
+ defaults.set(flow.from, flow.id);
35
+ }
36
+ return defaults;
37
+ }
3
38
  // ── Compactify ───────────────────────────────────────────────────────────────
4
39
  function findAttr(ext, name, attr) {
5
40
  return ext.find((e) => e.name === name)?.attributes[attr];
@@ -74,18 +109,29 @@ function compactifyElement(el) {
74
109
  const seqFlows = "sequenceFlows" in el && Array.isArray(el.sequenceFlows) ? el.sequenceFlows : [];
75
110
  result.children = {
76
111
  elements: el.flowElements.map(compactifyElement),
77
- flows: seqFlows.map((sf) => {
78
- const f = { id: sf.id, from: sf.sourceRef, to: sf.targetRef };
79
- if (sf.name)
80
- f.name = sf.name;
81
- if (sf.conditionExpression)
82
- f.condition = sf.conditionExpression.text;
83
- return f;
84
- }),
112
+ flows: compactifyFlows(el.flowElements, seqFlows),
85
113
  };
86
114
  }
87
115
  return result;
88
116
  }
117
+ /**
118
+ * Projects sequence flows, marking the one each gateway points at with
119
+ * `bpmn:default`. The gateways are read here rather than in
120
+ * {@link compactifyElement} because the attribute names a sibling flow.
121
+ */
122
+ function compactifyFlows(elements, sequenceFlows) {
123
+ const marked = new Set(elements.flatMap((element) => "default" in element && element.default !== undefined ? [element.default] : []));
124
+ return sequenceFlows.map((sf) => {
125
+ const flow = { id: sf.id, from: sf.sourceRef, to: sf.targetRef };
126
+ if (sf.name)
127
+ flow.name = sf.name;
128
+ if (sf.conditionExpression)
129
+ flow.condition = sf.conditionExpression.text;
130
+ if (marked.has(sf.id))
131
+ flow.isDefault = true;
132
+ return flow;
133
+ });
134
+ }
89
135
  /**
90
136
  * Converts a {@link BpmnDefinitions} model into a token-efficient
91
137
  * {@link CompactDiagram} representation suitable for AI contexts (LLM prompts,
@@ -114,14 +160,7 @@ export function compactify(defs) {
114
160
  name: process.name,
115
161
  documentation: process.documentation,
116
162
  elements: process.flowElements.map(compactifyElement),
117
- flows: process.sequenceFlows.map((sf) => {
118
- const f = { id: sf.id, from: sf.sourceRef, to: sf.targetRef };
119
- if (sf.name)
120
- f.name = sf.name;
121
- if (sf.conditionExpression)
122
- f.condition = sf.conditionExpression.text;
123
- return f;
124
- }),
163
+ flows: compactifyFlows(process.flowElements, process.sequenceFlows),
125
164
  })),
126
165
  };
127
166
  }
@@ -224,8 +263,9 @@ function buildSubContent(children) {
224
263
  i.push(f.id);
225
264
  inc.set(f.to, i);
226
265
  }
266
+ const defaults = defaultFlows(children.elements, children.flows);
227
267
  return {
228
- flowElements: children.elements.map((child) => buildFlowElement(child, inc.get(child.id) ?? [], out.get(child.id) ?? [])),
268
+ flowElements: children.elements.map((child) => buildFlowElement(child, inc.get(child.id) ?? [], out.get(child.id) ?? [], defaults.get(child.id))),
229
269
  sequenceFlows: children.flows.map((f) => ({
230
270
  id: f.id,
231
271
  name: f.name,
@@ -240,7 +280,9 @@ function buildSubContent(children) {
240
280
  groups: [],
241
281
  };
242
282
  }
243
- export function buildFlowElement(el, incoming, outgoing) {
283
+ export function buildFlowElement(el, incoming, outgoing,
284
+ /** Id of the outgoing flow marked `isDefault`, for a gateway that has one. */
285
+ defaultFlow) {
244
286
  const base = {
245
287
  id: el.id,
246
288
  name: el.name,
@@ -297,15 +339,15 @@ export function buildFlowElement(el, incoming, outgoing) {
297
339
  case "transaction":
298
340
  return { ...base, type: "transaction", ...subContent };
299
341
  case "exclusiveGateway":
300
- return { ...base, type: "exclusiveGateway" };
342
+ return { ...base, type: "exclusiveGateway", default: defaultFlow };
301
343
  case "parallelGateway":
302
344
  return { ...base, type: "parallelGateway" };
303
345
  case "inclusiveGateway":
304
- return { ...base, type: "inclusiveGateway" };
346
+ return { ...base, type: "inclusiveGateway", default: defaultFlow };
305
347
  case "eventBasedGateway":
306
348
  return { ...base, type: "eventBasedGateway" };
307
349
  case "complexGateway":
308
- return { ...base, type: "complexGateway" };
350
+ return { ...base, type: "complexGateway", default: defaultFlow };
309
351
  // Data elements are not sequence-flow participants; they carry a
310
352
  // reference instead, and dropping that reference is what made them
311
353
  // round-trip as bare tasks before.
@@ -373,7 +415,8 @@ function expandProcess(compact) {
373
415
  inc.push(f.id);
374
416
  incoming.set(f.to, inc);
375
417
  }
376
- const flowElements = compact.elements.map((el) => buildFlowElement(el, incoming.get(el.id) ?? [], outgoing.get(el.id) ?? []));
418
+ const defaults = defaultFlows(compact.elements, compact.flows);
419
+ const flowElements = compact.elements.map((el) => buildFlowElement(el, incoming.get(el.id) ?? [], outgoing.get(el.id) ?? [], defaults.get(el.id)));
377
420
  const sequenceFlows = compact.flows.map((f) => ({
378
421
  id: f.id,
379
422
  name: f.name,
@@ -1,5 +1,5 @@
1
1
  import { assertBpmnDefinitions, assertCompactDiagram } from "./argument-guards.js";
2
- import { buildFlowElement, makeEventDef, } from "./compact.js";
2
+ import { buildFlowElement, defaultFlows, makeEventDef, } from "./compact.js";
3
3
  import { bpmnElementName, ensureZeebeExtension, isZeebePlacementAllowed, } from "./zeebe-extensions.js";
4
4
  /** Thrown by {@link applyBpmnOperations} in strict mode. */
5
5
  export class OperationError extends Error {
@@ -405,7 +405,35 @@ export function reconcileCompact(definitions, compact, options = {}) {
405
405
  });
406
406
  }
407
407
  }
408
- return applyBpmnOperations(draft, operationsForCompact(draft, compact), options);
408
+ const result = applyBpmnOperations(draft, operationsForCompact(draft, compact), options);
409
+ reconcileDefaultFlows(result.definitions, compact);
410
+ return result;
411
+ }
412
+ /**
413
+ * Brings each gateway's `bpmn:default` in line with the flow the compact input
414
+ * marks, clearing one the input no longer marks.
415
+ *
416
+ * It runs after the operations rather than as one of them because the attribute
417
+ * names a flow: a default can only be set once the flow it points at exists, and
418
+ * a flow that is being replaced is deleted and re-added under the same id.
419
+ */
420
+ function reconcileDefaultFlows(definitions, compact) {
421
+ for (const compactProcess of compact.processes) {
422
+ const process = definitions.processes.find((candidate) => candidate.id === compactProcess.id);
423
+ if (!process)
424
+ continue;
425
+ const wanted = defaultFlows(compactProcess.elements, compactProcess.flows);
426
+ for (const element of process.flowElements) {
427
+ // By type, not by `"default" in element`: a gateway built without the
428
+ // attribute has no such key, and skipping it would drop a wanted default.
429
+ if (element.type !== "exclusiveGateway" &&
430
+ element.type !== "inclusiveGateway" &&
431
+ element.type !== "complexGateway") {
432
+ continue;
433
+ }
434
+ element.default = wanted.get(element.id);
435
+ }
436
+ }
409
437
  }
410
438
  /**
411
439
  * Derives the operations that would bring `definitions` in line with `compact`.
@@ -1,3 +1,4 @@
1
+ import { ParseError } from "../errors.js";
1
2
  import { parseXml } from "../xml/xml-parser.js";
2
3
  const DMN_NS = "https://www.omg.org/spec/DMN/20191111/MODEL/";
3
4
  /** Strip namespace prefix from a tag name. */
@@ -28,7 +29,7 @@ function attr(element, name) {
28
29
  function requiredAttr(element, name) {
29
30
  const value = attr(element, name);
30
31
  if (value === undefined) {
31
- throw new Error(`Missing required attribute "${name}" on element <${element.name}>`);
32
+ throw new ParseError(`Missing required attribute "${name}" on element <${element.name}>`);
32
33
  }
33
34
  return value;
34
35
  }
@@ -59,7 +60,7 @@ function parseInputExpression(el) {
59
60
  function parseInput(el) {
60
61
  const exprEl = findChild(el, "inputExpression");
61
62
  if (!exprEl) {
62
- throw new Error(`Missing <inputExpression> in input "${attr(el, "id")}"`);
63
+ throw new ParseError(`Missing <inputExpression> in input "${attr(el, "id")}"`);
63
64
  }
64
65
  return {
65
66
  id: requiredAttr(el, "id"),
@@ -231,7 +232,7 @@ function parseDiagram(dmndiEl) {
231
232
  export function parseDmn(xml) {
232
233
  const root = parseXml(xml);
233
234
  if (localName(root.name) !== "definitions") {
234
- throw new Error(`Expected <definitions> root element, got <${root.name}>`);
235
+ throw new ParseError(`Expected <definitions> root element, got <${root.name}>`);
235
236
  }
236
237
  // Extract namespace declarations
237
238
  const namespaces = {};
@@ -1,3 +1,4 @@
1
+ import { ParseError } from "../errors.js";
1
2
  const KNOWN_COMPONENT_TYPES = new Set([
2
3
  "text",
3
4
  "textfield",
@@ -29,20 +30,20 @@ export function parseForm(json) {
29
30
  raw = JSON.parse(json);
30
31
  }
31
32
  catch (e) {
32
- throw new Error(`Failed to parse form JSON: ${e.message}`);
33
+ throw new ParseError(`Failed to parse form JSON: ${e.message}`);
33
34
  }
34
35
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
35
- throw new Error("Form JSON must be an object");
36
+ throw new ParseError("Form JSON must be an object");
36
37
  }
37
38
  const obj = raw;
38
39
  if (typeof obj.id !== "string" || obj.id.length === 0) {
39
- throw new Error("Form must have a non-empty 'id' string");
40
+ throw new ParseError("Form must have a non-empty 'id' string");
40
41
  }
41
42
  if (typeof obj.type !== "string") {
42
- throw new Error("Form must have a 'type' string");
43
+ throw new ParseError("Form must have a 'type' string");
43
44
  }
44
45
  if (!Array.isArray(obj.components)) {
45
- throw new Error("Form must have a 'components' array");
46
+ throw new ParseError("Form must have a 'components' array");
46
47
  }
47
48
  const definition = {
48
49
  id: obj.id,
@@ -72,14 +73,14 @@ export function parseForm(json) {
72
73
  }
73
74
  function parseComponent(raw, path) {
74
75
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
75
- throw new Error(`${path}: component must be an object`);
76
+ throw new ParseError(`${path}: component must be an object`);
76
77
  }
77
78
  const obj = raw;
78
79
  if (typeof obj.type !== "string") {
79
- throw new Error(`${path}: component must have a 'type' string`);
80
+ throw new ParseError(`${path}: component must have a 'type' string`);
80
81
  }
81
82
  if (typeof obj.id !== "string" || obj.id.length === 0) {
82
- throw new Error(`${path}: component must have a non-empty 'id'`);
83
+ throw new ParseError(`${path}: component must have a non-empty 'id'`);
83
84
  }
84
85
  const layout = parseLayout(obj.layout, path);
85
86
  if (!KNOWN_COMPONENT_TYPES.has(obj.type)) {
@@ -88,7 +89,7 @@ function parseComponent(raw, path) {
88
89
  switch (obj.type) {
89
90
  case "text": {
90
91
  if (typeof obj.text !== "string") {
91
- throw new Error(`${path}: text component must have a 'text' string`);
92
+ throw new ParseError(`${path}: text component must have a 'text' string`);
92
93
  }
93
94
  const c = { type: "text", id: obj.id, text: obj.text };
94
95
  if (typeof obj.label === "string")
@@ -147,7 +148,7 @@ function parseLayout(raw, path) {
147
148
  if (raw === undefined || raw === null)
148
149
  return undefined;
149
150
  if (typeof raw !== "object" || Array.isArray(raw)) {
150
- throw new Error(`${path}.layout: must be an object`);
151
+ throw new ParseError(`${path}.layout: must be an object`);
151
152
  }
152
153
  const obj = raw;
153
154
  const layout = {};
@@ -165,7 +166,7 @@ function parseValidation(raw, path) {
165
166
  if (raw === undefined || raw === null)
166
167
  return undefined;
167
168
  if (typeof raw !== "object" || Array.isArray(raw)) {
168
- throw new Error(`${path}.validate: must be an object`);
169
+ throw new ParseError(`${path}.validate: must be an object`);
169
170
  }
170
171
  const obj = raw;
171
172
  const v = {};
@@ -179,11 +180,11 @@ function parseValidation(raw, path) {
179
180
  }
180
181
  function parseValues(raw, path) {
181
182
  if (!Array.isArray(raw)) {
182
- throw new Error(`${path}.values: must be an array`);
183
+ throw new ParseError(`${path}.values: must be an array`);
183
184
  }
184
185
  return raw.map((v, i) => {
185
186
  if (typeof v !== "object" || v === null) {
186
- throw new Error(`${path}.values[${i}]: must be an object`);
187
+ throw new ParseError(`${path}.values[${i}]: must be an object`);
187
188
  }
188
189
  const vo = v;
189
190
  return {
@@ -194,10 +195,10 @@ function parseValues(raw, path) {
194
195
  }
195
196
  function parseFieldComponent(obj, type, path, layout) {
196
197
  if (typeof obj.label !== "string") {
197
- throw new Error(`${path}: ${type} must have a 'label' string`);
198
+ throw new ParseError(`${path}: ${type} must have a 'label' string`);
198
199
  }
199
200
  if (typeof obj.key !== "string") {
200
- throw new Error(`${path}: ${type} must have a 'key' string`);
201
+ throw new ParseError(`${path}: ${type} must have a 'key' string`);
201
202
  }
202
203
  const validate = parseValidation(obj.validate, path);
203
204
  const base = {
@@ -214,10 +215,10 @@ function parseFieldComponent(obj, type, path, layout) {
214
215
  }
215
216
  function parseSelectComponent(obj, path, layout) {
216
217
  if (typeof obj.label !== "string") {
217
- throw new Error(`${path}: select must have a 'label' string`);
218
+ throw new ParseError(`${path}: select must have a 'label' string`);
218
219
  }
219
220
  if (typeof obj.key !== "string") {
220
- throw new Error(`${path}: select must have a 'key' string`);
221
+ throw new ParseError(`${path}: select must have a 'key' string`);
221
222
  }
222
223
  const c = {
223
224
  type: "select",
@@ -243,10 +244,10 @@ function parseSelectComponent(obj, path, layout) {
243
244
  }
244
245
  function parseValuesComponent(obj, type, path, layout) {
245
246
  if (typeof obj.label !== "string") {
246
- throw new Error(`${path}: ${type} must have a 'label' string`);
247
+ throw new ParseError(`${path}: ${type} must have a 'label' string`);
247
248
  }
248
249
  if (typeof obj.key !== "string") {
249
- throw new Error(`${path}: ${type} must have a 'key' string`);
250
+ throw new ParseError(`${path}: ${type} must have a 'key' string`);
250
251
  }
251
252
  const values = Array.isArray(obj.values) ? parseValues(obj.values, path) : undefined;
252
253
  if (type === "radio") {
@@ -288,10 +289,10 @@ function parseValuesComponent(obj, type, path, layout) {
288
289
  }
289
290
  function parseCheckboxComponent(obj, path, layout) {
290
291
  if (typeof obj.label !== "string") {
291
- throw new Error(`${path}: checkbox must have a 'label' string`);
292
+ throw new ParseError(`${path}: checkbox must have a 'label' string`);
292
293
  }
293
294
  if (typeof obj.key !== "string") {
294
- throw new Error(`${path}: checkbox must have a 'key' string`);
295
+ throw new ParseError(`${path}: checkbox must have a 'key' string`);
295
296
  }
296
297
  const c = {
297
298
  type: "checkbox",
@@ -310,10 +311,10 @@ function parseCheckboxComponent(obj, path, layout) {
310
311
  }
311
312
  function parseGroupComponent(obj, path, layout) {
312
313
  if (typeof obj.label !== "string") {
313
- throw new Error(`${path}: group must have a 'label' string`);
314
+ throw new ParseError(`${path}: group must have a 'label' string`);
314
315
  }
315
316
  if (!Array.isArray(obj.components)) {
316
- throw new Error(`${path}: group must have a 'components' array`);
317
+ throw new ParseError(`${path}: group must have a 'components' array`);
317
318
  }
318
319
  const components = obj.components.map((c, i) => parseComponent(c, `${path}.components[${i}]`));
319
320
  const c = {
@@ -330,9 +331,9 @@ function parseGroupComponent(obj, path, layout) {
330
331
  }
331
332
  function parseNumberComponent(obj, path, layout) {
332
333
  if (typeof obj.label !== "string")
333
- throw new Error(`${path}: number must have a 'label' string`);
334
+ throw new ParseError(`${path}: number must have a 'label' string`);
334
335
  if (typeof obj.key !== "string")
335
- throw new Error(`${path}: number must have a 'key' string`);
336
+ throw new ParseError(`${path}: number must have a 'key' string`);
336
337
  const c = { type: "number", id: obj.id, label: obj.label, key: obj.key };
337
338
  const validate = parseValidation(obj.validate, path);
338
339
  if (validate)
@@ -357,7 +358,7 @@ function parseDatetimeComponent(obj, _path, layout) {
357
358
  }
358
359
  function parseButtonComponent(obj, path, layout) {
359
360
  if (typeof obj.label !== "string")
360
- throw new Error(`${path}: button must have a 'label' string`);
361
+ throw new ParseError(`${path}: button must have a 'label' string`);
361
362
  const c = { type: "button", id: obj.id, label: obj.label };
362
363
  if (typeof obj.action === "string")
363
364
  c.action = obj.action;
@@ -367,9 +368,9 @@ function parseButtonComponent(obj, path, layout) {
367
368
  }
368
369
  function parseTaglistComponent(obj, path, layout) {
369
370
  if (typeof obj.label !== "string")
370
- throw new Error(`${path}: taglist must have a 'label' string`);
371
+ throw new ParseError(`${path}: taglist must have a 'label' string`);
371
372
  if (typeof obj.key !== "string")
372
- throw new Error(`${path}: taglist must have a 'key' string`);
373
+ throw new ParseError(`${path}: taglist must have a 'key' string`);
373
374
  const c = {
374
375
  type: "taglist",
375
376
  id: obj.id,
package/dist/index.d.ts CHANGED
@@ -57,6 +57,8 @@ export type { BenchmarkResult, BoundingBox, ElementComparison, ElementPosition,
57
57
  export type { Bounds, LayoutEdge, LayoutNode, LayoutResult, Waypoint } from "./layout/index.js";
58
58
  export { ELEMENT_SIZES, GRID_CELL_HEIGHT, GRID_CELL_WIDTH } from "./layout/index.js";
59
59
  export { compactify, expand } from "./bpmn/compact.js";
60
+ export { createCompactStream } from "./bpmn/compact-stream.js";
61
+ export type { CompactStream, CompactStreamOptions } from "./bpmn/compact-stream.js";
60
62
  export { ELEMENT_GROUP_ORDER, ELEMENT_TYPE_GROUPS, allElementTypes, elementTypesInGroup, } from "./bpmn/element-catalog.js";
61
63
  export type { ElementTypeGroup } from "./bpmn/element-catalog.js";
62
64
  export { createFlowElement, retypeElement } from "./bpmn/element-shape.js";
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ export { layoutProcess, layoutFlowNodes } from "./layout/index.js";
31
31
  export { benchmarkLayout, compareLayouts, formatBenchmarkResult, generateAutoLayout, parseReferenceLayout, } from "./layout/index.js";
32
32
  export { ELEMENT_SIZES, GRID_CELL_HEIGHT, GRID_CELL_WIDTH } from "./layout/index.js";
33
33
  export { compactify, expand } from "./bpmn/compact.js";
34
+ export { createCompactStream } from "./bpmn/compact-stream.js";
34
35
  export { ELEMENT_GROUP_ORDER, ELEMENT_TYPE_GROUPS, allElementTypes, elementTypesInGroup, } from "./bpmn/element-catalog.js";
35
36
  export { createFlowElement, retypeElement } from "./bpmn/element-shape.js";
36
37
  export { applyOperations } from "./bpmn/operations.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bpmnkit/core",
3
- "version": "0.7.1",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -20,8 +20,11 @@
20
20
  "dist/**/*.js",
21
21
  "dist/**/*.d.ts"
22
22
  ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
23
26
  "dependencies": {
24
- "@bpmnkit/feel": "0.1.0"
27
+ "@bpmnkit/feel": "^1.0.0"
25
28
  },
26
29
  "description": "TypeScript-first BPMN 2.0 SDK — parse, build, layout, and optimize diagrams",
27
30
  "keywords": [