@nanobpm/workflow 0.8.1 → 0.9.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 (62) hide show
  1. package/README.md +1 -1
  2. package/dist/declarative.d.ts +172 -10
  3. package/dist/declarative.js +213 -355
  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 +104 -0
  12. package/dist/nodes/index.d.ts +11 -0
  13. package/dist/nodes/index.js +18 -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/registry.d.ts +33 -0
  19. package/dist/nodes/registry.js +71 -0
  20. package/dist/nodes/run.d.ts +10 -0
  21. package/dist/nodes/run.js +21 -0
  22. package/dist/nodes/signal.d.ts +11 -0
  23. package/dist/nodes/signal.js +21 -0
  24. package/dist/nodes/switch.d.ts +11 -0
  25. package/dist/nodes/switch.js +51 -0
  26. package/dist/nodes/task.d.ts +11 -0
  27. package/dist/nodes/task.js +21 -0
  28. package/dist/nodes/timer.d.ts +9 -0
  29. package/dist/nodes/timer.js +34 -0
  30. package/dist/test-support/diff.d.ts +8 -0
  31. package/dist/test-support/diff.js +70 -0
  32. package/dist/test-support/index.d.ts +8 -0
  33. package/dist/test-support/index.js +49 -0
  34. package/dist/test-support/normalize.d.ts +19 -0
  35. package/dist/test-support/normalize.js +245 -0
  36. package/dist/test-support/parity.d.ts +28 -0
  37. package/dist/test-support/parity.js +61 -0
  38. package/dist/test-support/xml.d.ts +17 -0
  39. package/dist/test-support/xml.js +135 -0
  40. package/dist/types.d.ts +20 -56
  41. package/package.json +14 -6
  42. package/src/declarative.ts +327 -359
  43. package/src/nodes/README.md +123 -0
  44. package/src/nodes/branch.ts +48 -0
  45. package/src/nodes/break.ts +25 -0
  46. package/src/nodes/continue.ts +24 -0
  47. package/src/nodes/forEach.ts +137 -0
  48. package/src/nodes/index.ts +19 -0
  49. package/src/nodes/loop.ts +34 -0
  50. package/src/nodes/parallel.ts +48 -0
  51. package/src/nodes/registry.ts +105 -0
  52. package/src/nodes/run.ts +29 -0
  53. package/src/nodes/signal.ts +29 -0
  54. package/src/nodes/switch.ts +56 -0
  55. package/src/nodes/task.ts +29 -0
  56. package/src/nodes/timer.ts +42 -0
  57. package/src/test-support/diff.ts +69 -0
  58. package/src/test-support/index.ts +53 -0
  59. package/src/test-support/normalize.ts +274 -0
  60. package/src/test-support/parity.ts +85 -0
  61. package/src/test-support/xml.ts +140 -0
  62. package/src/types.ts +20 -30
@@ -0,0 +1,34 @@
1
+ // Built-in flow-node kind: `timer` — a durable wait for a point in time (a BPMN
2
+ // timer intermediate catch event): exactly one of `{ after }` (a delay) or
3
+ // `{ at }` (an instant). Contributed through the extension seam (epic #314).
4
+ import { assertTimerDate, assertTimerDuration } from "../xml.js";
5
+ import { registerNodeKind } from "./registry.js";
6
+ registerNodeKind("timer", {
7
+ build: (api) => (name, opts) => {
8
+ api.claim(name);
9
+ if (!opts || typeof opts !== "object") {
10
+ throw new Error(`timer("${name}") needs exactly one of { after } (a delay) or { at } (an instant)`);
11
+ }
12
+ const hasAfter = "after" in opts && typeof opts.after === "string";
13
+ const hasAt = "at" in opts && typeof opts.at === "string";
14
+ if (hasAfter === hasAt) {
15
+ throw new Error(`timer("${name}") needs exactly one of { after } (a delay) or { at } (an instant)`);
16
+ }
17
+ if ("after" in opts) {
18
+ const after = opts.after.trim();
19
+ assertTimerDuration(`timer("${name}") after`, after);
20
+ api.out.push({ kind: "timer", name, after });
21
+ }
22
+ else {
23
+ const at = opts.at.trim();
24
+ assertTimerDate(`timer("${name}") at`, at);
25
+ api.out.push({ kind: "timer", name, at });
26
+ }
27
+ return api.self();
28
+ },
29
+ emit: (node, incoming, _loop, api) => {
30
+ api.addTimerCatchEvent(node);
31
+ api.connect(incoming, node.name);
32
+ return [api.newEdge(node.name)];
33
+ },
34
+ });
@@ -0,0 +1,8 @@
1
+ import type { CanonicalModel } from "./normalize.js";
2
+ /** True when two canonical models are structurally equal (all three multisets
3
+ * match). */
4
+ export declare function modelsEqual(expected: CanonicalModel, actual: CanonicalModel): boolean;
5
+ /** Render a legible red/green structural diff, or `""` when the two models are
6
+ * structurally equal. `-`/red is the `expected` (golden) side, `+`/green the
7
+ * `actual` (derived) side. */
8
+ export declare function diffModels(expected: CanonicalModel, actual: CanonicalModel): string;
@@ -0,0 +1,70 @@
1
+ // A legible red/green structural diff between two canonical models. Each of the
2
+ // three sections (flow nodes, sequence flows, message subscriptions) is compared
3
+ // as a MULTISET: a line present more times on one side than the other is
4
+ // reported, `-` (red) for "expected / golden only" and `+` (green) for "derived
5
+ // only". Equal models produce an empty diff.
6
+ const useColor = () => {
7
+ if (process.env.NO_COLOR)
8
+ return false;
9
+ if (process.env.FORCE_COLOR)
10
+ return true;
11
+ return Boolean(process.stdout?.isTTY);
12
+ };
13
+ const RED = "\x1b[31m";
14
+ const GREEN = "\x1b[32m";
15
+ const DIM = "\x1b[2m";
16
+ const RESET = "\x1b[0m";
17
+ function paint(code, s) {
18
+ return useColor() ? `${code}${s}${RESET}` : s;
19
+ }
20
+ /** Multiset difference: for each distinct line, the count on `expected` minus the
21
+ * count on `actual`. Positive → missing from `actual` (removed); negative →
22
+ * extra in `actual` (added). */
23
+ function multisetDiff(expected, actual) {
24
+ const counts = new Map();
25
+ for (const line of expected)
26
+ counts.set(line, (counts.get(line) ?? 0) + 1);
27
+ for (const line of actual)
28
+ counts.set(line, (counts.get(line) ?? 0) - 1);
29
+ const removed = [];
30
+ const added = [];
31
+ for (const [line, n] of counts) {
32
+ for (let k = 0; k < n; k++)
33
+ removed.push(line);
34
+ for (let k = 0; k < -n; k++)
35
+ added.push(line);
36
+ }
37
+ return { removed: removed.sort(), added: added.sort() };
38
+ }
39
+ function section(title, expected, actual) {
40
+ const { removed, added } = multisetDiff(expected, actual);
41
+ if (removed.length === 0 && added.length === 0)
42
+ return [];
43
+ const out = [paint(DIM, ` ${title}:`)];
44
+ for (const line of removed)
45
+ out.push(paint(RED, ` - ${line}`));
46
+ for (const line of added)
47
+ out.push(paint(GREEN, ` + ${line}`));
48
+ return out;
49
+ }
50
+ /** True when two canonical models are structurally equal (all three multisets
51
+ * match). */
52
+ export function modelsEqual(expected, actual) {
53
+ return diffModels(expected, actual) === "";
54
+ }
55
+ /** Render a legible red/green structural diff, or `""` when the two models are
56
+ * structurally equal. `-`/red is the `expected` (golden) side, `+`/green the
57
+ * `actual` (derived) side. */
58
+ export function diffModels(expected, actual) {
59
+ const lines = [
60
+ ...section("flow nodes", expected.nodes, actual.nodes),
61
+ ...section("sequence flows", expected.flows, actual.flows),
62
+ ...section("message subscriptions", expected.messages, actual.messages),
63
+ ];
64
+ if (lines.length === 0)
65
+ return "";
66
+ return [
67
+ paint(DIM, "structural mismatch (-expected/golden, +actual/derived):"),
68
+ ...lines,
69
+ ].join("\n");
70
+ }
@@ -0,0 +1,8 @@
1
+ export { normalize } from "./normalize.js";
2
+ export type { CanonicalModel } from "./normalize.js";
3
+ export { assertDerivationParity, deploySmoke } from "./parity.js";
4
+ export type { DerivedInput, DeploySmokeOptions, DeploySmokeResult } from "./parity.js";
5
+ export { diffModels, modelsEqual } from "./diff.js";
6
+ export { parseXml, localName } from "./xml.js";
7
+ export type { XmlElement } from "./xml.js";
8
+ export { isFlowBuilder, assemblyFailureMessage } from "../declarative.js";
@@ -0,0 +1,49 @@
1
+ // @nanobpm/workflow/test-support — the DERIVATION-PARITY HARNESS (the oracle).
2
+ //
3
+ // This is the reusable test-support surface S1–S6 (epic #314) import to assert
4
+ // their derived flows against the hand-authored golden `.bpmn` models vendored in
5
+ // `packages/workflow/test/fixtures/nwf/`. It ships as the package subpath export
6
+ // `@nanobpm/workflow/test-support`:
7
+ //
8
+ // import {
9
+ // normalize,
10
+ // assertDerivationParity,
11
+ // deploySmoke,
12
+ // } from "@nanobpm/workflow/test-support";
13
+ //
14
+ // PUBLIC SURFACE
15
+ // ─────────────────────────────────────────────────────────────────────────────
16
+ //
17
+ // normalize(bpmnXml: string): CanonicalModel
18
+ // Strip DI (`bpmndi:BPMNDiagram` layout) and canonicalize element ids, child
19
+ // ordering, and sequence-flow ids so only SEMANTIC structure remains. Returns
20
+ // a `CanonicalModel` — three sorted multisets: `nodes` (flow nodes with their
21
+ // type + definition + edge-degree signature), `flows` (sequence, attach, and
22
+ // containment edges by endpoint), and `messages` (each subscribed message's
23
+ // full definition — name plus `zeebe:subscription correlationKey` and
24
+ // `zeebe:properties` envelope, so correlationKey/envelope differences count).
25
+ // Two models mean the same thing iff their `CanonicalModel`s are equal.
26
+ //
27
+ // assertDerivationParity(derived, goldenBpmnPath): void
28
+ // `derived` is a `DeclarativeFlow` (its BPMN is derived for you) or derived
29
+ // BPMN XML. Normalizes both it and the golden at `goldenBpmnPath` and asserts
30
+ // structural equality over flow nodes, sequence flows, message subscriptions,
31
+ // and timer/boundary definitions — throwing a legible red/green structural
32
+ // diff on mismatch.
33
+ //
34
+ // deploySmoke(derivedModel, opts?): Promise<DeploySmokeResult>
35
+ // Deploy the derived model to the wasm/live engine and assert acceptance.
36
+ // Supply `{ client }`, `{ baseUrl }`, or set `WORKFLOW_GATEWAY_URL`; with no
37
+ // engine reachable it resolves `{ skipped: true }` (never throws) so unit-only
38
+ // CI stays green, and throws only when a reachable engine REJECTS the model.
39
+ //
40
+ // LOWER-LEVEL HELPERS (for custom assertions):
41
+ // modelsEqual(a, b): boolean — structural equality predicate.
42
+ // diffModels(expected, actual): string — the red/green diff ("" when equal).
43
+ // parseXml / localName — the dependency-free XML reader.
44
+ export { normalize } from "./normalize.js";
45
+ export { assertDerivationParity, deploySmoke } from "./parity.js";
46
+ export { diffModels, modelsEqual } from "./diff.js";
47
+ export { parseXml, localName } from "./xml.js";
48
+ // The internal builder invariant guard, exposed for the fail-fast guard test.
49
+ export { isFlowBuilder, assemblyFailureMessage } from "../declarative.js";
@@ -0,0 +1,19 @@
1
+ /** The id-agnostic, order-agnostic semantic structure of a BPMN model. Two
2
+ * models are structurally equal iff their three multisets are equal. */
3
+ export interface CanonicalModel {
4
+ /** Semantic descriptor of every flow node (task/gateway/event/subProcess),
5
+ * sorted. Each carries its type, definition, and edge-degree signature. */
6
+ nodes: string[];
7
+ /** Every sequence flow as `«fromNode» =[tag]=> «toNode»`, plus structural
8
+ * attach (boundary→host) and containment (subProcess→child) edges, sorted. */
9
+ flows: string[];
10
+ /** The full semantic identity of every message a catch event subscribes to,
11
+ * sorted (deduped): the serialized `<bpmn:message>` definition — its name plus
12
+ * the `zeebe:subscription correlationKey` and any `zeebe:properties` envelope —
13
+ * so a differing correlation key or envelope is a structural difference. */
14
+ messages: string[];
15
+ }
16
+ /** Normalize a BPMN XML document to its canonical semantic model. Strips DI and
17
+ * canonicalizes ids, child ordering, and sequence-flow ids so only semantic
18
+ * structure remains. */
19
+ export declare function normalize(bpmnXml: string): CanonicalModel;
@@ -0,0 +1,245 @@
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
+ import { localName, parseXml } from "./xml.js";
24
+ const FLOW_NODES = new Set([
25
+ "startEvent",
26
+ "endEvent",
27
+ "intermediateCatchEvent",
28
+ "intermediateThrowEvent",
29
+ "boundaryEvent",
30
+ "task",
31
+ "serviceTask",
32
+ "userTask",
33
+ "scriptTask",
34
+ "sendTask",
35
+ "receiveTask",
36
+ "manualTask",
37
+ "businessRuleTask",
38
+ "callActivity",
39
+ "subProcess",
40
+ "adHocSubProcess",
41
+ "transaction",
42
+ "exclusiveGateway",
43
+ "parallelGateway",
44
+ "inclusiveGateway",
45
+ "eventBasedGateway",
46
+ "complexGateway",
47
+ ]);
48
+ const REF_ATTRS = new Set(["messageRef", "errorRef", "signalRef", "escalationRef"]);
49
+ function isDI(el) {
50
+ const prefix = el.name.includes(":") ? el.name.slice(0, el.name.indexOf(":")) : "";
51
+ if (prefix === "bpmndi" || prefix === "di" || prefix === "dc" || prefix === "omgdi" || prefix === "omgdc") {
52
+ return true;
53
+ }
54
+ const l = localName(el.name);
55
+ return l === "BPMNDiagram" || l === "BPMNPlane" || l === "BPMNShape" || l === "BPMNEdge" || l === "BPMNLabel";
56
+ }
57
+ /** Accumulates the flat graph while walking every process / sub-process. */
58
+ class Collector {
59
+ refNames = new Map();
60
+ messageDefs = new Map();
61
+ nodes = new Map();
62
+ edges = [];
63
+ messages = new Set();
64
+ defaultFlows = new Set();
65
+ seqFlows = [];
66
+ /** Resolve a *Ref value to the referenced element's name (falling back to the
67
+ * raw ref only when the target is unknown), recording message subscriptions.
68
+ * A `messageRef` records the subscribed message's FULL semantic identity — the
69
+ * serialized `<bpmn:message>` definition (its name plus the `zeebe:subscription
70
+ * correlationKey` and any `zeebe:properties` envelope), not just its name — so
71
+ * two models whose catch events share a message name but differ in correlation
72
+ * key or envelope properties do NOT compare equal (the parity oracle would
73
+ * otherwise be blind to a wrong-correlationKey derivation). Falls back to the
74
+ * bare name only when the referenced message definition is unknown. */
75
+ resolveRef(attr, value) {
76
+ const name = this.refNames.get(value) ?? value;
77
+ if (attr === "messageRef") {
78
+ const def = this.messageDefs.get(value);
79
+ this.messages.add(def ? this.serialize(def) : name);
80
+ }
81
+ return `@${name}`;
82
+ }
83
+ /** Serialize a definition/extension descendant fully (all descendants), with
84
+ * sorted attributes (ids dropped, refs resolved) and sorted children, so the
85
+ * string is invariant to attribute/child ordering and to id renaming. */
86
+ serialize(el) {
87
+ const attrs = Object.entries(el.attrs)
88
+ .filter(([k]) => k !== "id")
89
+ .map(([k, v]) => `${k}=${REF_ATTRS.has(k) ? this.resolveRef(k, v) : v}`)
90
+ .sort();
91
+ const kids = el.children.filter((c) => !isDI(c)).map((c) => this.serialize(c)).sort();
92
+ const text = el.text ? `=${el.text}` : "";
93
+ return `${localName(el.name)}{${attrs.join(",")}}${text}[${kids.join(";")}]`;
94
+ }
95
+ /** The id-agnostic semantic descriptor of a flow node: its type, its own
96
+ * discriminating attributes, and its definition subtree — but NOT nested flow
97
+ * nodes / sequence flows (those are separate graph entities) and NOT cosmetic
98
+ * id / name / structural-ref attributes. */
99
+ nodeLabel(el) {
100
+ const excluded = new Set(["id", "name", "default", "attachedToRef", "sourceRef", "targetRef"]);
101
+ const attrs = Object.entries(el.attrs)
102
+ .filter(([k]) => !excluded.has(k))
103
+ .map(([k, v]) => `${k}=${REF_ATTRS.has(k) ? this.resolveRef(k, v) : v}`)
104
+ .sort();
105
+ const defs = el.children
106
+ .filter((c) => {
107
+ const cl = localName(c.name);
108
+ // Skip nested flow nodes / sequence flows (separate graph entities) and
109
+ // the `incoming`/`outgoing` flow-id back-references (fully redundant with
110
+ // the sequence-flow edges, and carrying raw ids that must not leak here).
111
+ return !isDI(c) && !FLOW_NODES.has(cl) && cl !== "sequenceFlow" && cl !== "incoming" && cl !== "outgoing";
112
+ })
113
+ .map((c) => this.serialize(c))
114
+ .sort();
115
+ return `${localName(el.name)}(${attrs.join(",")})[${defs.join(";")}]`;
116
+ }
117
+ registerNode(el) {
118
+ const id = el.attrs.id;
119
+ if (!id)
120
+ return;
121
+ this.nodes.set(id, { id, type: localName(el.name), label: this.nodeLabel(el) });
122
+ if (el.attrs.default)
123
+ this.defaultFlows.add(el.attrs.default);
124
+ }
125
+ /** Walk a container (process or sub-process), registering its flow nodes and
126
+ * sequence flows and recursing into nested sub-processes. `scope` is the
127
+ * enclosing sub-process id (containment edges point scope→child). */
128
+ collectContainer(container, scope) {
129
+ for (const child of container.children) {
130
+ if (isDI(child))
131
+ continue;
132
+ const l = localName(child.name);
133
+ if (FLOW_NODES.has(l)) {
134
+ this.registerNode(child);
135
+ const id = child.attrs.id;
136
+ if (id && scope)
137
+ this.edges.push({ kind: "contain", from: scope, to: id, tag: "" });
138
+ if (l === "boundaryEvent" && child.attrs.attachedToRef && id) {
139
+ this.edges.push({ kind: "attach", from: id, to: child.attrs.attachedToRef, tag: "" });
140
+ }
141
+ if (l === "subProcess" || l === "adHocSubProcess" || l === "transaction") {
142
+ this.collectContainer(child, id);
143
+ }
144
+ }
145
+ else if (l === "sequenceFlow") {
146
+ this.seqFlows.push(child);
147
+ }
148
+ }
149
+ }
150
+ /** Turn collected sequence-flow elements into endpoint edges once every node
151
+ * and default marker is known. */
152
+ finalizeFlows() {
153
+ for (const sf of this.seqFlows) {
154
+ const from = sf.attrs.sourceRef;
155
+ const to = sf.attrs.targetRef;
156
+ if (!from || !to)
157
+ continue;
158
+ const cond = sf.children.find((c) => localName(c.name) === "conditionExpression");
159
+ let tag = "";
160
+ if (cond?.text)
161
+ tag = `if:${cond.text}`;
162
+ else if (sf.attrs.id && this.defaultFlows.has(sf.attrs.id))
163
+ tag = "default";
164
+ this.edges.push({ kind: "seq", from, to, tag });
165
+ }
166
+ }
167
+ }
168
+ /** Record every referenceable root definition (`message`/`error`/`signal`/
169
+ * `escalation`) so a `*Ref` can be resolved to a stable name. */
170
+ function collectRefs(el, c) {
171
+ const l = localName(el.name);
172
+ if ((l === "message" || l === "error" || l === "signal" || l === "escalation") && el.attrs.id) {
173
+ c.refNames.set(el.attrs.id, el.attrs.name ?? el.attrs.errorCode ?? el.attrs.id);
174
+ if (l === "message")
175
+ c.messageDefs.set(el.attrs.id, el);
176
+ }
177
+ for (const child of el.children)
178
+ if (!isDI(child))
179
+ collectRefs(child, c);
180
+ }
181
+ function findContainers(el, out) {
182
+ const l = localName(el.name);
183
+ if (l === "process")
184
+ out.push(el);
185
+ for (const child of el.children)
186
+ if (!isDI(child))
187
+ findContainers(child, out);
188
+ }
189
+ /** Normalize a BPMN XML document to its canonical semantic model. Strips DI and
190
+ * canonicalizes ids, child ordering, and sequence-flow ids so only semantic
191
+ * structure remains. */
192
+ export function normalize(bpmnXml) {
193
+ const root = parseXml(bpmnXml);
194
+ const c = new Collector();
195
+ collectRefs(root, c);
196
+ const processes = [];
197
+ findContainers(root, processes);
198
+ if (processes.length === 0)
199
+ throw new Error("normalize: no <process> element found");
200
+ for (const p of processes)
201
+ c.collectContainer(p, undefined);
202
+ c.finalizeFlows();
203
+ // Per-node edge-degree signature — captures wiring (how many sequence flows in
204
+ // / out, whether it hosts or is a boundary, whether it contains or is
205
+ // contained) so a rewiring that preserves node labels still shows up.
206
+ const deg = new Map();
207
+ const bump = (id) => {
208
+ let d = deg.get(id);
209
+ if (!d) {
210
+ d = { si: 0, so: 0, at: 0, ah: 0, ci: 0, co: 0 };
211
+ deg.set(id, d);
212
+ }
213
+ return d;
214
+ };
215
+ for (const e of c.edges) {
216
+ if (e.kind === "seq") {
217
+ bump(e.from).so += 1;
218
+ bump(e.to).si += 1;
219
+ }
220
+ else if (e.kind === "attach") {
221
+ bump(e.from).at += 1; // this node is a boundary attached to something
222
+ bump(e.to).ah += 1; // this node hosts a boundary
223
+ }
224
+ else {
225
+ bump(e.from).co += 1; // this sub-process contains children
226
+ bump(e.to).ci += 1; // this node is contained
227
+ }
228
+ }
229
+ const labelWithDegree = (id) => {
230
+ const node = c.nodes.get(id);
231
+ if (!node)
232
+ return `«unknown:${id}»`;
233
+ const d = deg.get(id) ?? { si: 0, so: 0, at: 0, ah: 0, ci: 0, co: 0 };
234
+ return `${node.label}<in=${d.si},out=${d.so},boundary=${d.at},hosts=${d.ah},contained=${d.ci},contains=${d.co}>`;
235
+ };
236
+ const nodes = [...c.nodes.keys()].map(labelWithDegree).sort();
237
+ const flows = c.edges
238
+ .map((e) => {
239
+ const arrow = e.kind === "attach" ? "--attach-->" : e.kind === "contain" ? "--contains-->" : `=[${e.tag}]=>`;
240
+ return `${labelWithDegree(e.from)} ${arrow} ${labelWithDegree(e.to)}`;
241
+ })
242
+ .sort();
243
+ const messages = [...c.messages].sort();
244
+ return { nodes, flows, messages };
245
+ }
@@ -0,0 +1,28 @@
1
+ import { WorkflowClient } from "../client.js";
2
+ import type { DeclarativeFlow, DeployResult, Workflow } from "../types.js";
3
+ /** A derived flow, or the derived BPMN XML directly. */
4
+ export type DerivedInput = DeclarativeFlow | string;
5
+ /** Derive `derived`'s BPMN, normalize it and the golden at `goldenBpmnPath`, and
6
+ * assert structural equality. Throws with a legible structural diff on
7
+ * mismatch. Returns silently on parity. */
8
+ export declare function assertDerivationParity(derived: DerivedInput, goldenBpmnPath: string): void;
9
+ /** Options for {@link deploySmoke}. Supply a pre-built `client`, a `baseUrl`
10
+ * (a client is built for you), or rely on the `WORKFLOW_GATEWAY_URL` env var. */
11
+ export interface DeploySmokeOptions {
12
+ client?: WorkflowClient;
13
+ baseUrl?: string;
14
+ token?: string;
15
+ transport?: "auto" | "falcon" | "rest";
16
+ }
17
+ /** The outcome of a {@link deploySmoke}: either a completed deployment, or a
18
+ * skip because no engine was reachable. */
19
+ export interface DeploySmokeResult {
20
+ deployed: boolean;
21
+ skipped: boolean;
22
+ reason?: string;
23
+ result?: DeployResult;
24
+ }
25
+ /** Deploy `model` to the engine and assert the deployment is accepted. Resolves
26
+ * a skip (never throws) when no engine is reachable, so it is safe to call in
27
+ * unit-only CI; it throws only when a reachable engine REJECTS the model. */
28
+ export declare function deploySmoke(model: Workflow, opts?: DeploySmokeOptions): Promise<DeploySmokeResult>;
@@ -0,0 +1,61 @@
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
+ import { readFileSync } from "node:fs";
13
+ import { WorkflowClient } from "../client.js";
14
+ import { declarativeToBpmn } from "../declarative.js";
15
+ import { diffModels } from "./diff.js";
16
+ import { normalize } from "./normalize.js";
17
+ function toBpmnXml(input) {
18
+ if (typeof input === "string")
19
+ return input;
20
+ return declarativeToBpmn(input);
21
+ }
22
+ /** Derive `derived`'s BPMN, normalize it and the golden at `goldenBpmnPath`, and
23
+ * assert structural equality. Throws with a legible structural diff on
24
+ * mismatch. Returns silently on parity. */
25
+ export function assertDerivationParity(derived, goldenBpmnPath) {
26
+ const derivedXml = toBpmnXml(derived);
27
+ const goldenXml = readFileSync(goldenBpmnPath, "utf8");
28
+ const golden = normalize(goldenXml);
29
+ const actual = normalize(derivedXml);
30
+ const diff = diffModels(golden, actual);
31
+ if (diff) {
32
+ throw new Error(`derivation parity failed against ${goldenBpmnPath}:\n${diff}`);
33
+ }
34
+ }
35
+ function resolveClient(opts) {
36
+ if (opts.client)
37
+ return opts.client;
38
+ const baseUrl = opts.baseUrl ?? process.env.WORKFLOW_GATEWAY_URL;
39
+ if (!baseUrl)
40
+ return undefined;
41
+ const clientOpts = {
42
+ baseUrl,
43
+ ...(opts.token ? { token: opts.token } : {}),
44
+ ...(opts.transport ? { transport: opts.transport } : {}),
45
+ };
46
+ return new WorkflowClient(clientOpts);
47
+ }
48
+ /** Deploy `model` to the engine and assert the deployment is accepted. Resolves
49
+ * a skip (never throws) when no engine is reachable, so it is safe to call in
50
+ * unit-only CI; it throws only when a reachable engine REJECTS the model. */
51
+ export async function deploySmoke(model, opts = {}) {
52
+ const client = resolveClient(opts);
53
+ if (!client) {
54
+ return { deployed: false, skipped: true, reason: "no engine reachable (set baseUrl/client/WORKFLOW_GATEWAY_URL)" };
55
+ }
56
+ const result = await client.deploy(model);
57
+ if (!result || typeof result !== "object" || Object.keys(result).length === 0) {
58
+ throw new Error(`deploySmoke: engine did not accept "${model.id}" (empty deploy result)`);
59
+ }
60
+ return { deployed: true, skipped: false, result };
61
+ }
@@ -0,0 +1,17 @@
1
+ /** A parsed XML element. `attrs` preserves declared attributes (entity-decoded);
2
+ * `children` are child elements in document order; `text` is the concatenated
3
+ * direct text content (trimmed), used for elements like `conditionExpression`. */
4
+ export interface XmlElement {
5
+ /** The qualified name as written, e.g. `bpmn:serviceTask` or `process`. */
6
+ name: string;
7
+ attrs: Record<string, string>;
8
+ children: XmlElement[];
9
+ text: string;
10
+ }
11
+ /** The local (un-prefixed) name of an element or attribute. */
12
+ export declare function localName(qualified: string): string;
13
+ /** Parse an XML document into its root element. Throws on a malformed document
14
+ * (unbalanced tags, no root, or more than one top-level element). Comments,
15
+ * CDATA, the `<?xml?>` prolog and other processing instructions are handled;
16
+ * CDATA content contributes to `text`. */
17
+ export declare function parseXml(xml: string): XmlElement;