wirepulse 0.0.0-stage → 0.2.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.
@@ -0,0 +1,6 @@
1
+ import type { DiagramSpec, LayoutResult } from "./types.js";
2
+ /**
3
+ * Compute automatic topological columns (layers) and balanced rows
4
+ * while respecting any explicit `col`/`row` or `x`/`y` coordinates on nodes.
5
+ */
6
+ export declare function layoutDiagram(spec: DiagramSpec): LayoutResult;
package/dist/layout.js ADDED
@@ -0,0 +1,387 @@
1
+ const NODE_W = 204;
2
+ const NODE_H = 76;
3
+ const GAP_X = 112;
4
+ const GAP_Y = 52;
5
+ const PAD_X = 48;
6
+ const PAD_TOP = 36;
7
+ const PAD_BOTTOM = 44;
8
+ const HEADER_H = 72;
9
+ const GROUP_PAD_X = 22;
10
+ const GROUP_PAD_TOP = 34;
11
+ const GROUP_PAD_BOTTOM = 20;
12
+ /**
13
+ * Compute automatic topological columns (layers) and balanced rows
14
+ * while respecting any explicit `col`/`row` or `x`/`y` coordinates on nodes.
15
+ */
16
+ export function layoutDiagram(spec) {
17
+ const hasHeader = Boolean(spec.title || spec.subtitle);
18
+ const headerHeight = hasHeader ? HEADER_H : 0;
19
+ if (spec.nodes.length === 0) {
20
+ return {
21
+ width: 680,
22
+ height: 300,
23
+ headerHeight,
24
+ nodes: [],
25
+ groups: [],
26
+ edges: [],
27
+ };
28
+ }
29
+ const nodeIds = spec.nodes.map((n) => n.id);
30
+ const nodeById = new Map(spec.nodes.map((n) => [n.id, n]));
31
+ // 1. Build adjacency for topological layering
32
+ const outgoing = new Map();
33
+ const incoming = new Map();
34
+ const inDegree = new Map();
35
+ for (const id of nodeIds) {
36
+ outgoing.set(id, []);
37
+ incoming.set(id, []);
38
+ inDegree.set(id, 0);
39
+ }
40
+ for (const e of spec.edges) {
41
+ if (e.from === e.to)
42
+ continue;
43
+ if (!nodeById.has(e.from) || !nodeById.has(e.to))
44
+ continue;
45
+ outgoing.get(e.from).push(e.to);
46
+ incoming.get(e.to).push(e.from);
47
+ inDegree.set(e.to, (inDegree.get(e.to) ?? 0) + 1);
48
+ }
49
+ // Kahn's algorithm with longest-path layer assignment (cycle-safe)
50
+ const autoLayer = new Map();
51
+ const queue = [];
52
+ const tempIn = new Map(inDegree);
53
+ for (const id of nodeIds) {
54
+ if ((tempIn.get(id) ?? 0) === 0) {
55
+ queue.push(id);
56
+ autoLayer.set(id, 0);
57
+ }
58
+ }
59
+ const visited = new Set();
60
+ while (queue.length > 0) {
61
+ const u = queue.shift();
62
+ if (visited.has(u))
63
+ continue;
64
+ visited.add(u);
65
+ const uLayer = autoLayer.get(u) ?? 0;
66
+ for (const v of outgoing.get(u) ?? []) {
67
+ const nextLayer = Math.max(autoLayer.get(v) ?? 0, uLayer + 1);
68
+ autoLayer.set(v, nextLayer);
69
+ const rem = (tempIn.get(v) ?? 1) - 1;
70
+ tempIn.set(v, rem);
71
+ if (rem === 0)
72
+ queue.push(v);
73
+ }
74
+ }
75
+ // Any remaining cycle nodes get placed cleanly
76
+ for (const id of nodeIds) {
77
+ if (!autoLayer.has(id)) {
78
+ const parentLayers = (incoming.get(id) ?? [])
79
+ .map((p) => autoLayer.get(p))
80
+ .filter((l) => l !== undefined);
81
+ autoLayer.set(id, parentLayers.length > 0 ? Math.max(...parentLayers) + 1 : 0);
82
+ }
83
+ }
84
+ // 2. Assign final col & row (respecting explicit col/row)
85
+ const isTB = spec.direction === "TB";
86
+ const layerBuckets = new Map();
87
+ for (const node of spec.nodes) {
88
+ const layer = isTB
89
+ ? (node.row ?? autoLayer.get(node.id) ?? 0)
90
+ : (node.col ?? autoLayer.get(node.id) ?? 0);
91
+ const bucket = layerBuckets.get(layer) ?? [];
92
+ bucket.push(node);
93
+ layerBuckets.set(layer, bucket);
94
+ }
95
+ const sortedLayers = [...layerBuckets.keys()].sort((a, b) => a - b);
96
+ // Sort nodes within each layer using barycenter of upstream neighbors (reduces crossings)
97
+ const assignedCross = new Map();
98
+ for (const layer of sortedLayers) {
99
+ const bucket = layerBuckets.get(layer);
100
+ bucket.sort((a, b) => {
101
+ const explicitA = isTB ? a.col : a.row;
102
+ const explicitB = isTB ? b.col : b.row;
103
+ if (explicitA !== undefined && explicitB !== undefined)
104
+ return explicitA - explicitB;
105
+ if (explicitA !== undefined)
106
+ return -1;
107
+ if (explicitB !== undefined)
108
+ return 1;
109
+ const avgA = averageParentPos(a.id, incoming, assignedCross);
110
+ const avgB = averageParentPos(b.id, incoming, assignedCross);
111
+ if (avgA !== avgB)
112
+ return avgA - avgB;
113
+ // Group siblings together
114
+ if (a.group && b.group && a.group !== b.group) {
115
+ return a.group.localeCompare(b.group);
116
+ }
117
+ return 0;
118
+ });
119
+ // Assign integer cross-axis positions avoiding collisions with explicit positions
120
+ const used = new Set();
121
+ for (const n of bucket) {
122
+ const explicit = isTB ? n.col : n.row;
123
+ if (explicit !== undefined) {
124
+ used.add(explicit);
125
+ assignedCross.set(n.id, explicit);
126
+ }
127
+ }
128
+ let cursor = 0;
129
+ for (const n of bucket) {
130
+ if (assignedCross.has(n.id))
131
+ continue;
132
+ while (used.has(cursor))
133
+ cursor++;
134
+ used.add(cursor);
135
+ assignedCross.set(n.id, cursor);
136
+ cursor++;
137
+ }
138
+ }
139
+ // Compute max cross count per layer so narrower layers are vertically centered nicely
140
+ const layerMeta = new Map();
141
+ let globalMaxSpan = 0;
142
+ for (const layer of sortedLayers) {
143
+ const bucket = layerBuckets.get(layer);
144
+ const positions = bucket.map((n) => assignedCross.get(n.id) ?? 0);
145
+ const minC = Math.min(...positions);
146
+ const maxC = Math.max(...positions);
147
+ layerMeta.set(layer, { minCross: minC, maxCross: maxC });
148
+ globalMaxSpan = Math.max(globalMaxSpan, maxC - minC);
149
+ }
150
+ const hasGroups = spec.groups.length > 0;
151
+ const extraTop = hasGroups ? GROUP_PAD_TOP : 0;
152
+ const extraSide = hasGroups ? GROUP_PAD_X : 0;
153
+ // 3. Calculate pixel coordinates
154
+ const layoutNodes = [];
155
+ const layoutNodeMap = new Map();
156
+ for (const node of spec.nodes) {
157
+ const layer = isTB
158
+ ? (node.row ?? autoLayer.get(node.id) ?? 0)
159
+ : (node.col ?? autoLayer.get(node.id) ?? 0);
160
+ const cross = assignedCross.get(node.id) ?? 0;
161
+ const meta = layerMeta.get(layer);
162
+ const span = meta.maxCross - meta.minCross;
163
+ // Center single/fewer nodes cleanly unless they have explicit grid placement
164
+ const hasExplicitCross = isTB ? node.col !== undefined : node.row !== undefined;
165
+ const centerOffset = hasExplicitCross ? 0 : (globalMaxSpan - span) / 2;
166
+ const col = isTB ? cross : layer;
167
+ const row = isTB ? layer : cross;
168
+ const computedX = node.x ??
169
+ PAD_X +
170
+ extraSide +
171
+ (isTB ? (cross - meta.minCross + centerOffset) : layer) * (NODE_W + GAP_X);
172
+ const computedY = node.y ??
173
+ PAD_TOP +
174
+ headerHeight +
175
+ extraTop +
176
+ (isTB ? layer : (cross - meta.minCross + centerOffset)) * (NODE_H + GAP_Y);
177
+ const ln = {
178
+ node,
179
+ col,
180
+ row,
181
+ x: Math.round(computedX),
182
+ y: Math.round(computedY),
183
+ width: NODE_W,
184
+ height: NODE_H,
185
+ };
186
+ layoutNodes.push(ln);
187
+ layoutNodeMap.set(node.id, ln);
188
+ }
189
+ // Normalize negative coordinates if user passed custom x/y or negative col/row
190
+ const minX = Math.min(...layoutNodes.map((n) => n.x));
191
+ const minY = Math.min(...layoutNodes.map((n) => n.y));
192
+ const shiftX = minX < PAD_X + extraSide ? PAD_X + extraSide - minX : 0;
193
+ const shiftY = minY < PAD_TOP + headerHeight + extraTop
194
+ ? PAD_TOP + headerHeight + extraTop - minY
195
+ : 0;
196
+ if (shiftX !== 0 || shiftY !== 0) {
197
+ for (const ln of layoutNodes) {
198
+ ln.x = Math.round(ln.x + shiftX);
199
+ ln.y = Math.round(ln.y + shiftY);
200
+ }
201
+ }
202
+ // 4. Compute group bounding boxes
203
+ const layoutGroups = [];
204
+ for (const group of spec.groups) {
205
+ const members = layoutNodes.filter((ln) => ln.node.group === group.id);
206
+ if (members.length === 0)
207
+ continue;
208
+ const gx1 = Math.min(...members.map((m) => m.x)) - GROUP_PAD_X;
209
+ const gy1 = Math.min(...members.map((m) => m.y)) - GROUP_PAD_TOP;
210
+ const gx2 = Math.max(...members.map((m) => m.x + m.width)) + GROUP_PAD_X;
211
+ const gy2 = Math.max(...members.map((m) => m.y + m.height)) + GROUP_PAD_BOTTOM;
212
+ layoutGroups.push({
213
+ group,
214
+ x: Math.round(gx1),
215
+ y: Math.round(gy1),
216
+ width: Math.round(gx2 - gx1),
217
+ height: Math.round(gy2 - gy1),
218
+ });
219
+ }
220
+ // 5. Route edges with distributed anchor ports
221
+ const outCounts = new Map();
222
+ const inCounts = new Map();
223
+ const outSeen = new Map();
224
+ const inSeen = new Map();
225
+ for (const e of spec.edges) {
226
+ outCounts.set(e.from, (outCounts.get(e.from) ?? 0) + 1);
227
+ inCounts.set(e.to, (inCounts.get(e.to) ?? 0) + 1);
228
+ }
229
+ const layoutEdges = [];
230
+ for (const edge of spec.edges) {
231
+ const src = layoutNodeMap.get(edge.from);
232
+ const dst = layoutNodeMap.get(edge.to);
233
+ if (!src || !dst)
234
+ continue;
235
+ const outIdx = outSeen.get(edge.from) ?? 0;
236
+ outSeen.set(edge.from, outIdx + 1);
237
+ const outTotal = outCounts.get(edge.from) ?? 1;
238
+ const inIdx = inSeen.get(edge.to) ?? 0;
239
+ inSeen.set(edge.to, inIdx + 1);
240
+ const inTotal = inCounts.get(edge.to) ?? 1;
241
+ const color = edge.color ?? src.node.color ?? "cyan";
242
+ const routed = routeEdge(src, dst, outIdx, outTotal, inIdx, inTotal, edge.curve ?? "smooth");
243
+ layoutEdges.push({
244
+ edge,
245
+ ...routed,
246
+ color,
247
+ });
248
+ }
249
+ // 6. Final canvas dimensions
250
+ const maxRight = Math.max(...layoutNodes.map((n) => n.x + n.width), ...layoutGroups.map((g) => g.x + g.width), 560);
251
+ const maxBottom = Math.max(...layoutNodes.map((n) => n.y + n.height), ...layoutGroups.map((g) => g.y + g.height), 240);
252
+ return {
253
+ width: Math.round(maxRight + PAD_X),
254
+ height: Math.round(maxBottom + PAD_BOTTOM),
255
+ headerHeight,
256
+ nodes: layoutNodes,
257
+ groups: layoutGroups,
258
+ edges: layoutEdges,
259
+ };
260
+ }
261
+ function averageParentPos(id, incoming, assignedCross) {
262
+ const parents = incoming.get(id) ?? [];
263
+ const vals = parents
264
+ .map((p) => assignedCross.get(p))
265
+ .filter((v) => v !== undefined);
266
+ if (vals.length === 0)
267
+ return 0;
268
+ return vals.reduce((a, b) => a + b, 0) / vals.length;
269
+ }
270
+ function portOffset(index, total, span) {
271
+ if (total <= 1)
272
+ return 0;
273
+ const maxOffset = Math.min(span * 0.28, (total - 1) * 11);
274
+ return -maxOffset + (2 * maxOffset * index) / (total - 1);
275
+ }
276
+ function routeEdge(src, dst, outIdx, outTotal, inIdx, inTotal, curve) {
277
+ const srcCx = src.x + src.width / 2;
278
+ const srcCy = src.y + src.height / 2;
279
+ const dstCx = dst.x + dst.width / 2;
280
+ const dstCy = dst.y + dst.height / 2;
281
+ const dx = dstCx - srcCx;
282
+ const dy = dstCy - srcCy;
283
+ // Choose primary exit/entry faces based on relative geometry
284
+ const horizontal = Math.abs(dx) >= Math.abs(dy) * 0.75;
285
+ let startX;
286
+ let startY;
287
+ let endX;
288
+ let endY;
289
+ if (horizontal) {
290
+ const goingRight = dx >= 0;
291
+ startX = goingRight ? src.x + src.width : src.x;
292
+ startY = srcCy + portOffset(outIdx, outTotal, src.height);
293
+ endX = goingRight ? dst.x : dst.x + dst.width;
294
+ endY = dstCy + portOffset(inIdx, inTotal, dst.height);
295
+ }
296
+ else {
297
+ const goingDown = dy >= 0;
298
+ startX = srcCx + portOffset(outIdx, outTotal, src.width);
299
+ startY = goingDown ? src.y + src.height : src.y;
300
+ endX = dstCx + portOffset(inIdx, inTotal, dst.width);
301
+ endY = goingDown ? dst.y : dst.y + dst.height;
302
+ }
303
+ startX = Math.round(startX);
304
+ startY = Math.round(startY);
305
+ endX = Math.round(endX);
306
+ endY = Math.round(endY);
307
+ if (curve === "straight") {
308
+ return {
309
+ pathD: `M ${startX} ${startY} L ${endX} ${endY}`,
310
+ reversePathD: `M ${endX} ${endY} L ${startX} ${startY}`,
311
+ labelX: Math.round((startX + endX) / 2),
312
+ labelY: Math.round((startY + endY) / 2 - 8),
313
+ startX,
314
+ startY,
315
+ endX,
316
+ endY,
317
+ };
318
+ }
319
+ if (curve === "ortho") {
320
+ const midX = Math.round((startX + endX) / 2);
321
+ const midY = Math.round((startY + endY) / 2);
322
+ if (horizontal) {
323
+ return {
324
+ pathD: `M ${startX} ${startY} L ${midX} ${startY} L ${midX} ${endY} L ${endX} ${endY}`,
325
+ reversePathD: `M ${endX} ${endY} L ${midX} ${endY} L ${midX} ${startY} L ${startX} ${startY}`,
326
+ labelX: midX,
327
+ labelY: midY - 6,
328
+ startX,
329
+ startY,
330
+ endX,
331
+ endY,
332
+ };
333
+ }
334
+ return {
335
+ pathD: `M ${startX} ${startY} L ${startX} ${midY} L ${endX} ${midY} L ${endX} ${endY}`,
336
+ reversePathD: `M ${endX} ${endY} L ${endX} ${midY} L ${startX} ${midY} L ${startX} ${startY}`,
337
+ labelX: midX,
338
+ labelY: midY - 8,
339
+ startX,
340
+ startY,
341
+ endX,
342
+ endY,
343
+ };
344
+ }
345
+ // Smooth cubic Bezier curve
346
+ if (horizontal) {
347
+ const dist = Math.max(36, Math.abs(endX - startX) * 0.46);
348
+ const dir = endX >= startX ? 1 : -1;
349
+ const c1x = Math.round(startX + dir * dist);
350
+ const c1y = startY;
351
+ const c2x = Math.round(endX - dir * dist);
352
+ const c2y = endY;
353
+ // Cubic Bezier midpoint at t=0.5
354
+ const labelX = Math.round(0.125 * startX + 0.375 * c1x + 0.375 * c2x + 0.125 * endX);
355
+ const labelY = Math.round(0.125 * startY + 0.375 * c1y + 0.375 * c2y + 0.125 * endY);
356
+ return {
357
+ pathD: `M ${startX} ${startY} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${endX} ${endY}`,
358
+ reversePathD: `M ${endX} ${endY} C ${c2x} ${c2y}, ${c1x} ${c1y}, ${startX} ${startY}`,
359
+ labelX,
360
+ labelY,
361
+ startX,
362
+ startY,
363
+ endX,
364
+ endY,
365
+ };
366
+ }
367
+ else {
368
+ const dist = Math.max(32, Math.abs(endY - startY) * 0.46);
369
+ const dir = endY >= startY ? 1 : -1;
370
+ const c1x = startX;
371
+ const c1y = Math.round(startY + dir * dist);
372
+ const c2x = endX;
373
+ const c2y = Math.round(endY - dir * dist);
374
+ const labelX = Math.round(0.125 * startX + 0.375 * c1x + 0.375 * c2x + 0.125 * endX);
375
+ const labelY = Math.round(0.125 * startY + 0.375 * c1y + 0.375 * c2y + 0.125 * endY);
376
+ return {
377
+ pathD: `M ${startX} ${startY} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${endX} ${endY}`,
378
+ reversePathD: `M ${endX} ${endY} C ${c2x} ${c2y}, ${c1x} ${c1y}, ${startX} ${startY}`,
379
+ labelX,
380
+ labelY,
381
+ startX,
382
+ startY,
383
+ endX,
384
+ endY,
385
+ };
386
+ }
387
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Detect whether a text string looks like a Mermaid flowchart/graph definition.
3
+ */
4
+ export declare function isMermaidSource(source: string): boolean;
5
+ /**
6
+ * Convert a Mermaid `flowchart` / `graph` diagram into clean, animated `wirepulse` `.wp` DSL
7
+ * with automatic semantic icon & color inference.
8
+ */
9
+ export declare function convertMermaidToWirepulse(mermaidSource: string, options?: {
10
+ title?: string;
11
+ }): string;
@@ -0,0 +1,278 @@
1
+ const GROUP_COLORS = ["cyan", "violet", "emerald", "amber", "blue", "rose"];
2
+ /**
3
+ * Infer a crisp semantic icon and accent color from a node's label/shape
4
+ * so converted Mermaid diagrams instantly look hand-crafted.
5
+ */
6
+ function inferStyleFromLabel(label, shapeHint) {
7
+ const lower = label.toLowerCase();
8
+ if (/\b(redis|cache|memcached|cdn|fastly|cloudflare|edge)\b/.test(lower)) {
9
+ return { icon: "bolt", color: "amber" };
10
+ }
11
+ if (shapeHint === "db" || /\b(postgres|mysql|mongo|sqlite|sql|database|db|supabase|dynamo|vector|pgvector|qdrant|pinecone)\b/.test(lower)) {
12
+ return { icon: "database", color: "emerald" };
13
+ }
14
+ if (/\b(kafka|queue|sqs|rabbitmq|pubsub|event|stream|bus|broker)\b/.test(lower)) {
15
+ return { icon: "queue", color: "rose" };
16
+ }
17
+ if (/\b(auth|oauth|jwt|gateway|firewall|waf|guard|security|shield|proxy|nginx)\b/.test(lower)) {
18
+ return { icon: "shield", color: "violet", pulse: true };
19
+ }
20
+ if (/\b(ai|llm|agent|claude|gpt|gemini|model|openai|anthropic|rag|mcp|embed)\b/.test(lower)) {
21
+ return { icon: "sparkles", color: "violet", pulse: true };
22
+ }
23
+ if (/\b(browser|web|client|frontend|react|next|vue|ui|app|spa)\b/.test(lower)) {
24
+ return { icon: "browser", color: "cyan", pulse: true };
25
+ }
26
+ if (/\b(mobile|ios|android|phone)\b/.test(lower)) {
27
+ return { icon: "mobile", color: "cyan", pulse: true };
28
+ }
29
+ if (/\b(user|customer|dev|developer|admin)\b/.test(lower)) {
30
+ return { icon: "user", color: "cyan", pulse: true };
31
+ }
32
+ if (/\b(cli|terminal|shell|bash|ssh)\b/.test(lower)) {
33
+ return { icon: "terminal", color: "cyan", pulse: true };
34
+ }
35
+ if (/\b(git|github|repo|pr|branch|ci|cd|action|deploy)\b/.test(lower)) {
36
+ return { icon: "git", color: "blue" };
37
+ }
38
+ if (/\b(docker|container|k8s|kubernetes|pod|helm|build)\b/.test(lower)) {
39
+ return { icon: "box", color: "blue" };
40
+ }
41
+ if (/\b(s3|bucket|storage|blob|disk|file|cdn)\b/.test(lower)) {
42
+ return { icon: "storage", color: "amber" };
43
+ }
44
+ if (/\b(worker|lambda|function|cron|job|processor)\b/.test(lower)) {
45
+ return { icon: "lambda", color: "orange" };
46
+ }
47
+ if (/\b(api|service|server|backend|node|go|rust|python|micro)\b/.test(lower)) {
48
+ return { icon: "server", color: "blue" };
49
+ }
50
+ if (/\b(search|elastic|algolia|bm25|index)\b/.test(lower)) {
51
+ return { icon: "search", color: "amber" };
52
+ }
53
+ if (/\b(webhook|stripe|payment|billing|mail|email|notify)\b/.test(lower)) {
54
+ return { icon: "plug", color: "orange" };
55
+ }
56
+ if (/\b(cloud|aws|gcp|azure|internet|web)\b/.test(lower)) {
57
+ return { icon: "cloud", color: "cyan" };
58
+ }
59
+ if (shapeHint === "decision") {
60
+ return { icon: "layers", color: "amber" };
61
+ }
62
+ return { icon: "server", color: "blue" };
63
+ }
64
+ function sanitizeId(raw) {
65
+ const cleaned = raw.trim().replace(/[^a-zA-Z0-9_-]/g, "_");
66
+ return cleaned || "node";
67
+ }
68
+ function parseNodeToken(token) {
69
+ const trimmed = token.trim();
70
+ // Match shapes: id[(Label)], id([Label]), id((Label)), id{Label}, id[Label], id(Label)
71
+ const patterns = [
72
+ { re: /^([a-zA-Z0-9_-]+)\[\((.+?)\)\]$/, hint: "db" },
73
+ { re: /^([a-zA-Z0-9_-]+)\(\[(.+?)\]\)$/, hint: "default" },
74
+ { re: /^([a-zA-Z0-9_-]+)\(\((.+?)\)\)$/, hint: "circle" },
75
+ { re: /^([a-zA-Z0-9_-]+)\{\{(.+?)\}\}$/, hint: "decision" },
76
+ { re: /^([a-zA-Z0-9_-]+)\{(.+?)\}$/, hint: "decision" },
77
+ { re: /^([a-zA-Z0-9_-]+)\[(.+?)\]$/, hint: "default" },
78
+ { re: /^([a-zA-Z0-9_-]+)\((.+?)\)$/, hint: "default" },
79
+ ];
80
+ for (const { re, hint } of patterns) {
81
+ const m = re.exec(trimmed);
82
+ if (m) {
83
+ const id = sanitizeId(m[1]);
84
+ let rawLabel = m[2].trim().replace(/^["']|["']$/g, "");
85
+ // Split `<br/>` or `\n` into label + sublabel
86
+ const parts = rawLabel.split(/<br\s*\/?>|\\n/i).map((p) => p.trim()).filter(Boolean);
87
+ const label = parts[0] || id;
88
+ const sublabel = parts.length > 1 ? parts.slice(1).join(" · ") : undefined;
89
+ return { id, label, sublabel, shapeHint: hint };
90
+ }
91
+ }
92
+ return { id: sanitizeId(trimmed), shapeHint: "default" };
93
+ }
94
+ function escapeQuote(s) {
95
+ return s.replace(/"/g, '\\"');
96
+ }
97
+ /**
98
+ * Detect whether a text string looks like a Mermaid flowchart/graph definition.
99
+ */
100
+ export function isMermaidSource(source) {
101
+ return /^\s*(?:flowchart|graph)\s+(?:LR|RL|TD|TB|BT)\b/im.test(source);
102
+ }
103
+ /**
104
+ * Convert a Mermaid `flowchart` / `graph` diagram into clean, animated `wirepulse` `.wp` DSL
105
+ * with automatic semantic icon & color inference.
106
+ */
107
+ export function convertMermaidToWirepulse(mermaidSource, options = {}) {
108
+ const lines = mermaidSource.split(/\r?\n/);
109
+ let direction = "LR";
110
+ const groups = [];
111
+ const groupStack = [];
112
+ const nodes = new Map();
113
+ const edges = [];
114
+ const ensureNode = (rawToken, activeGroup) => {
115
+ const parsed = parseNodeToken(rawToken);
116
+ const existing = nodes.get(parsed.id);
117
+ if (existing) {
118
+ if (parsed.label && existing.label === existing.id) {
119
+ existing.label = parsed.label;
120
+ existing.sublabel = parsed.sublabel;
121
+ const style = inferStyleFromLabel(parsed.label, parsed.shapeHint);
122
+ existing.icon = style.icon;
123
+ existing.color = style.color;
124
+ existing.pulse = style.pulse;
125
+ }
126
+ if (activeGroup && !existing.group) {
127
+ existing.group = activeGroup;
128
+ }
129
+ return existing;
130
+ }
131
+ const label = parsed.label || parsed.id;
132
+ const style = inferStyleFromLabel(label, parsed.shapeHint);
133
+ const node = {
134
+ id: parsed.id,
135
+ label,
136
+ sublabel: parsed.sublabel,
137
+ icon: style.icon,
138
+ color: style.color,
139
+ pulse: style.pulse,
140
+ group: activeGroup,
141
+ };
142
+ nodes.set(parsed.id, node);
143
+ return node;
144
+ };
145
+ for (const rawLine of lines) {
146
+ const line = rawLine.replace(/%%.*$/, "").trim();
147
+ if (!line)
148
+ continue;
149
+ // Skip Mermaid styling / classDef directives
150
+ if (/^(?:classDef|class|style|linkStyle|click)\s+/i.test(line))
151
+ continue;
152
+ // Header: flowchart LR / graph TD
153
+ const dirMatch = /^(?:flowchart|graph)\s+(LR|RL|TD|TB|BT)\b/i.exec(line);
154
+ if (dirMatch) {
155
+ const dir = dirMatch[1].toUpperCase();
156
+ direction = dir === "TD" || dir === "TB" || dir === "BT" ? "TB" : "LR";
157
+ continue;
158
+ }
159
+ // Subgraph start
160
+ const subMatch = /^subgraph\s+([^\[\n]+?)(?:\s*\[(.+?)\])?$/i.exec(line);
161
+ if (subMatch) {
162
+ const rawHead = subMatch[1].trim().replace(/^["']|["']$/g, "");
163
+ const bracketLabel = subMatch[2]?.trim().replace(/^["']|["']$/g, "");
164
+ const id = sanitizeId(rawHead.split(/\s+/)[0]);
165
+ const label = bracketLabel || rawHead;
166
+ const color = GROUP_COLORS[groups.length % GROUP_COLORS.length];
167
+ groups.push({ id, label, color });
168
+ groupStack.push(id);
169
+ continue;
170
+ }
171
+ if (/^end$/i.test(line)) {
172
+ groupStack.pop();
173
+ continue;
174
+ }
175
+ const activeGroup = groupStack[groupStack.length - 1];
176
+ // Edge formats:
177
+ // 1) A -->|label| B or A -.->|label| B or A ==>|label| B or A <-->|label| B
178
+ // 2) A -- label --> B or A -. label .-> B or A == label ==> B
179
+ // 3) A --> B or A -.-> B or A ==> B or A <--> B
180
+ let matchedEdge = false;
181
+ const pipeEdgeRe = /^(.+?)\s+(<-->|<==>|<-.->|-->|--->|==>|-.->|---)\s*\|([^|]+)\|\s*(.+)$/;
182
+ const inlineLabelRe = /^(.+?)\s+(?:--\s+(.+?)\s+-->|-\.\s+(.+?)\s+\.->|==\s+(.+?)\s+==>)\s*(.+)$/;
183
+ const plainEdgeRe = /^(.+?)\s+(<-->|<==>|<-.->|-->|--->|==>|-.->|---)\s+(.+)$/;
184
+ let fromRaw = "";
185
+ let toRaw = "";
186
+ let edgeLabel;
187
+ let arrow = "-->";
188
+ const mPipe = pipeEdgeRe.exec(line);
189
+ const mInline = !mPipe ? inlineLabelRe.exec(line) : null;
190
+ const mPlain = !mPipe && !mInline ? plainEdgeRe.exec(line) : null;
191
+ if (mPipe) {
192
+ fromRaw = mPipe[1];
193
+ arrow = mPipe[2];
194
+ edgeLabel = mPipe[3].trim().replace(/^["']|["']$/g, "");
195
+ toRaw = mPipe[4];
196
+ matchedEdge = true;
197
+ }
198
+ else if (mInline) {
199
+ fromRaw = mInline[1];
200
+ edgeLabel = (mInline[2] || mInline[3] || mInline[4] || "").trim().replace(/^["']|["']$/g, "");
201
+ arrow = mInline[3] ? "-.->" : mInline[4] ? "==>" : "-->";
202
+ toRaw = mInline[5];
203
+ matchedEdge = true;
204
+ }
205
+ else if (mPlain) {
206
+ fromRaw = mPlain[1];
207
+ arrow = mPlain[2];
208
+ toRaw = mPlain[3];
209
+ matchedEdge = true;
210
+ }
211
+ if (matchedEdge) {
212
+ // Support chained `A & B --> C` splits
213
+ const fromParts = fromRaw.split(/\s*&\s*/).filter(Boolean);
214
+ const toParts = toRaw.split(/\s*&\s*/).filter(Boolean);
215
+ const bidir = arrow.startsWith("<");
216
+ const flow = arrow.includes(".") ? "dash" : arrow.includes("=") ? "pulse" : arrow === "---" ? "solid" : "packet";
217
+ for (const fp of fromParts) {
218
+ const src = ensureNode(fp, activeGroup);
219
+ for (const tp of toParts) {
220
+ const dst = ensureNode(tp, activeGroup);
221
+ edges.push({
222
+ from: src.id,
223
+ to: dst.id,
224
+ label: edgeLabel,
225
+ flow,
226
+ bidir,
227
+ color: src.color,
228
+ });
229
+ }
230
+ }
231
+ continue;
232
+ }
233
+ // Standalone node declaration inside or outside subgraph
234
+ if (/^[a-zA-Z0-9_-]+(?:\[|\(|\{)/.test(line) || /^[a-zA-Z0-9_-]+$/.test(line)) {
235
+ ensureNode(line, activeGroup);
236
+ }
237
+ }
238
+ // Serialize to clean `.wp` DSL
239
+ const out = [
240
+ `title: ${options.title || "Animated Architecture (Imported from Mermaid)"}`,
241
+ `subtitle: Zero-JS animated SVG — auto-adapts to GitHub Light & Dark mode`,
242
+ `theme: auto`,
243
+ `direction: ${direction}`,
244
+ `speed: normal`,
245
+ ``,
246
+ ];
247
+ if (groups.length > 0) {
248
+ for (const g of groups) {
249
+ out.push(`group ${g.id} "${escapeQuote(g.label)}" color=${g.color}`);
250
+ }
251
+ out.push("");
252
+ }
253
+ for (const n of nodes.values()) {
254
+ const parts = [`node ${n.id} "${escapeQuote(n.label)}"`];
255
+ if (n.sublabel)
256
+ parts.push(`sub="${escapeQuote(n.sublabel)}"`);
257
+ parts.push(`icon=${n.icon}`, `color=${n.color}`);
258
+ if (n.group)
259
+ parts.push(`group=${n.group}`);
260
+ if (n.pulse)
261
+ parts.push(`pulse=true`);
262
+ out.push(parts.join(" "));
263
+ }
264
+ if (edges.length > 0) {
265
+ out.push("");
266
+ for (const e of edges) {
267
+ const arrowSym = e.bidir ? "<->" : "->";
268
+ const parts = [`${e.from} ${arrowSym} ${e.to}`];
269
+ if (e.label)
270
+ parts.push(`"${escapeQuote(e.label)}"`);
271
+ parts.push(`flow=${e.flow}`);
272
+ if (e.color)
273
+ parts.push(`color=${e.color}`);
274
+ out.push(parts.join(" "));
275
+ }
276
+ }
277
+ return out.join("\n") + "\n";
278
+ }
@@ -0,0 +1,10 @@
1
+ import type { ParseResult } from "./types.js";
2
+ /**
3
+ * Parse a wirepulse `.wp` DSL string (or JSON string) into a typed DiagramSpec.
4
+ */
5
+ export declare function parseDiagram(source: string): ParseResult;
6
+ /**
7
+ * Update (or insert) `col=X row=Y` on a `node <id>` line in `.wp` source text.
8
+ * Used by the Visual Studio when the user drags nodes onto a new grid cell.
9
+ */
10
+ export declare function updateNodeGridInSource(source: string, nodeId: string, col: number, row: number): string;