@nanobpm/workflow 0.8.2 → 0.10.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 (65) hide show
  1. package/README.md +73 -2
  2. package/dist/declarative.d.ts +178 -10
  3. package/dist/declarative.js +216 -356
  4. package/dist/nodes/branch.d.ts +11 -0
  5. package/dist/nodes/branch.js +40 -0
  6. package/dist/nodes/break.d.ts +8 -0
  7. package/dist/nodes/break.js +19 -0
  8. package/dist/nodes/continue.d.ts +8 -0
  9. package/dist/nodes/continue.js +18 -0
  10. package/dist/nodes/forEach.d.ts +24 -0
  11. package/dist/nodes/forEach.js +109 -0
  12. package/dist/nodes/index.d.ts +12 -0
  13. package/dist/nodes/index.js +19 -0
  14. package/dist/nodes/loop.d.ts +9 -0
  15. package/dist/nodes/loop.js +25 -0
  16. package/dist/nodes/parallel.d.ts +9 -0
  17. package/dist/nodes/parallel.js +40 -0
  18. package/dist/nodes/race.d.ts +54 -0
  19. package/dist/nodes/race.js +134 -0
  20. package/dist/nodes/registry.d.ts +33 -0
  21. package/dist/nodes/registry.js +71 -0
  22. package/dist/nodes/run.d.ts +10 -0
  23. package/dist/nodes/run.js +21 -0
  24. package/dist/nodes/signal.d.ts +11 -0
  25. package/dist/nodes/signal.js +26 -0
  26. package/dist/nodes/switch.d.ts +11 -0
  27. package/dist/nodes/switch.js +51 -0
  28. package/dist/nodes/task.d.ts +47 -0
  29. package/dist/nodes/task.js +97 -0
  30. package/dist/nodes/timer.d.ts +9 -0
  31. package/dist/nodes/timer.js +34 -0
  32. package/dist/test-support/diff.d.ts +8 -0
  33. package/dist/test-support/diff.js +70 -0
  34. package/dist/test-support/index.d.ts +8 -0
  35. package/dist/test-support/index.js +49 -0
  36. package/dist/test-support/normalize.d.ts +19 -0
  37. package/dist/test-support/normalize.js +245 -0
  38. package/dist/test-support/parity.d.ts +28 -0
  39. package/dist/test-support/parity.js +61 -0
  40. package/dist/test-support/xml.d.ts +17 -0
  41. package/dist/test-support/xml.js +135 -0
  42. package/dist/types.d.ts +20 -56
  43. package/package.json +12 -4
  44. package/src/declarative.ts +339 -360
  45. package/src/nodes/README.md +123 -0
  46. package/src/nodes/branch.ts +48 -0
  47. package/src/nodes/break.ts +25 -0
  48. package/src/nodes/continue.ts +24 -0
  49. package/src/nodes/forEach.ts +142 -0
  50. package/src/nodes/index.ts +20 -0
  51. package/src/nodes/loop.ts +34 -0
  52. package/src/nodes/parallel.ts +48 -0
  53. package/src/nodes/race.ts +185 -0
  54. package/src/nodes/registry.ts +105 -0
  55. package/src/nodes/run.ts +29 -0
  56. package/src/nodes/signal.ts +35 -0
  57. package/src/nodes/switch.ts +56 -0
  58. package/src/nodes/task.ts +150 -0
  59. package/src/nodes/timer.ts +42 -0
  60. package/src/test-support/diff.ts +69 -0
  61. package/src/test-support/index.ts +53 -0
  62. package/src/test-support/normalize.ts +274 -0
  63. package/src/test-support/parity.ts +85 -0
  64. package/src/test-support/xml.ts +140 -0
  65. package/src/types.ts +20 -30
@@ -0,0 +1,274 @@
1
+ // Canonicalize a BPMN 2.0 document down to its SEMANTIC structure, so two models
2
+ // that mean the same thing compare equal regardless of element ids, child
3
+ // ordering, or diagram-interchange (DI) layout. This is the oracle S1–S6 assert
4
+ // their derived flows against.
5
+ //
6
+ // What "semantic structure" keeps (and what it deliberately drops):
7
+ // - DROPPED: the `bpmndi:BPMNDiagram` layout subtree (shapes, edges, bounds);
8
+ // every element `id` and every `sequenceFlow` id (canonicalized away — a
9
+ // flow node is identified by its TYPE + semantic definition, an edge by its
10
+ // endpoints); cosmetic `name` labels on flow nodes and gateways (the routing
11
+ // meaning lives in edge conditions and in derived task/message identities,
12
+ // not in a human label); child ORDER (everything is compared as a sorted
13
+ // multiset).
14
+ // - KEPT: flow nodes (tasks, gateways, events) with their semantic definition
15
+ // (task-definition job type, user-task / form / assignment / io-mapping /
16
+ // linked-resources extension elements, multi-instance characteristics, event
17
+ // definitions); sequence flows as endpoint pairs with their condition /
18
+ // default marker; message subscriptions (a catch event's `messageRef`
19
+ // resolved to the referenced message's full definition — name plus its
20
+ // `zeebe:subscription correlationKey` and `zeebe:properties` envelope);
21
+ // timer definitions; and boundary events (their `attachedToRef` modelled as
22
+ // a structural attach edge to the host, never as a raw-id attribute).
23
+
24
+ import { localName, parseXml, type XmlElement } from "./xml.js";
25
+
26
+ /** The id-agnostic, order-agnostic semantic structure of a BPMN model. Two
27
+ * models are structurally equal iff their three multisets are equal. */
28
+ export interface CanonicalModel {
29
+ /** Semantic descriptor of every flow node (task/gateway/event/subProcess),
30
+ * sorted. Each carries its type, definition, and edge-degree signature. */
31
+ nodes: string[];
32
+ /** Every sequence flow as `«fromNode» =[tag]=> «toNode»`, plus structural
33
+ * attach (boundary→host) and containment (subProcess→child) edges, sorted. */
34
+ flows: string[];
35
+ /** The full semantic identity of every message a catch event subscribes to,
36
+ * sorted (deduped): the serialized `<bpmn:message>` definition — its name plus
37
+ * the `zeebe:subscription correlationKey` and any `zeebe:properties` envelope —
38
+ * so a differing correlation key or envelope is a structural difference. */
39
+ messages: string[];
40
+ }
41
+
42
+ const FLOW_NODES = new Set([
43
+ "startEvent",
44
+ "endEvent",
45
+ "intermediateCatchEvent",
46
+ "intermediateThrowEvent",
47
+ "boundaryEvent",
48
+ "task",
49
+ "serviceTask",
50
+ "userTask",
51
+ "scriptTask",
52
+ "sendTask",
53
+ "receiveTask",
54
+ "manualTask",
55
+ "businessRuleTask",
56
+ "callActivity",
57
+ "subProcess",
58
+ "adHocSubProcess",
59
+ "transaction",
60
+ "exclusiveGateway",
61
+ "parallelGateway",
62
+ "inclusiveGateway",
63
+ "eventBasedGateway",
64
+ "complexGateway",
65
+ ]);
66
+
67
+ const REF_ATTRS = new Set(["messageRef", "errorRef", "signalRef", "escalationRef"]);
68
+
69
+ function isDI(el: XmlElement): boolean {
70
+ const prefix = el.name.includes(":") ? el.name.slice(0, el.name.indexOf(":")) : "";
71
+ if (prefix === "bpmndi" || prefix === "di" || prefix === "dc" || prefix === "omgdi" || prefix === "omgdc") {
72
+ return true;
73
+ }
74
+ const l = localName(el.name);
75
+ return l === "BPMNDiagram" || l === "BPMNPlane" || l === "BPMNShape" || l === "BPMNEdge" || l === "BPMNLabel";
76
+ }
77
+
78
+ interface Node {
79
+ id: string;
80
+ type: string;
81
+ label: string;
82
+ }
83
+
84
+ interface Edge {
85
+ kind: "seq" | "attach" | "contain";
86
+ from: string;
87
+ to: string;
88
+ tag: string;
89
+ }
90
+
91
+ /** Accumulates the flat graph while walking every process / sub-process. */
92
+ class Collector {
93
+ readonly refNames = new Map<string, string>();
94
+ readonly messageDefs = new Map<string, XmlElement>();
95
+ readonly nodes = new Map<string, Node>();
96
+ readonly edges: Edge[] = [];
97
+ readonly messages = new Set<string>();
98
+ readonly defaultFlows = new Set<string>();
99
+ private readonly seqFlows: XmlElement[] = [];
100
+
101
+ /** Resolve a *Ref value to the referenced element's name (falling back to the
102
+ * raw ref only when the target is unknown), recording message subscriptions.
103
+ * A `messageRef` records the subscribed message's FULL semantic identity — the
104
+ * serialized `<bpmn:message>` definition (its name plus the `zeebe:subscription
105
+ * correlationKey` and any `zeebe:properties` envelope), not just its name — so
106
+ * two models whose catch events share a message name but differ in correlation
107
+ * key or envelope properties do NOT compare equal (the parity oracle would
108
+ * otherwise be blind to a wrong-correlationKey derivation). Falls back to the
109
+ * bare name only when the referenced message definition is unknown. */
110
+ private resolveRef(attr: string, value: string): string {
111
+ const name = this.refNames.get(value) ?? value;
112
+ if (attr === "messageRef") {
113
+ const def = this.messageDefs.get(value);
114
+ this.messages.add(def ? this.serialize(def) : name);
115
+ }
116
+ return `@${name}`;
117
+ }
118
+
119
+ /** Serialize a definition/extension descendant fully (all descendants), with
120
+ * sorted attributes (ids dropped, refs resolved) and sorted children, so the
121
+ * string is invariant to attribute/child ordering and to id renaming. */
122
+ private serialize(el: XmlElement): string {
123
+ const attrs = Object.entries(el.attrs)
124
+ .filter(([k]) => k !== "id")
125
+ .map(([k, v]) => `${k}=${REF_ATTRS.has(k) ? this.resolveRef(k, v) : v}`)
126
+ .sort();
127
+ const kids = el.children.filter((c) => !isDI(c)).map((c) => this.serialize(c)).sort();
128
+ const text = el.text ? `=${el.text}` : "";
129
+ return `${localName(el.name)}{${attrs.join(",")}}${text}[${kids.join(";")}]`;
130
+ }
131
+
132
+ /** The id-agnostic semantic descriptor of a flow node: its type, its own
133
+ * discriminating attributes, and its definition subtree — but NOT nested flow
134
+ * nodes / sequence flows (those are separate graph entities) and NOT cosmetic
135
+ * id / name / structural-ref attributes. */
136
+ private nodeLabel(el: XmlElement): string {
137
+ const excluded = new Set(["id", "name", "default", "attachedToRef", "sourceRef", "targetRef"]);
138
+ const attrs = Object.entries(el.attrs)
139
+ .filter(([k]) => !excluded.has(k))
140
+ .map(([k, v]) => `${k}=${REF_ATTRS.has(k) ? this.resolveRef(k, v) : v}`)
141
+ .sort();
142
+ const defs = el.children
143
+ .filter((c) => {
144
+ const cl = localName(c.name);
145
+ // Skip nested flow nodes / sequence flows (separate graph entities) and
146
+ // the `incoming`/`outgoing` flow-id back-references (fully redundant with
147
+ // the sequence-flow edges, and carrying raw ids that must not leak here).
148
+ return !isDI(c) && !FLOW_NODES.has(cl) && cl !== "sequenceFlow" && cl !== "incoming" && cl !== "outgoing";
149
+ })
150
+ .map((c) => this.serialize(c))
151
+ .sort();
152
+ return `${localName(el.name)}(${attrs.join(",")})[${defs.join(";")}]`;
153
+ }
154
+
155
+ private registerNode(el: XmlElement): void {
156
+ const id = el.attrs.id;
157
+ if (!id) return;
158
+ this.nodes.set(id, { id, type: localName(el.name), label: this.nodeLabel(el) });
159
+ if (el.attrs.default) this.defaultFlows.add(el.attrs.default);
160
+ }
161
+
162
+ /** Walk a container (process or sub-process), registering its flow nodes and
163
+ * sequence flows and recursing into nested sub-processes. `scope` is the
164
+ * enclosing sub-process id (containment edges point scope→child). */
165
+ collectContainer(container: XmlElement, scope: string | undefined): void {
166
+ for (const child of container.children) {
167
+ if (isDI(child)) continue;
168
+ const l = localName(child.name);
169
+ if (FLOW_NODES.has(l)) {
170
+ this.registerNode(child);
171
+ const id = child.attrs.id;
172
+ if (id && scope) this.edges.push({ kind: "contain", from: scope, to: id, tag: "" });
173
+ if (l === "boundaryEvent" && child.attrs.attachedToRef && id) {
174
+ this.edges.push({ kind: "attach", from: id, to: child.attrs.attachedToRef, tag: "" });
175
+ }
176
+ if (l === "subProcess" || l === "adHocSubProcess" || l === "transaction") {
177
+ this.collectContainer(child, id);
178
+ }
179
+ } else if (l === "sequenceFlow") {
180
+ this.seqFlows.push(child);
181
+ }
182
+ }
183
+ }
184
+
185
+ /** Turn collected sequence-flow elements into endpoint edges once every node
186
+ * and default marker is known. */
187
+ finalizeFlows(): void {
188
+ for (const sf of this.seqFlows) {
189
+ const from = sf.attrs.sourceRef;
190
+ const to = sf.attrs.targetRef;
191
+ if (!from || !to) continue;
192
+ const cond = sf.children.find((c) => localName(c.name) === "conditionExpression");
193
+ let tag = "";
194
+ if (cond?.text) tag = `if:${cond.text}`;
195
+ else if (sf.attrs.id && this.defaultFlows.has(sf.attrs.id)) tag = "default";
196
+ this.edges.push({ kind: "seq", from, to, tag });
197
+ }
198
+ }
199
+ }
200
+
201
+ /** Record every referenceable root definition (`message`/`error`/`signal`/
202
+ * `escalation`) so a `*Ref` can be resolved to a stable name. */
203
+ function collectRefs(el: XmlElement, c: Collector): void {
204
+ const l = localName(el.name);
205
+ if ((l === "message" || l === "error" || l === "signal" || l === "escalation") && el.attrs.id) {
206
+ c.refNames.set(el.attrs.id, el.attrs.name ?? el.attrs.errorCode ?? el.attrs.id);
207
+ if (l === "message") c.messageDefs.set(el.attrs.id, el);
208
+ }
209
+ for (const child of el.children) if (!isDI(child)) collectRefs(child, c);
210
+ }
211
+
212
+ function findContainers(el: XmlElement, out: XmlElement[]): void {
213
+ const l = localName(el.name);
214
+ if (l === "process") out.push(el);
215
+ for (const child of el.children) if (!isDI(child)) findContainers(child, out);
216
+ }
217
+
218
+ /** Normalize a BPMN XML document to its canonical semantic model. Strips DI and
219
+ * canonicalizes ids, child ordering, and sequence-flow ids so only semantic
220
+ * structure remains. */
221
+ export function normalize(bpmnXml: string): CanonicalModel {
222
+ const root = parseXml(bpmnXml);
223
+ const c = new Collector();
224
+ collectRefs(root, c);
225
+
226
+ const processes: XmlElement[] = [];
227
+ findContainers(root, processes);
228
+ if (processes.length === 0) throw new Error("normalize: no <process> element found");
229
+ for (const p of processes) c.collectContainer(p, undefined);
230
+ c.finalizeFlows();
231
+
232
+ // Per-node edge-degree signature — captures wiring (how many sequence flows in
233
+ // / out, whether it hosts or is a boundary, whether it contains or is
234
+ // contained) so a rewiring that preserves node labels still shows up.
235
+ const deg = new Map<string, { si: number; so: number; at: number; ah: number; ci: number; co: number }>();
236
+ const bump = (id: string) => {
237
+ let d = deg.get(id);
238
+ if (!d) {
239
+ d = { si: 0, so: 0, at: 0, ah: 0, ci: 0, co: 0 };
240
+ deg.set(id, d);
241
+ }
242
+ return d;
243
+ };
244
+ for (const e of c.edges) {
245
+ if (e.kind === "seq") {
246
+ bump(e.from).so += 1;
247
+ bump(e.to).si += 1;
248
+ } else if (e.kind === "attach") {
249
+ bump(e.from).at += 1; // this node is a boundary attached to something
250
+ bump(e.to).ah += 1; // this node hosts a boundary
251
+ } else {
252
+ bump(e.from).co += 1; // this sub-process contains children
253
+ bump(e.to).ci += 1; // this node is contained
254
+ }
255
+ }
256
+
257
+ const labelWithDegree = (id: string): string => {
258
+ const node = c.nodes.get(id);
259
+ if (!node) return `«unknown:${id}»`;
260
+ const d = deg.get(id) ?? { si: 0, so: 0, at: 0, ah: 0, ci: 0, co: 0 };
261
+ return `${node.label}<in=${d.si},out=${d.so},boundary=${d.at},hosts=${d.ah},contained=${d.ci},contains=${d.co}>`;
262
+ };
263
+
264
+ const nodes = [...c.nodes.keys()].map(labelWithDegree).sort();
265
+ const flows = c.edges
266
+ .map((e) => {
267
+ const arrow = e.kind === "attach" ? "--attach-->" : e.kind === "contain" ? "--contains-->" : `=[${e.tag}]=>`;
268
+ return `${labelWithDegree(e.from)} ${arrow} ${labelWithDegree(e.to)}`;
269
+ })
270
+ .sort();
271
+ const messages = [...c.messages].sort();
272
+
273
+ return { nodes, flows, messages };
274
+ }
@@ -0,0 +1,85 @@
1
+ // The two assertions S1–S6 build their derivation-parity tests on:
2
+ //
3
+ // assertDerivationParity(derivedFlow, goldenBpmnPath)
4
+ // Derive the flow's BPMN, normalize it and the checked-in golden, and assert
5
+ // they are structurally equal — throwing a legible red/green diff otherwise.
6
+ //
7
+ // deploySmoke(derivedModel, opts?)
8
+ // Deploy the derived model to a live/wasm engine and assert acceptance. When
9
+ // no engine is reachable (no client, baseUrl, or WORKFLOW_GATEWAY_URL), it
10
+ // resolves `{ deployed: false, skipped: true }` so unit-only CI stays green —
11
+ // the caller decides whether to hard-require deployment.
12
+
13
+ import { readFileSync } from "node:fs";
14
+ import { WorkflowClient, type WorkflowClientOptions } from "../client.js";
15
+ import { declarativeToBpmn } from "../declarative.js";
16
+ import type { DeclarativeFlow, DeployResult, Workflow } from "../types.js";
17
+ import { diffModels } from "./diff.js";
18
+ import { normalize } from "./normalize.js";
19
+
20
+ /** A derived flow, or the derived BPMN XML directly. */
21
+ export type DerivedInput = DeclarativeFlow | string;
22
+
23
+ function toBpmnXml(input: DerivedInput): string {
24
+ if (typeof input === "string") return input;
25
+ return declarativeToBpmn(input);
26
+ }
27
+
28
+ /** Derive `derived`'s BPMN, normalize it and the golden at `goldenBpmnPath`, and
29
+ * assert structural equality. Throws with a legible structural diff on
30
+ * mismatch. Returns silently on parity. */
31
+ export function assertDerivationParity(derived: DerivedInput, goldenBpmnPath: string): void {
32
+ const derivedXml = toBpmnXml(derived);
33
+ const goldenXml = readFileSync(goldenBpmnPath, "utf8");
34
+ const golden = normalize(goldenXml);
35
+ const actual = normalize(derivedXml);
36
+ const diff = diffModels(golden, actual);
37
+ if (diff) {
38
+ throw new Error(`derivation parity failed against ${goldenBpmnPath}:\n${diff}`);
39
+ }
40
+ }
41
+
42
+ /** Options for {@link deploySmoke}. Supply a pre-built `client`, a `baseUrl`
43
+ * (a client is built for you), or rely on the `WORKFLOW_GATEWAY_URL` env var. */
44
+ export interface DeploySmokeOptions {
45
+ client?: WorkflowClient;
46
+ baseUrl?: string;
47
+ token?: string;
48
+ transport?: "auto" | "falcon" | "rest";
49
+ }
50
+
51
+ /** The outcome of a {@link deploySmoke}: either a completed deployment, or a
52
+ * skip because no engine was reachable. */
53
+ export interface DeploySmokeResult {
54
+ deployed: boolean;
55
+ skipped: boolean;
56
+ reason?: string;
57
+ result?: DeployResult;
58
+ }
59
+
60
+ function resolveClient(opts: DeploySmokeOptions): WorkflowClient | undefined {
61
+ if (opts.client) return opts.client;
62
+ const baseUrl = opts.baseUrl ?? process.env.WORKFLOW_GATEWAY_URL;
63
+ if (!baseUrl) return undefined;
64
+ const clientOpts: WorkflowClientOptions = {
65
+ baseUrl,
66
+ ...(opts.token ? { token: opts.token } : {}),
67
+ ...(opts.transport ? { transport: opts.transport } : {}),
68
+ };
69
+ return new WorkflowClient(clientOpts);
70
+ }
71
+
72
+ /** Deploy `model` to the engine and assert the deployment is accepted. Resolves
73
+ * a skip (never throws) when no engine is reachable, so it is safe to call in
74
+ * unit-only CI; it throws only when a reachable engine REJECTS the model. */
75
+ export async function deploySmoke(model: Workflow, opts: DeploySmokeOptions = {}): Promise<DeploySmokeResult> {
76
+ const client = resolveClient(opts);
77
+ if (!client) {
78
+ return { deployed: false, skipped: true, reason: "no engine reachable (set baseUrl/client/WORKFLOW_GATEWAY_URL)" };
79
+ }
80
+ const result = await client.deploy(model);
81
+ if (!result || typeof result !== "object" || Object.keys(result).length === 0) {
82
+ throw new Error(`deploySmoke: engine did not accept "${model.id}" (empty deploy result)`);
83
+ }
84
+ return { deployed: true, skipped: false, result };
85
+ }
@@ -0,0 +1,140 @@
1
+ // A dependency-free XML reader, just enough to parse a BPMN 2.0 document into a
2
+ // tree the normalizer can canonicalize. BPMN files this package emits (and the
3
+ // hand-authored goldens) are plain XML — elements, attributes, text — with no
4
+ // DTDs, processing instructions beyond the `<?xml …?>` prolog, or mixed-content
5
+ // subtleties that would need a full parser. We keep prefixed names verbatim
6
+ // (`bpmn:serviceTask`, `zeebe:taskDefinition`) so the normalizer can reason about
7
+ // namespaces by local name.
8
+
9
+ /** A parsed XML element. `attrs` preserves declared attributes (entity-decoded);
10
+ * `children` are child elements in document order; `text` is the concatenated
11
+ * direct text content (trimmed), used for elements like `conditionExpression`. */
12
+ export interface XmlElement {
13
+ /** The qualified name as written, e.g. `bpmn:serviceTask` or `process`. */
14
+ name: string;
15
+ attrs: Record<string, string>;
16
+ children: XmlElement[];
17
+ text: string;
18
+ }
19
+
20
+ /** The local (un-prefixed) name of an element or attribute. */
21
+ export function localName(qualified: string): string {
22
+ const i = qualified.indexOf(":");
23
+ return i === -1 ? qualified : qualified.slice(i + 1);
24
+ }
25
+
26
+ function decodeEntities(s: string): string {
27
+ return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (m, body: string) => {
28
+ switch (body) {
29
+ case "lt":
30
+ return "<";
31
+ case "gt":
32
+ return ">";
33
+ case "amp":
34
+ return "&";
35
+ case "quot":
36
+ return '"';
37
+ case "apos":
38
+ return "'";
39
+ }
40
+ if (body[0] === "#") {
41
+ const code =
42
+ body[1] === "x" || body[1] === "X" ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10);
43
+ // Only decode a valid Unicode scalar value. `String.fromCodePoint` throws
44
+ // a `RangeError` for code points outside 0..0x10FFFF (e.g. `&#x110000;`),
45
+ // and surrogate halves (0xD800..0xDFFF) are not valid characters — treat
46
+ // any such reference as malformed and leave it verbatim rather than
47
+ // throwing an opaque exception out of `parseXml`.
48
+ const isScalar = Number.isInteger(code) && code >= 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff);
49
+ return isScalar ? String.fromCodePoint(code) : m;
50
+ }
51
+ return m;
52
+ });
53
+ }
54
+
55
+ function parseAttrs(src: string): Record<string, string> {
56
+ const attrs: Record<string, string> = {};
57
+ const re = /([^\s=/]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
58
+ let m: RegExpExecArray | null = re.exec(src);
59
+ while (m !== null) {
60
+ const value = m[3] !== undefined ? m[3] : (m[4] ?? "");
61
+ attrs[m[1]] = decodeEntities(value);
62
+ m = re.exec(src);
63
+ }
64
+ return attrs;
65
+ }
66
+
67
+ function appendText(el: XmlElement, chunk: string): void {
68
+ if (chunk) el.text = el.text ? `${el.text} ${chunk}` : chunk;
69
+ }
70
+
71
+ /** Parse an XML document into its root element. Throws on a malformed document
72
+ * (unbalanced tags, no root, or more than one top-level element). Comments,
73
+ * CDATA, the `<?xml?>` prolog and other processing instructions are handled;
74
+ * CDATA content contributes to `text`. */
75
+ export function parseXml(xml: string): XmlElement {
76
+ const root: XmlElement = { name: "#root", attrs: {}, children: [], text: "" };
77
+ const stack: XmlElement[] = [root];
78
+ let i = 0;
79
+ const n = xml.length;
80
+ while (i < n) {
81
+ const lt = xml.indexOf("<", i);
82
+ if (lt === -1) break;
83
+ if (lt > i) appendText(stack[stack.length - 1], decodeEntities(xml.slice(i, lt)).trim());
84
+ if (xml.startsWith("<!--", lt)) {
85
+ const end = xml.indexOf("-->", lt + 4);
86
+ if (end === -1) throw new Error("parseXml: unterminated comment");
87
+ i = end + 3;
88
+ continue;
89
+ }
90
+ if (xml.startsWith("<![CDATA[", lt)) {
91
+ const end = xml.indexOf("]]>", lt + 9);
92
+ if (end === -1) throw new Error("parseXml: unterminated CDATA");
93
+ appendText(stack[stack.length - 1], xml.slice(lt + 9, end).trim());
94
+ i = end + 3;
95
+ continue;
96
+ }
97
+ if (xml.startsWith("<?", lt) || xml.startsWith("<!", lt)) {
98
+ const end = xml.indexOf(">", lt + 2);
99
+ if (end === -1) throw new Error("parseXml: unterminated processing instruction / declaration");
100
+ i = end + 1;
101
+ continue;
102
+ }
103
+ const gt = xml.indexOf(">", lt);
104
+ if (gt === -1) throw new Error("parseXml: unterminated tag");
105
+ let inner = xml.slice(lt + 1, gt);
106
+ if (inner.startsWith("/")) {
107
+ const closeName = inner.slice(1).trim();
108
+ if (stack.length <= 1) throw new Error(`parseXml: unbalanced end tag </${closeName}>`);
109
+ const open = stack.pop();
110
+ if (open === undefined || open.name !== closeName) {
111
+ throw new Error(`parseXml: mismatched end tag </${closeName}> (expected </${open?.name ?? "#root"}>)`);
112
+ }
113
+ i = gt + 1;
114
+ continue;
115
+ }
116
+ const selfClosing = inner.endsWith("/");
117
+ if (selfClosing) inner = inner.slice(0, -1);
118
+ const nameMatch = /^\s*(\S+)/.exec(inner);
119
+ if (!nameMatch) throw new Error("parseXml: malformed start tag");
120
+ const name = nameMatch[1];
121
+ const attrs = parseAttrs(inner.slice(nameMatch[0].length));
122
+ const el: XmlElement = { name, attrs, children: [], text: "" };
123
+ stack[stack.length - 1].children.push(el);
124
+ if (!selfClosing) stack.push(el);
125
+ i = gt + 1;
126
+ }
127
+ if (stack.length !== 1) {
128
+ const unclosed = stack
129
+ .slice(1)
130
+ .map((el) => `<${el.name}>`)
131
+ .join(", ");
132
+ throw new Error(`parseXml: unclosed tag(s): ${unclosed}`);
133
+ }
134
+ if (root.children.length === 0) throw new Error("parseXml: no root element");
135
+ if (root.children.length > 1) {
136
+ const roots = root.children.map((el) => `<${el.name}>`).join(", ");
137
+ throw new Error(`parseXml: multiple root elements (${roots}) — a well-formed document has exactly one`);
138
+ }
139
+ return root.children[0];
140
+ }
package/src/types.ts CHANGED
@@ -52,36 +52,26 @@ export type StepHandler<
52
52
  bivarianceHack(job: Job<V>): Promise<R | void> | R | void;
53
53
  }["bivarianceHack"];
54
54
 
55
- /** A node in a declarative flow tree. Leaf activities carry optional data
56
- * envelopes (lifted to `nano:shape` + `dataEnvelope` in the model); structural
57
- * combinators carry nested `FlowNode[]` bodies. */
58
- export type FlowNode =
59
- | { kind: "run"; name: string; envelopes?: NodeEnvelopes }
60
- | { kind: "task"; name: string; envelopes?: NodeEnvelopes; jobType?: string }
61
- | { kind: "signal"; name: string; correlationKey: string; payload?: Envelope }
62
- | ({ kind: "timer"; name: string } & TimerAt)
63
- | { kind: "switch"; subject: string; cases: SwitchCase[]; default?: FlowNode[] }
64
- | { kind: "branch"; condition: string; then: FlowNode[]; else?: FlowNode[] }
65
- | { kind: "loop"; body: FlowNode[] }
66
- | { kind: "break" }
67
- | { kind: "continue" }
68
- | { kind: "parallel"; branches: FlowNode[][] }
69
- | {
70
- kind: "forEach";
71
- /** FEEL expression evaluating to the list to fan out over. */
72
- collection: string;
73
- /** Variable each item is bound to in the child's scope (`inputElement`). */
74
- itemVar: string;
75
- body: FlowNode[];
76
- /** Run children one at a time (sequential MI) instead of all at once. */
77
- sequential?: boolean;
78
- /** List variable that each child's `outputElement` is collected into. */
79
- outputCollection?: string;
80
- /** FEEL expression producing each child's contribution to `outputCollection`. */
81
- outputElement?: string;
82
- /** FEEL boolean that, once true, completes the body early. */
83
- completionCondition?: string;
84
- };
55
+ /** The OPEN registry of flow-node kinds — the single extension seam for the
56
+ * `FlowNode` union (epic #314, S0/#315). Each kind module under `src/nodes/`
57
+ * declaration-merges ONE property into this interface (`kindName: NodeShape`),
58
+ * so `FlowNode` grows without editing a central union here. The built-in kinds
59
+ * register `run`/`task`/`signal`/`timer`/`switch`/`branch`/`loop`/`break`/
60
+ * `continue`/`parallel`/`forEach` from their own modules through this same
61
+ * mechanism — see `src/nodes/README.md`.
62
+ *
63
+ * Invariant: every value type MUST be an object with a `kind` discriminant
64
+ * equal to its key, so `FlowNode` stays a discriminated union.
65
+ *
66
+ * This interface is intentionally empty here: it is the augmentation target the
67
+ * per-kind modules declaration-merge their variant into. */
68
+ export interface FlowNodeRegistry {}
69
+
70
+ /** A node in a declarative flow tree, derived from the {@link FlowNodeRegistry}.
71
+ * Leaf activities carry optional data envelopes (lifted to `nano:shape` +
72
+ * `dataEnvelope` in the model); structural combinators carry nested
73
+ * `FlowNode[]` bodies. */
74
+ export type FlowNode = FlowNodeRegistry[keyof FlowNodeRegistry];
85
75
 
86
76
  /** A timer intermediate-catch definition: exactly one of `after` (an ISO-8601
87
77
  * delay or FEEL expression) or `at` (an absolute instant or FEEL expression).