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.
package/dist/parser.js ADDED
@@ -0,0 +1,401 @@
1
+ import { ACCENT_NAMES, THEME_NAMES } from "./themes.js";
2
+ const VALID_ACCENTS = new Set(ACCENT_NAMES);
3
+ const VALID_THEMES = new Set(THEME_NAMES);
4
+ const VALID_FLOWS = new Set(["packet", "dash", "pulse", "solid"]);
5
+ const VALID_SPEEDS = new Set(["slow", "normal", "fast"]);
6
+ const VALID_CURVES = new Set(["smooth", "ortho", "straight"]);
7
+ function parseAccent(val, fallback = "cyan") {
8
+ if (!val)
9
+ return fallback;
10
+ const lower = val.toLowerCase();
11
+ return VALID_ACCENTS.has(lower) ? lower : fallback;
12
+ }
13
+ function parseTheme(val) {
14
+ if (!val)
15
+ return "auto";
16
+ const lower = val.toLowerCase();
17
+ return VALID_THEMES.has(lower) ? lower : "auto";
18
+ }
19
+ function parseFlow(val) {
20
+ if (!val)
21
+ return "packet";
22
+ const lower = val.toLowerCase();
23
+ return VALID_FLOWS.has(lower) ? lower : "packet";
24
+ }
25
+ function parseSpeed(val) {
26
+ if (!val)
27
+ return undefined;
28
+ const lower = val.toLowerCase();
29
+ return VALID_SPEEDS.has(lower) ? lower : undefined;
30
+ }
31
+ function parseCurve(val) {
32
+ if (!val)
33
+ return undefined;
34
+ const lower = val.toLowerCase();
35
+ return VALID_CURVES.has(lower) ? lower : undefined;
36
+ }
37
+ function parseBool(val) {
38
+ if (!val)
39
+ return false;
40
+ const lower = val.toLowerCase();
41
+ return lower === "true" || lower === "1" || lower === "yes";
42
+ }
43
+ /**
44
+ * Tokenize a single DSL line preserving quoted strings and key="quoted value" pairs.
45
+ */
46
+ function tokenizeLine(line) {
47
+ const tokens = [];
48
+ let current = "";
49
+ let quote = null;
50
+ for (let i = 0; i < line.length; i++) {
51
+ const ch = line[i];
52
+ if (quote) {
53
+ if (ch === "\\" && i + 1 < line.length) {
54
+ current += line[i + 1];
55
+ i++;
56
+ }
57
+ else if (ch === quote) {
58
+ quote = null;
59
+ }
60
+ else {
61
+ current += ch;
62
+ }
63
+ continue;
64
+ }
65
+ if (ch === "#") {
66
+ break;
67
+ }
68
+ if (ch === '"' || ch === "'") {
69
+ quote = ch;
70
+ continue;
71
+ }
72
+ if (/\s/.test(ch)) {
73
+ if (current.length > 0) {
74
+ tokens.push(current);
75
+ current = "";
76
+ }
77
+ continue;
78
+ }
79
+ current += ch;
80
+ }
81
+ if (current.length > 0) {
82
+ tokens.push(current);
83
+ }
84
+ return tokens;
85
+ }
86
+ function splitKeyValues(tokens) {
87
+ const positionals = [];
88
+ const attrs = {};
89
+ for (const tok of tokens) {
90
+ const eqIdx = tok.indexOf("=");
91
+ if (eqIdx > 0 && /^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(tok.slice(0, eqIdx))) {
92
+ const k = tok.slice(0, eqIdx).toLowerCase();
93
+ const v = tok.slice(eqIdx + 1);
94
+ attrs[k] = v;
95
+ }
96
+ else {
97
+ positionals.push(tok);
98
+ }
99
+ }
100
+ return { positionals, attrs };
101
+ }
102
+ function parseJsonDiagram(raw) {
103
+ const errors = [];
104
+ const spec = {
105
+ theme: "auto",
106
+ direction: "LR",
107
+ speed: "normal",
108
+ groups: [],
109
+ nodes: [],
110
+ edges: [],
111
+ };
112
+ try {
113
+ const obj = JSON.parse(raw);
114
+ if (typeof obj.title === "string")
115
+ spec.title = obj.title;
116
+ if (typeof obj.subtitle === "string")
117
+ spec.subtitle = obj.subtitle;
118
+ if (typeof obj.theme === "string")
119
+ spec.theme = parseTheme(obj.theme);
120
+ if (obj.direction === "TB" || obj.direction === "LR") {
121
+ spec.direction = obj.direction;
122
+ }
123
+ if (typeof obj.speed === "string") {
124
+ spec.speed = parseSpeed(obj.speed) ?? "normal";
125
+ }
126
+ if (Array.isArray(obj.groups)) {
127
+ for (const g of obj.groups) {
128
+ if (typeof g?.id === "string") {
129
+ spec.groups.push({
130
+ id: g.id,
131
+ label: typeof g.label === "string" ? g.label : g.id,
132
+ color: parseAccent(typeof g.color === "string" ? g.color : undefined, "slate"),
133
+ });
134
+ }
135
+ }
136
+ }
137
+ if (Array.isArray(obj.nodes)) {
138
+ for (const n of obj.nodes) {
139
+ if (typeof n?.id === "string") {
140
+ spec.nodes.push({
141
+ id: n.id,
142
+ label: typeof n.label === "string" ? n.label : n.id,
143
+ sublabel: typeof n.sublabel === "string" ? n.sublabel : typeof n.sub === "string" ? n.sub : undefined,
144
+ icon: typeof n.icon === "string" ? n.icon : "box",
145
+ color: parseAccent(typeof n.color === "string" ? n.color : undefined, "cyan"),
146
+ badge: typeof n.badge === "string" ? n.badge : undefined,
147
+ group: typeof n.group === "string" ? n.group : undefined,
148
+ pulse: Boolean(n.pulse),
149
+ col: typeof n.col === "number" ? n.col : undefined,
150
+ row: typeof n.row === "number" ? n.row : undefined,
151
+ x: typeof n.x === "number" ? n.x : undefined,
152
+ y: typeof n.y === "number" ? n.y : undefined,
153
+ });
154
+ }
155
+ }
156
+ }
157
+ if (Array.isArray(obj.edges)) {
158
+ let idx = 0;
159
+ for (const e of obj.edges) {
160
+ if (typeof e?.from === "string" && typeof e?.to === "string") {
161
+ spec.edges.push({
162
+ id: typeof e.id === "string" ? e.id : `edge-${idx++}`,
163
+ from: e.from,
164
+ to: e.to,
165
+ label: typeof e.label === "string" ? e.label : undefined,
166
+ flow: parseFlow(typeof e.flow === "string" ? e.flow : undefined),
167
+ speed: parseSpeed(typeof e.speed === "string" ? e.speed : undefined),
168
+ color: typeof e.color === "string" ? parseAccent(e.color) : undefined,
169
+ bidir: Boolean(e.bidir),
170
+ packets: typeof e.packets === "number" ? Math.max(1, Math.min(4, Math.round(e.packets))) : undefined,
171
+ curve: parseCurve(typeof e.curve === "string" ? e.curve : undefined),
172
+ });
173
+ }
174
+ }
175
+ }
176
+ }
177
+ catch (err) {
178
+ errors.push({
179
+ line: 1,
180
+ message: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,
181
+ });
182
+ }
183
+ return { spec, errors };
184
+ }
185
+ /**
186
+ * Parse a wirepulse `.wp` DSL string (or JSON string) into a typed DiagramSpec.
187
+ */
188
+ export function parseDiagram(source) {
189
+ const trimmedAll = source.trim();
190
+ if (trimmedAll.startsWith("{")) {
191
+ return parseJsonDiagram(trimmedAll);
192
+ }
193
+ const spec = {
194
+ theme: "auto",
195
+ direction: "LR",
196
+ speed: "normal",
197
+ groups: [],
198
+ nodes: [],
199
+ edges: [],
200
+ };
201
+ const errors = [];
202
+ const nodeMap = new Map();
203
+ const groupMap = new Map();
204
+ const lines = source.split(/\r?\n/);
205
+ let edgeIdx = 0;
206
+ for (let i = 0; i < lines.length; i++) {
207
+ const lineNum = i + 1;
208
+ const rawLine = lines[i].trim();
209
+ if (!rawLine || rawLine.startsWith("#") || rawLine.startsWith("//"))
210
+ continue;
211
+ // Key: value header directives (title:, subtitle:, theme:, direction:, speed:)
212
+ const headerMatch = /^(title|subtitle|theme|direction|speed)\s*:\s*(.+)$/i.exec(rawLine);
213
+ if (headerMatch) {
214
+ const key = headerMatch[1].toLowerCase();
215
+ const rawVal = headerMatch[2].trim();
216
+ const val = (rawVal.startsWith('"') && rawVal.endsWith('"')) ||
217
+ (rawVal.startsWith("'") && rawVal.endsWith("'"))
218
+ ? rawVal.slice(1, -1)
219
+ : rawVal;
220
+ if (key === "title")
221
+ spec.title = val;
222
+ else if (key === "subtitle")
223
+ spec.subtitle = val;
224
+ else if (key === "theme") {
225
+ if (!VALID_THEMES.has(val.toLowerCase())) {
226
+ errors.push({ line: lineNum, message: `Unknown theme "${val}". Valid: ${THEME_NAMES.join(", ")}` });
227
+ }
228
+ spec.theme = parseTheme(val);
229
+ }
230
+ else if (key === "direction") {
231
+ const up = val.toUpperCase();
232
+ if (up !== "LR" && up !== "TB") {
233
+ errors.push({ line: lineNum, message: `Unknown direction "${val}". Use LR or TB.` });
234
+ }
235
+ else {
236
+ spec.direction = up;
237
+ }
238
+ }
239
+ else if (key === "speed") {
240
+ const spd = parseSpeed(val);
241
+ if (!spd) {
242
+ errors.push({ line: lineNum, message: `Unknown speed "${val}". Use slow, normal, or fast.` });
243
+ }
244
+ else {
245
+ spec.speed = spd;
246
+ }
247
+ }
248
+ continue;
249
+ }
250
+ const tokens = tokenizeLine(rawLine);
251
+ if (tokens.length === 0)
252
+ continue;
253
+ const head = tokens[0].toLowerCase();
254
+ // Group declaration: group <id> ["Label"] [color=cyan]
255
+ if (head === "group") {
256
+ const { positionals, attrs } = splitKeyValues(tokens.slice(1));
257
+ const id = positionals[0];
258
+ if (!id) {
259
+ errors.push({ line: lineNum, message: "Group declaration requires an id: group <id> \"Label\"" });
260
+ continue;
261
+ }
262
+ const label = positionals[1] || attrs.label || id;
263
+ const group = {
264
+ id,
265
+ label,
266
+ color: parseAccent(attrs.color, "slate"),
267
+ };
268
+ if (!groupMap.has(id)) {
269
+ spec.groups.push(group);
270
+ groupMap.set(id, group);
271
+ }
272
+ continue;
273
+ }
274
+ // Node declaration: node <id> ["Label"] [sub="..."] [icon=...] [color=...] [badge="..."] [group=...] [pulse=true] [col=0] [row=1] [at=0,1]
275
+ if (head === "node") {
276
+ const { positionals, attrs } = splitKeyValues(tokens.slice(1));
277
+ const id = positionals[0];
278
+ if (!id) {
279
+ errors.push({ line: lineNum, message: "Node declaration requires an id: node <id> \"Label\"" });
280
+ continue;
281
+ }
282
+ const label = positionals[1] || attrs.label || id;
283
+ let col = attrs.col !== undefined ? Number(attrs.col) : undefined;
284
+ let row = attrs.row !== undefined ? Number(attrs.row) : undefined;
285
+ if (attrs.at && attrs.at.includes(",")) {
286
+ const [cStr, rStr] = attrs.at.split(",");
287
+ col = Number(cStr);
288
+ row = Number(rStr);
289
+ }
290
+ const x = attrs.x !== undefined ? Number(attrs.x) : undefined;
291
+ const y = attrs.y !== undefined ? Number(attrs.y) : undefined;
292
+ if (col !== undefined && Number.isNaN(col)) {
293
+ errors.push({ line: lineNum, message: `Invalid col value for node "${id}".` });
294
+ col = undefined;
295
+ }
296
+ if (row !== undefined && Number.isNaN(row)) {
297
+ errors.push({ line: lineNum, message: `Invalid row value for node "${id}".` });
298
+ row = undefined;
299
+ }
300
+ const node = {
301
+ id,
302
+ label,
303
+ sublabel: attrs.sub || attrs.sublabel,
304
+ icon: attrs.icon || "box",
305
+ color: parseAccent(attrs.color, "cyan"),
306
+ badge: attrs.badge,
307
+ group: attrs.group,
308
+ pulse: parseBool(attrs.pulse),
309
+ col,
310
+ row,
311
+ x: x !== undefined && !Number.isNaN(x) ? x : undefined,
312
+ y: y !== undefined && !Number.isNaN(y) ? y : undefined,
313
+ };
314
+ if (nodeMap.has(id)) {
315
+ // Update existing implicitly created or duplicated node
316
+ const existing = nodeMap.get(id);
317
+ Object.assign(existing, node);
318
+ }
319
+ else {
320
+ spec.nodes.push(node);
321
+ nodeMap.set(id, node);
322
+ }
323
+ continue;
324
+ }
325
+ // Edge declaration: <from> -> <to> ["label"] [flow=packet] [speed=fast] [bidir=true] [color=...] [packets=2] [curve=smooth]
326
+ // Also supports: <from> <-> <to> (auto bidir=true) and `edge <from> -> <to>`
327
+ const edgeTokens = head === "edge" ? tokens.slice(1) : tokens;
328
+ const arrowIdx = edgeTokens.findIndex((t) => t === "->" || t === "<->" || t === "-->" || t === "<-->");
329
+ if (arrowIdx === 1 && edgeTokens.length >= 3) {
330
+ const from = edgeTokens[0];
331
+ const arrow = edgeTokens[1];
332
+ const to = edgeTokens[2];
333
+ const { positionals, attrs } = splitKeyValues(edgeTokens.slice(3));
334
+ const label = positionals[0] || attrs.label;
335
+ const bidir = arrow.startsWith("<") || parseBool(attrs.bidir);
336
+ const packetsNum = attrs.packets !== undefined ? Number(attrs.packets) : undefined;
337
+ const edge = {
338
+ id: `edge-${edgeIdx++}`,
339
+ from,
340
+ to,
341
+ label,
342
+ flow: parseFlow(attrs.flow),
343
+ speed: parseSpeed(attrs.speed),
344
+ color: attrs.color ? parseAccent(attrs.color) : undefined,
345
+ bidir,
346
+ packets: packetsNum !== undefined && !Number.isNaN(packetsNum)
347
+ ? Math.max(1, Math.min(4, Math.round(packetsNum)))
348
+ : undefined,
349
+ curve: parseCurve(attrs.curve),
350
+ };
351
+ spec.edges.push(edge);
352
+ // Auto-create implicit nodes if referenced before declaration
353
+ for (const nodeId of [from, to]) {
354
+ if (!nodeMap.has(nodeId)) {
355
+ const implicit = {
356
+ id: nodeId,
357
+ label: nodeId,
358
+ icon: "box",
359
+ color: "slate",
360
+ };
361
+ spec.nodes.push(implicit);
362
+ nodeMap.set(nodeId, implicit);
363
+ }
364
+ }
365
+ continue;
366
+ }
367
+ errors.push({
368
+ line: lineNum,
369
+ message: `Unrecognized statement: "${rawLine.slice(0, 48)}"`,
370
+ });
371
+ }
372
+ return { spec, errors };
373
+ }
374
+ /**
375
+ * Update (or insert) `col=X row=Y` on a `node <id>` line in `.wp` source text.
376
+ * Used by the Visual Studio when the user drags nodes onto a new grid cell.
377
+ */
378
+ export function updateNodeGridInSource(source, nodeId, col, row) {
379
+ const escapedId = nodeId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
380
+ const nodeRe = new RegExp(`^(\\s*node\\s+${escapedId}\\b.*)$`, "m");
381
+ const match = nodeRe.exec(source);
382
+ if (!match)
383
+ return source;
384
+ let line = match[1];
385
+ line = line.replace(/\s+at=-?\d+,-?\d+/g, "");
386
+ line = line.replace(/\s+x=-?\d+(?:\.\d+)?/g, "");
387
+ line = line.replace(/\s+y=-?\d+(?:\.\d+)?/g, "");
388
+ if (/\bcol=-?\d+/.test(line)) {
389
+ line = line.replace(/\bcol=-?\d+/, `col=${col}`);
390
+ }
391
+ else {
392
+ line += ` col=${col}`;
393
+ }
394
+ if (/\brow=-?\d+/.test(line)) {
395
+ line = line.replace(/\brow=-?\d+/, `row=${row}`);
396
+ }
397
+ else {
398
+ line += ` row=${row}`;
399
+ }
400
+ return source.replace(nodeRe, line);
401
+ }
@@ -0,0 +1,6 @@
1
+ import type { DiagramSpec, RenderOptions } from "./types.js";
2
+ /**
3
+ * Compile a DiagramSpec into a self-contained, zero-JS, GitHub-README-safe
4
+ * animated SVG string.
5
+ */
6
+ export declare function renderSvg(spec: DiagramSpec, options?: RenderOptions): string;