@miragon/wardley-dsl 0.5.2 → 0.6.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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { validateMap, CURRENT_SCHEMA_VERSION } from '@miragon/wardley-schema-model';
1
+ import { DEFAULT_MAP_TITLE, validateMap, PLOT_MIN, PLOT_MAX, drawnPlotLength, CURRENT_SCHEMA_VERSION } from '@miragon/wardley-schema-model';
2
2
  export { loadMap, parseMapJSON as mapFromJSON, serializeMap as mapToJSON } from '@miragon/wardley-schema-model';
3
3
 
4
4
  // src/parser.ts
@@ -13,64 +13,165 @@ function parseCoords(line) {
13
13
  if (Number.isNaN(a) || Number.isNaN(b)) return null;
14
14
  return { a, b };
15
15
  }
16
- function stripCoords(line) {
17
- return line.replace(COORDS_RE, " ");
18
- }
19
- function splitAtCoords(line) {
16
+ function splitAtTuple(line) {
20
17
  const m = COORDS_RE.exec(line);
21
18
  if (!m) return null;
22
19
  const a = Number(m[1]);
23
20
  const b = Number(m[2]);
24
- if (Number.isNaN(a) || Number.isNaN(b)) return null;
25
21
  return {
26
- name: line.slice(0, m.index).trim(),
27
- coords: { a, b },
28
- suffix: line.slice(m.index + m[0].length)
22
+ before: line.slice(0, m.index).trim(),
23
+ tuple: m[0],
24
+ coords: Number.isNaN(a) || Number.isNaN(b) ? null : { a, b },
25
+ after: line.slice(m.index + m[0].length)
29
26
  };
30
27
  }
28
+ function splitAtCoords(line) {
29
+ const split = splitAtTuple(line);
30
+ if (!split?.coords) return null;
31
+ return { name: split.before, coords: split.coords, suffix: split.after };
32
+ }
31
33
  var COORDS4_RE = /\[\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\]/;
32
- function parseCoords4(line) {
34
+ function splitAtCoords4(line) {
33
35
  const m = COORDS4_RE.exec(line);
34
36
  if (!m) return null;
35
37
  const vals = [m[1], m[2], m[3], m[4]].map(Number);
36
38
  if (vals.some(Number.isNaN)) return null;
37
- return { a: vals[0], b: vals[1], c: vals[2], d: vals[3] };
39
+ return {
40
+ before: line.slice(0, m.index).trim(),
41
+ coords: { a: vals[0], b: vals[1], c: vals[2], d: vals[3] },
42
+ after: line.slice(m.index + m[0].length)
43
+ };
44
+ }
45
+ var TUPLE_LIST_RE = /\[\s{0,8}(\[[^[\]]*\](?:\s{0,8},\s{0,8}\[[^[\]]*\])*)\s{0,8}\]/;
46
+ var LIST_ENTRY_RE = /\[[^[\]]*\]/g;
47
+ var WHOLE_COORDS_RE = /^\[\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\]$/;
48
+ function readTupleList(line, list) {
49
+ const tuples = [];
50
+ const unreadable = [];
51
+ for (const [entry] of list[1].matchAll(LIST_ENTRY_RE)) {
52
+ const coords = WHOLE_COORDS_RE.exec(entry);
53
+ const a = Number(coords?.[1]);
54
+ const b = Number(coords?.[2]);
55
+ if (coords && !Number.isNaN(a) && !Number.isNaN(b)) tuples.push({ a, b });
56
+ else unreadable.push(entry);
57
+ }
58
+ return {
59
+ tuples,
60
+ unreadable,
61
+ before: line.slice(0, list.index).trim(),
62
+ after: line.slice(list.index + list[0].length)
63
+ };
38
64
  }
39
- var MULTI_COORDS_RE = /\[\s{0,8}(\[[^[\]]*\](?:\s{0,8},\s{0,8}\[[^[\]]*\])+)\s{0,8}\]/;
40
65
  function parseMultiCoords(line) {
41
- const m = MULTI_COORDS_RE.exec(line);
66
+ const list = TUPLE_LIST_RE.exec(line);
67
+ return list ? readTupleList(line, list) : null;
68
+ }
69
+ var FIRST_CHILD_TUPLE_RE = /\[\s*([-\d.]+)\s*(?:,\s*([-\d.]+)\s*)?\]/;
70
+ function splitAtFirstChildTuple(line) {
71
+ const m = FIRST_CHILD_TUPLE_RE.exec(line);
42
72
  if (!m) return null;
43
- const tuples = [];
44
- const inner = /\[\s{0,8}([-\d.]+)\s{0,8},\s{0,8}([-\d.]+)\s{0,8}\]/g;
45
- let t;
46
- while (t = inner.exec(m[1])) {
47
- const a = Number(t[1]);
48
- const b = Number(t[2]);
49
- if (!Number.isNaN(a) && !Number.isNaN(b)) tuples.push({ a, b });
50
- }
51
- if (!tuples.length) return null;
52
- return { tuples, rest: line.replace(MULTI_COORDS_RE, " ") };
53
- }
54
- function splitLineComment(line) {
55
- let inQuote = false;
73
+ return {
74
+ before: line.slice(0, m.index).trim(),
75
+ values: m[2] === void 0 ? [m[1]] : [m[1], m[2]],
76
+ after: line.slice(m.index + m[0].length)
77
+ };
78
+ }
79
+ function parsePositions(line) {
80
+ const single = COORDS_RE.exec(line);
81
+ const list = TUPLE_LIST_RE.exec(line);
82
+ if (list && (!single || list.index < single.index)) return readTupleList(line, list);
83
+ if (!single) return null;
84
+ const a = Number(single[1]);
85
+ const b = Number(single[2]);
86
+ const readable = !Number.isNaN(a) && !Number.isNaN(b);
87
+ return {
88
+ tuples: readable ? [{ a, b }] : [],
89
+ unreadable: readable ? [] : [single[0]],
90
+ before: line.slice(0, single.index).trim(),
91
+ after: line.slice(single.index + single[0].length)
92
+ };
93
+ }
94
+ function flowValueEnd(line, at) {
95
+ return line[at] === "'" && line[at - 1] === "+" ? line.indexOf("'", at + 1) : -1;
96
+ }
97
+ function rewriteOutsideFlowValues(text, rewrite) {
98
+ let rewritten = "";
99
+ let partStart = 0;
100
+ for (let i = 0; i < text.length; i++) {
101
+ const valueEnd = flowValueEnd(text, i);
102
+ if (valueEnd < 0) continue;
103
+ rewritten += rewrite(text.slice(partStart, i)) + text.slice(i, valueEnd + 1);
104
+ partStart = valueEnd + 1;
105
+ i = valueEnd;
106
+ }
107
+ return rewritten + rewrite(text.slice(partStart));
108
+ }
109
+ function indexOfLineComment(line) {
56
110
  for (let i = 0; i < line.length - 1; i++) {
57
- const ch = line[i];
58
- if (ch === "'") inQuote = !inQuote;
59
- else if (!inQuote && ch === "/" && line[i + 1] === "/" && line[i - 1] !== ":") {
60
- return { code: line.slice(0, i), comment: line.slice(i) };
61
- }
111
+ const valueEnd = flowValueEnd(line, i);
112
+ if (valueEnd > 0) i = valueEnd;
113
+ else if (line[i] === "/" && line[i + 1] === "/" && line[i - 1] !== ":") return i;
62
114
  }
63
- return { code: line, comment: null };
115
+ return -1;
64
116
  }
65
- function indexOfOutsideQuotes(line, needle) {
66
- let inQuote = false;
67
- for (let i = 0; i + needle.length <= line.length; i++) {
68
- const ch = line[i];
69
- if (ch === "'") {
70
- inQuote = !inQuote;
71
- continue;
117
+ function readUrlDefinition(after) {
118
+ const open = after.indexOf("[");
119
+ const close = after.lastIndexOf("]");
120
+ const name = open > 0 ? after.slice(0, open).trim() : "";
121
+ const address = open > 0 && close > open ? after.slice(open + 1, close).trim() : "";
122
+ if (!name || !address || after.slice(close + 1).trim() !== "") return null;
123
+ return { name, address };
124
+ }
125
+ function isUrlDefinition(line) {
126
+ return keywordOf(line) === "url" && readUrlDefinition(line.trim().slice("url".length)) !== null;
127
+ }
128
+ var CommentStripper = class {
129
+ inBlockComment = false;
130
+ get insideBlockComment() {
131
+ return this.inBlockComment;
132
+ }
133
+ strip(raw) {
134
+ const comments = [];
135
+ let working = raw;
136
+ if (this.inBlockComment) {
137
+ const close = working.indexOf("*/");
138
+ if (close < 0) return { code: "", comments: [raw] };
139
+ comments.push(working.slice(0, close + 2));
140
+ working = working.slice(close + 2);
141
+ this.inBlockComment = false;
142
+ }
143
+ const code = isUrlDefinition(working) ? working : this.stripComments(working, comments);
144
+ return { code, comments };
145
+ }
146
+ /** Left to right, so a `/*` inside a `//` comment opens no block comment. */
147
+ stripComments(line, comments) {
148
+ let code = "";
149
+ let rest = line;
150
+ for (; ; ) {
151
+ const lineComment = indexOfLineComment(rest);
152
+ const open = indexOutsideFlowValues(rest, "/*");
153
+ if (lineComment >= 0 && (open < 0 || lineComment < open)) {
154
+ comments.push(rest.slice(lineComment));
155
+ return code + rest.slice(0, lineComment);
156
+ }
157
+ if (open < 0) return code + rest;
158
+ const close = rest.indexOf("*/", open + 2);
159
+ if (close < 0) {
160
+ comments.push(rest.slice(open));
161
+ this.inBlockComment = true;
162
+ return code + rest.slice(0, open);
163
+ }
164
+ comments.push(rest.slice(open, close + 2));
165
+ code += `${rest.slice(0, open)} `;
166
+ rest = rest.slice(close + 2);
72
167
  }
73
- if (!inQuote && line.startsWith(needle, i)) return i;
168
+ }
169
+ };
170
+ function indexOutsideFlowValues(line, needle) {
171
+ for (let i = 0; i + needle.length <= line.length; i++) {
172
+ const valueEnd = flowValueEnd(line, i);
173
+ if (valueEnd > 0) i = valueEnd;
174
+ else if (line.startsWith(needle, i)) return i;
74
175
  }
75
176
  return -1;
76
177
  }
@@ -95,36 +196,172 @@ function parseDecorators(line) {
95
196
  });
96
197
  return { decorators: dec, rest };
97
198
  }
98
- var COLOR_RE = /\(\s*color\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z][\w-]*)\s*\)/i;
99
- function parseColor(line) {
100
- const m = COLOR_RE.exec(line);
101
- if (!m || !m[1]) return { rest: line };
102
- return { color: m[1], rest: line.replace(COLOR_RE, " ") };
199
+ var COLOR_SOURCE = String.raw`\(\s*color\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z][\w-]*)\s*\)`;
200
+ var HEIGHT_SOURCE = String.raw`\(\s{0,8}y\s{1,8}([^\s()]+)\s{0,8}\)`;
201
+ var LABEL_OFFSET_SOURCE = String.raw`label\s*\[\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\]`;
202
+ var COLOR_TOKEN_RE = new RegExp(COLOR_SOURCE, "iy");
203
+ var HEIGHT_TOKEN_RE = new RegExp(HEIGHT_SOURCE, "y");
204
+ var LABEL_TOKEN_RE = new RegExp(LABEL_OFFSET_SOURCE, "iy");
205
+ var URL_TOKEN_RE = /url\s{0,8}\(([^()]*)\)/iy;
206
+ var GROUP_TOKEN_RE = /\(([^()]*)\)/y;
207
+ var INERTIA_TOKEN_RE = /inertia\b/iy;
208
+ var WORD_TOKEN_RE = /\(?[^\s(]*/y;
209
+ function matchAt(pattern, text, at) {
210
+ pattern.lastIndex = at;
211
+ return pattern.exec(text);
212
+ }
213
+ function groupItems(content, contentAt) {
214
+ const items = [];
215
+ let itemStart = 0;
216
+ for (const raw of content.split(",")) {
217
+ const leading = raw.length - raw.trimStart().length;
218
+ const text = raw.trim();
219
+ if (text) items.push({ at: contentAt + itemStart + leading, text });
220
+ itemStart += raw.length + 1;
221
+ }
222
+ return items;
223
+ }
224
+ function readSuffixToken(text, at) {
225
+ let m;
226
+ if (m = matchAt(COLOR_TOKEN_RE, text, at)) {
227
+ return { at, text: m[0], kind: "color", color: m[1] };
228
+ }
229
+ if (m = matchAt(HEIGHT_TOKEN_RE, text, at)) {
230
+ return { at, text: m[0], kind: "height", value: m[1] };
231
+ }
232
+ if (m = matchAt(LABEL_TOKEN_RE, text, at)) {
233
+ return { at, text: m[0], kind: "label", dx: m[1], dy: m[2] };
234
+ }
235
+ if (m = matchAt(URL_TOKEN_RE, text, at)) {
236
+ return { at, text: m[0], kind: "url", ref: m[1].trim() };
237
+ }
238
+ if (m = matchAt(GROUP_TOKEN_RE, text, at)) {
239
+ return { at, text: m[0], kind: "group", items: groupItems(m[1], at + 1) };
240
+ }
241
+ if (m = matchAt(INERTIA_TOKEN_RE, text, at)) return { at, text: m[0], kind: "inertia" };
242
+ return { at, text: matchAt(WORD_TOKEN_RE, text, at)[0], kind: "word" };
243
+ }
244
+ function scanSuffix(text) {
245
+ const tokens = [];
246
+ let at = 0;
247
+ while (at < text.length) {
248
+ if (/\s/.test(text[at])) {
249
+ at++;
250
+ continue;
251
+ }
252
+ const token = readSuffixToken(text, at);
253
+ tokens.push(token);
254
+ at += token.text.length;
255
+ }
256
+ return tokens;
257
+ }
258
+ var WHOLE_COLOR_GROUP_RE = new RegExp(`^${COLOR_SOURCE}$`, "i");
259
+ var WHOLE_HEIGHT_GROUP_RE = new RegExp(`^${HEIGHT_SOURCE}$`);
260
+ function splitTrailingGroups(text, kinds) {
261
+ const groups = [];
262
+ let end = text.trimEnd().length;
263
+ while (text[end - 1] === ")") {
264
+ const open = text.lastIndexOf("(", end - 1);
265
+ const group = text.slice(Math.max(open, 0), end);
266
+ const wanted = kinds.color && WHOLE_COLOR_GROUP_RE.test(group) || kinds.height && WHOLE_HEIGHT_GROUP_RE.test(group);
267
+ if (open < 0 || !wanted) break;
268
+ groups.push(group);
269
+ end = open;
270
+ while (end > 0 && /\s/.test(text[end - 1])) end--;
271
+ }
272
+ return { rest: text.slice(0, end), groups: groups.reverse() };
273
+ }
274
+ function splitLeadingColor(text) {
275
+ const start = text.length - text.trimStart().length;
276
+ const m = matchAt(COLOR_TOKEN_RE, text, start);
277
+ if (!m) return { rest: text };
278
+ return { color: m[1], rest: text.slice(start + m[0].length) };
103
279
  }
104
- var LABEL_OFFSET_RE = /\blabel\s*\[\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\]/i;
280
+ var MAX_UNCLAMPED_MAGNITUDE = 1e12;
281
+ function isRoundTrippableNumber(value) {
282
+ return Number.isFinite(value) && Math.abs(value) <= MAX_UNCLAMPED_MAGNITUDE;
283
+ }
284
+ function readUnclampedNumber(text) {
285
+ const value = Number(text);
286
+ return isRoundTrippableNumber(value) ? value : null;
287
+ }
288
+ var LABEL_OFFSET_RE = new RegExp(String.raw`\b${LABEL_OFFSET_SOURCE}`, "i");
105
289
  function parseLabelOffset(line) {
106
290
  const m = LABEL_OFFSET_RE.exec(line);
107
291
  if (!m) return { labelOffset: null, rest: line };
108
- const dx = Number(m[1]);
109
- const dy = Number(m[2]);
292
+ const dx = readUnclampedNumber(m[1]);
293
+ const dy = readUnclampedNumber(m[2]);
110
294
  const rest = line.replace(LABEL_OFFSET_RE, " ");
111
- if (Number.isNaN(dx) || Number.isNaN(dy)) return { labelOffset: null, rest };
295
+ if (dx === null || dy === null) return { labelOffset: null, rest, unreadable: m[0] };
112
296
  return { labelOffset: { dx, dy }, rest };
113
297
  }
114
- var URL_REF_RE = /\burl\s{0,8}\(([^()]*)\)/i;
115
- function parseUrlRef(line) {
116
- const m = URL_REF_RE.exec(line);
117
- if (!m) return { urlRef: null, rest: line };
118
- return { urlRef: m[1].trim() || null, rest: line.replace(URL_REF_RE, " ") };
119
- }
298
+ var KEYWORD_RE = /^\s*([A-Za-z][\w-]*)(?![\w\p{L}\p{M}\p{N}-])/u;
120
299
  function keywordOf(line) {
121
- const m = /^\s*([A-Za-z][\w-]*)/.exec(line);
300
+ const m = KEYWORD_RE.exec(line);
122
301
  return m ? m[1].toLowerCase() : "";
123
302
  }
124
303
  function slug(label) {
125
304
  return label.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_/, "").replace(/_$/, "") || "x";
126
305
  }
127
306
 
307
+ // src/names.ts
308
+ var NAMED_TYPES = /* @__PURE__ */ new Set([
309
+ "anchor",
310
+ "component",
311
+ "accelerator",
312
+ "submap"
313
+ ]);
314
+ function defaultName(type) {
315
+ switch (type) {
316
+ case "anchor":
317
+ return "User";
318
+ case "accelerator":
319
+ return "Accelerator";
320
+ case "submap":
321
+ return "Submap";
322
+ case "pipeline":
323
+ return "Pipeline";
324
+ default:
325
+ return "Component";
326
+ }
327
+ }
328
+ function roundAsWritten(n) {
329
+ return Math.round(n * 1e3) / 1e3;
330
+ }
331
+ var DIVISION_SLASH = "\u2215";
332
+ var FULLWIDTH_PLUS = "\uFF0B";
333
+ var FULLWIDTH_LEFT_BRACE = "\uFF5B";
334
+ function escapeCommentMarkers(text) {
335
+ return rewriteOutsideFlowValues(
336
+ text,
337
+ (part) => part.replace(/\/\*/g, `${DIVISION_SLASH}*`).replace(/(?<!:)\/\//g, DIVISION_SLASH.repeat(2))
338
+ );
339
+ }
340
+ function writtenText(text) {
341
+ return escapeCommentMarkers(text.replace(/\r?\n/g, " "));
342
+ }
343
+ function writtenNoteText(text) {
344
+ return escapeCommentMarkers(text).replace(/\r?\n/g, "\\n");
345
+ }
346
+ function writtenName(label, elementType) {
347
+ const name = label.replace(/\r?\n/g, " ").replace(/->/g, "\u2192").replace(/\+(?=['<>])/g, FULLWIDTH_PLUS).trim().replace(/^\{/, FULLWIDTH_LEFT_BRACE);
348
+ return escapeCommentMarkers(name) || defaultName(elementType);
349
+ }
350
+ var UniqueNames = class {
351
+ used = /* @__PURE__ */ new Set();
352
+ claim(base) {
353
+ let name = base;
354
+ let suffix = 2;
355
+ while (this.used.has(name)) name = `${base} ${suffix++}`;
356
+ this.used.add(name);
357
+ return name;
358
+ }
359
+ /** Takes a name as it is, even when it is already taken (a name the source text already uses). */
360
+ reserve(name) {
361
+ this.used.add(name);
362
+ }
363
+ };
364
+
128
365
  // src/parser.ts
129
366
  function splitDependency(core) {
130
367
  const arrow = core.indexOf("->");
@@ -152,7 +389,7 @@ function splitFlow(core) {
152
389
  }
153
390
  return null;
154
391
  }
155
- var NON_LINK_KEYWORDS = /* @__PURE__ */ new Set([
392
+ var LINK_LIKE_STATEMENT_KEYWORDS = /* @__PURE__ */ new Set([
156
393
  "title",
157
394
  "style",
158
395
  "size",
@@ -163,12 +400,111 @@ var NON_LINK_KEYWORDS = /* @__PURE__ */ new Set([
163
400
  "evolve",
164
401
  "line"
165
402
  ]);
403
+ var DECLARATION_KEYWORDS = /* @__PURE__ */ new Set([
404
+ "anchor",
405
+ "component",
406
+ "market",
407
+ "ecosystem",
408
+ "note",
409
+ "pioneers",
410
+ "settlers",
411
+ "townplanners",
412
+ "url",
413
+ "build",
414
+ "buy",
415
+ "outsource",
416
+ "accelerator",
417
+ "deaccelerator",
418
+ "submap"
419
+ ]);
166
420
  var KNOWN_STYLES = /* @__PURE__ */ new Set(["wardley", "handwritten", "colour", "dark"]);
167
421
  function compact(obj) {
168
422
  const out = {};
169
423
  for (const [k, v] of Object.entries(obj)) if (v !== void 0) out[k] = v;
170
424
  return out;
171
425
  }
426
+ function linkCore(line) {
427
+ const semi = line.indexOf(";");
428
+ return semi >= 0 ? line.slice(0, semi) : line;
429
+ }
430
+ function readLink(line, lineNo, text) {
431
+ const semi = line.indexOf(";");
432
+ const core = (semi >= 0 ? line.slice(0, semi) : line).trim();
433
+ const label = semi >= 0 ? line.slice(semi + 1).trim() : "";
434
+ const common = { ...label ? { label } : {}, raw: line, lineNo, text };
435
+ const dependency = splitDependency(core);
436
+ if (dependency) return { ...dependency, kind: "dependency", ...common };
437
+ const flow = splitFlow(core);
438
+ if (!flow) return null;
439
+ return {
440
+ left: flow.left,
441
+ right: flow.right,
442
+ kind: "flow",
443
+ bidirectional: flow.op === "<>",
444
+ reverse: flow.op === "<",
445
+ ...flow.value ? { flowValue: flow.value } : {},
446
+ ...common
447
+ };
448
+ }
449
+ function couldBeStatement(line, keyword, after) {
450
+ return LINK_LIKE_STATEMENT_KEYWORDS.has(keyword) || DECLARATION_KEYWORDS.has(keyword) && parseCoords(line) !== null || keyword === "url" && readUrlDefinition(after) !== null;
451
+ }
452
+ function namesAsWritten(link) {
453
+ const keyword = keywordOf(link.left);
454
+ const nameAfterKeyword = link.left.slice(keyword.length).trim();
455
+ return {
456
+ left: [keyword, nameAfterKeyword].filter(Boolean).join(" "),
457
+ right: link.right.split("->").map((part) => part.trim()).join("->")
458
+ };
459
+ }
460
+ function leftNameIsDeclared(link, names) {
461
+ return names.has(link.left) || names.has(namesAsWritten(link).left);
462
+ }
463
+ function unknownStatementMessage(line) {
464
+ const core = linkCore(line);
465
+ if (/->|\+('[^']*')?(<>|>|<)/.test(core)) return "Link needs a name on both sides";
466
+ const flowValue = /\+'[^']*'/.exec(core);
467
+ if (flowValue) return `Flow ${flowValue[0]} has no direction \u2014 add ">", "<" or "<>"`;
468
+ return `Unknown statement "${line.split(/\s/)[0]}"`;
469
+ }
470
+ function buildEdges(links, idOfName, unresolved, labelOf, built) {
471
+ let dependencies = 0;
472
+ let flows = 0;
473
+ const edges = [];
474
+ for (const link of links) {
475
+ const fromId = idOfName(link.left) ?? idOfName(link.writtenNames?.left ?? link.left);
476
+ const toId = idOfName(link.right) ?? idOfName(link.writtenNames?.right ?? link.right);
477
+ if (!fromId || !toId) {
478
+ unresolved(link, fromId ? link.right : link.left);
479
+ continue;
480
+ }
481
+ if (link.kind === "dependency") {
482
+ const edge2 = compact({
483
+ id: `dep_${++dependencies}`,
484
+ edgeType: "dependency",
485
+ from: fromId,
486
+ to: toId,
487
+ label: labelOf(link)
488
+ });
489
+ edges.push(edge2);
490
+ built(edge2, link);
491
+ continue;
492
+ }
493
+ const [from, to] = link.reverse ? [toId, fromId] : [fromId, toId];
494
+ const edge = compact({
495
+ id: `flow_${++flows}`,
496
+ edgeType: "flow",
497
+ from,
498
+ to,
499
+ bidirectional: link.bidirectional ? true : void 0,
500
+ flowValue: link.flowValue,
501
+ label: labelOf(link)
502
+ });
503
+ edges.push(edge);
504
+ built(edge, link);
505
+ }
506
+ return edges;
507
+ }
172
508
  var IdAllocator = class {
173
509
  used = /* @__PURE__ */ new Set();
174
510
  alloc(prefix, label) {
@@ -184,612 +520,1122 @@ function parseDSL(text) {
184
520
  return parseDSLWithDiagnostics(text).map;
185
521
  }
186
522
  function parseDSLWithDiagnostics(text) {
187
- const diagnostics = [];
188
- const ids = new IdAllocator();
189
- const nameToId = /* @__PURE__ */ new Map();
190
- const elements = [];
191
- const rawPassthrough = [];
192
- const pendingLinks = [];
193
- const pendingEvolve = [];
194
- const pendingPipeline = [];
195
- const pendingMethod = [];
196
- let config = { title: "Untitled Map" };
197
- let annoCounter = 0;
198
- let inBlockComment = false;
199
- const urlDefs = /* @__PURE__ */ new Map();
200
- const pendingUrlRefs = [];
201
- let lastPipeline = null;
202
- let blockPipeline = null;
203
- const register = (name, id) => {
204
- if (!nameToId.has(name)) nameToId.set(name, id);
205
- };
206
- let lineNo = 0;
207
- let currentLine = "";
208
- const pushLink = (line) => {
209
- const semi = line.indexOf(";");
210
- const core = semi >= 0 ? line.slice(0, semi).trim() : line;
211
- const linkLabel = semi >= 0 ? line.slice(semi + 1).trim() : "";
212
- const dep = splitDependency(core);
213
- const flow = dep ? null : splitFlow(core);
214
- if (dep) {
215
- pendingLinks.push({
216
- left: dep.left,
217
- right: dep.right,
218
- kind: "dependency",
219
- ...linkLabel ? { label: linkLabel } : {},
220
- raw: line,
221
- lineNo
222
- });
523
+ return readMap(text).result;
524
+ }
525
+ function parseDSLWithSourceMap(text) {
526
+ const reading = readMap(text);
527
+ return { ...reading.result, sourceMap: reading.sourceMap };
528
+ }
529
+ function readMap(text) {
530
+ const reading = new MapReader(/* @__PURE__ */ new Set()).read(text);
531
+ const needsDeclaredNames = reading.keywordLinks.some(
532
+ (link) => leftNameIsDeclared(link, reading.declaredNames)
533
+ );
534
+ return needsDeclaredNames ? new MapReader(reading.declaredNames).read(text) : reading;
535
+ }
536
+ var MapReader = class {
537
+ constructor(linkNames) {
538
+ this.linkNames = linkNames;
539
+ }
540
+ linkNames;
541
+ diagnostics = [];
542
+ ids = new IdAllocator();
543
+ namesInUse = new UniqueNames();
544
+ /** The first element declared under a name wins it. */
545
+ idBySourceName = /* @__PURE__ */ new Map();
546
+ idByElementName = /* @__PURE__ */ new Map();
547
+ elements = [];
548
+ passthrough = [];
549
+ pendingLinks = [];
550
+ keywordLinks = [];
551
+ pendingEvolve = [];
552
+ pendingPipeline = [];
553
+ pendingMethod = [];
554
+ config = { title: DEFAULT_MAP_TITLE };
555
+ lineThatSetConfig = /* @__PURE__ */ new Map();
556
+ unusedConfigLines = [];
557
+ annotationCounter = 0;
558
+ comments = new CommentStripper();
559
+ urlDefinitions = [];
560
+ pendingUrlRefs = [];
561
+ /** Candidate for a `{` block opening: a block binds only to the directly preceding pipeline line. */
562
+ lastPipeline = null;
563
+ blockPipeline = null;
564
+ blockOpening = { line: 0, text: "" };
565
+ lineNo = 0;
566
+ currentLine = "";
567
+ declarationLineById = /* @__PURE__ */ new Map();
568
+ configLinesByKeyword = /* @__PURE__ */ new Map();
569
+ evolveLinesById = /* @__PURE__ */ new Map();
570
+ methodLinesById = /* @__PURE__ */ new Map();
571
+ blockLines = /* @__PURE__ */ new Map();
572
+ pipelineIds = /* @__PURE__ */ new Map();
573
+ rangeFromChildren = /* @__PURE__ */ new Set();
574
+ addElement(element, line = this.lineNo) {
575
+ this.elements.push(element);
576
+ this.declarationLineById.set(element.id, line);
577
+ }
578
+ recordBlockLine(pipeline, end) {
579
+ const lines = this.blockLines.get(pipeline) ?? {};
580
+ lines[end] = this.lineNo;
581
+ this.blockLines.set(pipeline, lines);
582
+ }
583
+ report = (message) => this.diag(message);
584
+ reportAt = (message, line, text) => this.diag(message, line, text);
585
+ diag(message, atLine = this.lineNo, text = this.currentLine) {
586
+ this.diagnostics.push({ line: atLine, message, text });
587
+ }
588
+ keepLine(statement, lineNo = this.lineNo, source = this.currentLine) {
589
+ this.passthrough.push({ text: statement, isComment: false, lineNo, source });
590
+ }
591
+ keep(statement, message) {
592
+ this.keepLine(statement);
593
+ this.diag(message);
594
+ }
595
+ /** For a line that looks like a known construct but cannot be parsed. */
596
+ failed(line) {
597
+ this.keep(line, "Line could not be interpreted (kept losslessly in rawPassthrough)");
598
+ }
599
+ // A reference binds to the name as written first, so `X 2` stays bound to an explicit "X 2" even
600
+ // when a duplicate "X" was renamed to "X 2"; the serializer then writes that reference by the
601
+ // element's new name, and the next parse binds it the same way.
602
+ idOfName(name) {
603
+ return this.idBySourceName.get(name) ?? this.idByElementName.get(name);
604
+ }
605
+ register(sourceName, elementName, id) {
606
+ if (!this.idBySourceName.has(sourceName)) this.idBySourceName.set(sourceName, id);
607
+ this.idByElementName.set(elementName, id);
608
+ }
609
+ setConfig(keyword, update) {
610
+ const earlier = this.lineThatSetConfig.get(keyword);
611
+ if (earlier !== void 0) {
612
+ this.diag(`Repeated "${keyword}" \u2014 replaces the one on line ${earlier}`);
613
+ }
614
+ this.lineThatSetConfig.set(keyword, this.lineNo);
615
+ const configLines2 = this.configLinesByKeyword.get(keyword) ?? [];
616
+ configLines2.push(this.lineNo);
617
+ this.configLinesByKeyword.set(keyword, configLines2);
618
+ this.config = update;
619
+ }
620
+ keepUnusedConfigLine(keyword, statement, reason) {
621
+ this.unusedConfigLines.push({
622
+ keyword,
623
+ reason,
624
+ index: this.passthrough.length,
625
+ line: this.lineNo,
626
+ text: this.currentLine
627
+ });
628
+ this.keepLine(statement);
629
+ }
630
+ /**
631
+ * Links are read before statements, as names may begin with a keyword (`Component -> X`); a link
632
+ * has no `[a, b]` tuple before its `;`. A line that could also be its keyword's statement is a
633
+ * link only when both names are declared.
634
+ */
635
+ readsAsLink(line, kw, after) {
636
+ const link = parseCoords(linkCore(line)) ? null : readLink(line, this.lineNo, this.currentLine);
637
+ if (!link) return false;
638
+ if (!couldBeStatement(line, kw, after)) {
639
+ this.pendingLinks.push(link);
223
640
  return true;
224
641
  }
225
- if (flow) {
226
- pendingLinks.push({
227
- left: flow.left,
228
- right: flow.right,
229
- kind: "flow",
230
- bidirectional: flow.op === "<>",
231
- reverse: flow.op === "<",
232
- ...flow.value ? { flowValue: flow.value } : {},
233
- ...linkLabel ? { label: linkLabel } : {},
234
- raw: line,
235
- lineNo
236
- });
642
+ const declared = this.linkNames;
643
+ const written = namesAsWritten(link);
644
+ const leftDeclared = declared.has(link.left) || declared.has(written.left);
645
+ if (leftDeclared && (declared.has(link.right) || declared.has(written.right))) {
646
+ this.pendingLinks.push({ ...link, writtenNames: written });
237
647
  return true;
238
648
  }
649
+ this.keywordLinks.push(link);
650
+ if (leftDeclared) this.diag(`Link: "${link.right}" not found \u2014 read as a "${kw}" statement`);
239
651
  return false;
240
- };
241
- const diag = (message, atLine = lineNo, text_ = currentLine) => diagnostics.push({ line: atLine, message, text: text_ });
242
- const failed = (l) => {
243
- rawPassthrough.push(l);
244
- diag("Line could not be interpreted (kept losslessly in rawPassthrough)");
245
- };
246
- const clampDiag = (n) => {
247
- if (n < 0 || n > 1) diag(`Coordinate ${n} is outside [0,1] and was clamped`);
652
+ }
653
+ /** Clamps a normalized value to [0,1] — with a diagnostic instead of a later validation crash. */
654
+ clamp(n, report = this.report) {
655
+ if (n < 0 || n > 1) report(`Coordinate ${n} is outside [0,1] and was clamped`);
248
656
  return n < 0 ? 0 : n > 1 ? 1 : n;
249
- };
250
- const pos = (visibility, evolution) => ({
251
- visibility: clampDiag(visibility),
252
- evolution: clampDiag(evolution)
253
- });
254
- const sourceLines = text.split(/\r?\n/);
255
- for (let i = 0; i < sourceLines.length; i++) {
256
- const raw = sourceLines[i];
257
- lineNo = i + 1;
258
- currentLine = raw.trim();
259
- let working = raw;
260
- if (inBlockComment) {
261
- const close = working.indexOf("*/");
262
- if (close < 0) {
263
- rawPassthrough.push(raw);
264
- continue;
265
- }
266
- rawPassthrough.push(working.slice(0, close + 2));
267
- working = working.slice(close + 2);
268
- inBlockComment = false;
269
- }
270
- if (keywordOf(working) !== "url") {
271
- let open = indexOfOutsideQuotes(working, "/*");
272
- while (open >= 0) {
273
- const close = working.indexOf("*/", open + 2);
274
- if (close < 0) {
275
- rawPassthrough.push(working.slice(open));
276
- working = working.slice(0, open);
277
- inBlockComment = true;
278
- break;
279
- }
280
- rawPassthrough.push(working.slice(open, close + 2));
281
- working = `${working.slice(0, open)} ${working.slice(close + 2)}`;
282
- open = indexOfOutsideQuotes(working, "/*");
283
- }
284
- const { code, comment } = splitLineComment(working);
285
- if (comment !== null) rawPassthrough.push(comment);
286
- working = code;
287
- }
288
- const line = working.trim();
289
- if (!line) continue;
290
- if (blockPipeline) {
291
- if (line === "}") {
292
- blockPipeline = null;
293
- continue;
294
- }
295
- const childKw = keywordOf(line);
296
- if (childKw === "component") {
297
- const child = parseBlockChild(line.slice(childKw.length).trim());
298
- if (child) {
299
- blockPipeline.children.push(child);
300
- continue;
301
- }
302
- }
303
- rawPassthrough.push(line);
304
- continue;
657
+ }
658
+ position(visibility, evolution) {
659
+ return { visibility: this.clamp(visibility), evolution: this.clamp(evolution) };
660
+ }
661
+ reportTextBefore(before) {
662
+ if (before) this.diag(`Ignored text before the coordinates: "${before}"`);
663
+ }
664
+ /** A suffix written in front of the coordinates is part of the name or text (OWM). */
665
+ reportMisplacedSuffix(groups, where, fix) {
666
+ if (groups.length) this.diag(`"${groups.join(" ")}" ${where} \u2014 ${fix}`);
667
+ }
668
+ /**
669
+ * A text as the serializer writes it. Its comment markers are protected only by flow values
670
+ * `+'…'` within the text itself; one that other parts of the line protected is escaped now,
671
+ * not on the next parse.
672
+ */
673
+ readText(text, line = this.lineNo, source = this.currentLine) {
674
+ const written = escapeCommentMarkers(text);
675
+ if (written !== text) {
676
+ this.diag(
677
+ `"${text}" read as "${written}" \u2014 "//" or "/*" there would start a comment once saved`,
678
+ line,
679
+ source
680
+ );
305
681
  }
306
- if (line.startsWith("{")) {
307
- if (lastPipeline) {
308
- blockPipeline = lastPipeline;
309
- lastPipeline = null;
310
- continue;
682
+ return written;
683
+ }
684
+ /** Names an element the way the serializer writes it, so the next parse yields the same name. */
685
+ nameElement(sourceName, elementType, atLine = this.lineNo, atText = this.currentLine) {
686
+ const base = writtenName(sourceName, elementType);
687
+ const name = this.namesInUse.claim(base);
688
+ if (name !== base) {
689
+ this.diag(
690
+ `Duplicate name "${sourceName}" \u2014 renamed to "${name}"; links bind to the first "${sourceName}"`,
691
+ atLine,
692
+ atText
693
+ );
694
+ } else if (name !== sourceName) {
695
+ this.diag(renamedMessage(sourceName, name), atLine, atText);
696
+ }
697
+ return name;
698
+ }
699
+ openBlock() {
700
+ if (this.lastPipeline) {
701
+ this.blockPipeline = this.lastPipeline;
702
+ this.recordBlockLine(this.blockPipeline, "open");
703
+ this.blockOpening = { line: this.lineNo, text: this.currentLine };
704
+ } else this.diag('Ignored "{" \u2014 a block must directly follow a pipeline line');
705
+ this.lastPipeline = null;
706
+ }
707
+ closeBlock() {
708
+ if (this.blockPipeline) {
709
+ this.recordBlockLine(this.blockPipeline, "close");
710
+ this.blockPipeline = null;
711
+ } else this.diag('Ignored "}" \u2014 no pipeline block is open');
712
+ this.lastPipeline = null;
713
+ }
714
+ endUnclosedBlock() {
715
+ if (!this.blockPipeline) return;
716
+ this.diag(
717
+ `Pipeline block of "${this.blockPipeline.name}" is never closed \u2014 add "}"`,
718
+ this.blockOpening.line,
719
+ this.blockOpening.text
720
+ );
721
+ this.blockPipeline = null;
722
+ }
723
+ /** A `url(Name)` reference on the element just pushed. */
724
+ addUrlRef(ref) {
725
+ this.pendingUrlRefs.push({
726
+ index: this.elements.length - 1,
727
+ ref,
728
+ line: this.lineNo,
729
+ text: this.currentLine
730
+ });
731
+ }
732
+ read(text) {
733
+ const sourceLines = text.split(/\r?\n/);
734
+ if (sourceLines.length > 1 && sourceLines[sourceLines.length - 1] === "") sourceLines.pop();
735
+ let blockCommentStart = null;
736
+ for (let i = 0; i < sourceLines.length; i++) {
737
+ const raw = withoutTrailingCarriageReturns(sourceLines[i]);
738
+ this.lineNo = i + 1;
739
+ this.currentLine = raw.trim();
740
+ const stripped = this.comments.strip(raw);
741
+ if (!this.comments.insideBlockComment) blockCommentStart = null;
742
+ else blockCommentStart ??= { line: this.lineNo, text: this.currentLine };
743
+ for (const fragment of stripped.comments) {
744
+ this.passthrough.push({
745
+ text: fragment,
746
+ isComment: true,
747
+ lineNo: this.lineNo,
748
+ source: this.currentLine
749
+ });
311
750
  }
312
- rawPassthrough.push(line);
313
- continue;
751
+ this.readCode(stripped.code.trim());
752
+ }
753
+ this.endUnclosedBlock();
754
+ if (blockCommentStart) {
755
+ const { line, text: startText } = blockCommentStart;
756
+ this.diag(
757
+ 'Block comment "/*" is never closed \u2014 the rest of the file is a comment',
758
+ line,
759
+ startText
760
+ );
761
+ }
762
+ return this.finish();
763
+ }
764
+ /**
765
+ * Braces are structural tokens: `{` at the start of a line, and `}` there while a block is open
766
+ * or on its own; `}` also ends a block line. A name starting with `}` stays a name.
767
+ */
768
+ readCode(code) {
769
+ let statement = code;
770
+ for (; ; ) {
771
+ if (statement.startsWith("{")) this.openBlock();
772
+ else if (statement.startsWith("}") && (this.blockPipeline || statement === "}")) {
773
+ this.closeBlock();
774
+ } else break;
775
+ statement = statement.slice(1).trim();
314
776
  }
777
+ const closesBlock = this.blockPipeline !== null && statement.endsWith("}");
778
+ if (closesBlock) statement = statement.slice(0, -1).trim();
779
+ if (statement) this.readStatement(statement);
780
+ if (closesBlock && this.blockPipeline) {
781
+ this.recordBlockLine(this.blockPipeline, "close");
782
+ this.blockPipeline = null;
783
+ }
784
+ }
785
+ readStatement(line) {
315
786
  const kw = keywordOf(line);
316
787
  const after = line.slice(kw.length).trim();
317
- if (kw !== "pipeline") lastPipeline = null;
318
- if (!NON_LINK_KEYWORDS.has(kw) && !parseCoords(line) && pushLink(line)) {
319
- continue;
320
- }
788
+ if (this.blockPipeline && kw === "component" && this.readBlockChild(after)) return;
789
+ this.lastPipeline = null;
790
+ if (this.readsAsLink(line, kw, after)) return;
321
791
  switch (kw) {
322
792
  case "title":
323
- config = { ...config, title: after };
324
- break;
325
- case "anchor": {
326
- const node = parseNode(after);
327
- if (!node) {
328
- failed(line);
329
- break;
330
- }
331
- const id = ids.alloc("anchor", node.name);
332
- const anchor = compact({
333
- id,
334
- elementType: "anchor",
335
- label: node.name,
336
- position: pos(node.coords.a, node.coords.b),
337
- labelOffset: node.labelOffset,
338
- color: node.color
339
- });
340
- elements.push(anchor);
341
- register(node.name, id);
342
- break;
343
- }
793
+ this.setConfig("title", { ...this.config, title: this.readText(after) });
794
+ return;
795
+ case "anchor":
796
+ return this.readAnchor(line, after);
344
797
  case "component":
345
798
  case "market":
346
- case "ecosystem": {
347
- const node = parseNode(after);
348
- if (!node) {
349
- failed(line);
350
- break;
351
- }
352
- const decorators = mergeLegacy(kw, node.decorators);
353
- const id = ids.alloc("cmp", node.name);
354
- const component = compact({
355
- id,
356
- elementType: "component",
357
- label: node.name,
358
- position: pos(node.coords.a, node.coords.b),
359
- labelOffset: node.labelOffset,
360
- decorators: Object.keys(decorators).length ? decorators : void 0,
361
- color: node.color
362
- });
363
- elements.push(component);
364
- if (node.urlRef) pendingUrlRefs.push({ index: elements.length - 1, ref: node.urlRef });
365
- register(node.name, id);
366
- break;
367
- }
368
- case "note": {
369
- const { color, rest } = parseColor(after);
370
- const coords = parseCoords(rest);
371
- const textPart = stripCoords(rest).trim().replace(/\\n/g, "\n");
372
- if (!coords) {
373
- failed(line);
374
- break;
375
- }
376
- const id = ids.alloc("note", textPart || "note");
377
- const note = compact({
378
- id,
379
- elementType: "note",
380
- label: textPart,
381
- position: pos(coords.a, coords.b),
382
- color
383
- });
384
- elements.push(note);
385
- break;
386
- }
387
- case "pipeline": {
388
- let body = after;
389
- let opensBlock = false;
390
- if (body.endsWith("{")) {
391
- opensBlock = true;
392
- body = body.slice(0, -1).trim();
393
- }
394
- const col = parseColor(body);
395
- const yMatch = /\(\s{0,8}y\s{1,8}([\d.]+)\s{0,8}\)/.exec(col.rest);
396
- const bodyRest = yMatch ? col.rest.replace(yMatch[0], " ") : col.rest;
397
- const coords = parseCoords(bodyRest);
398
- const name = stripCoords(bodyRest).trim();
399
- if (!name) {
400
- failed(line);
401
- break;
402
- }
403
- const pending = {
404
- name,
405
- ...coords ? { start: coords.a, end: coords.b } : {},
406
- ...yMatch ? { visibility: clamp01(Number(yMatch[1])) } : {},
407
- ...col.color ? { color: col.color } : {},
408
- raw: line,
409
- children: []
410
- };
411
- pendingPipeline.push(pending);
412
- if (opensBlock) blockPipeline = pending;
413
- else lastPipeline = pending;
414
- break;
415
- }
416
- case "evolve": {
417
- const ev = parseEvolve(after);
418
- if (!ev) {
419
- failed(line);
420
- break;
421
- }
422
- pendingEvolve.push({ ...ev, target: clampDiag(ev.target), raw: line, lineNo });
423
- break;
424
- }
425
- case "style": {
426
- const s = after.toLowerCase();
427
- if (KNOWN_STYLES.has(s)) config = { ...config, style: s };
428
- else failed(line);
429
- break;
430
- }
431
- case "size": {
432
- const coords = parseCoords(after);
433
- if (coords) config = { ...config, size: { width: coords.a, height: coords.b } };
434
- else failed(line);
435
- break;
436
- }
437
- case "evolution": {
438
- const parts = after.split("->").map((s) => s.trim());
439
- if (parts.length === 4) {
440
- config = { ...config, evolutionLabels: [parts[0], parts[1], parts[2], parts[3]] };
441
- } else rawPassthrough.push(raw);
442
- break;
443
- }
444
- case "y-axis": {
445
- const parts = after.split("->").map((s) => s.trim()).filter(Boolean);
446
- if (parts.length) {
447
- config = {
448
- ...config,
449
- yAxisLabel: parts[0],
450
- ...parts.length >= 3 ? { yAxisEndLabels: [parts[1], parts[2]] } : {}
451
- };
452
- } else failed(line);
453
- break;
454
- }
455
- case "annotations": {
456
- const coords = parseCoords(after);
457
- if (coords) {
458
- config = {
459
- ...config,
460
- annotationsBoxPosition: pos(coords.a, coords.b)
461
- };
462
- } else rawPassthrough.push(raw);
463
- break;
464
- }
465
- case "annotation": {
466
- const numMatch = /^\s*(\d+)/.exec(after);
467
- const number = numMatch ? Number(numMatch[1]) : ++annoCounter;
468
- const colA = parseColor(after.replace(/^\s*\d+\s*/, ""));
469
- const afterNum = colA.rest;
470
- const multi = parseMultiCoords(afterNum);
471
- let positions;
472
- let text2;
473
- if (multi) {
474
- positions = multi.tuples.map((t) => pos(t.a, t.b));
475
- text2 = multi.rest.trim();
476
- } else {
477
- const coords = parseCoords(afterNum);
478
- if (!coords) {
479
- rawPassthrough.push(line);
480
- break;
481
- }
482
- positions = [pos(coords.a, coords.b)];
483
- text2 = stripCoords(afterNum).trim();
484
- }
485
- const annotation = {
486
- id: ids.alloc("anno", String(number)),
487
- elementType: "annotation",
488
- label: text2,
489
- position: positions[0],
490
- number,
491
- positions,
492
- text: text2,
493
- ...colA.color ? { color: colA.color } : {}
494
- };
495
- elements.push(annotation);
496
- break;
497
- }
498
- case "line": {
499
- const col = parseColor(after);
500
- const multi = parseMultiCoords(col.rest);
501
- if (!multi || multi.tuples.length < 2) {
502
- failed(line);
503
- break;
504
- }
505
- const flags = multi.rest.toLowerCase();
506
- const strokeStyle = flags.includes("(dashed)") ? "dashed" : flags.includes("(dotted)") ? "dotted" : void 0;
507
- const points = multi.tuples.map((t) => pos(t.a, t.b));
508
- const drawing = {
509
- id: ids.alloc("draw", "line"),
510
- elementType: "drawing",
511
- label: "",
512
- position: points[0],
513
- points,
514
- ...flags.includes("(closed)") ? { closed: true } : {},
515
- ...strokeStyle ? { strokeStyle } : {},
516
- ...col.color ? { color: col.color } : {}
517
- };
518
- elements.push(drawing);
519
- break;
520
- }
799
+ case "ecosystem":
800
+ if (!this.pushComponent(after, kw)) this.failed(line);
801
+ return;
802
+ case "note":
803
+ return this.readNote(line, after);
804
+ case "pipeline":
805
+ return this.readPipeline(line, after);
806
+ case "evolve":
807
+ return this.readEvolve(line, after);
808
+ case "style":
809
+ return this.readStyle(line, after);
810
+ case "size":
811
+ return this.readSize(line, after);
812
+ case "evolution":
813
+ return this.readEvolution(line, after);
814
+ case "y-axis":
815
+ return this.readYAxis(line, after);
816
+ case "annotations":
817
+ return this.readAnnotationsBox(line, after);
818
+ case "annotation":
819
+ return this.readAnnotation(line, after);
820
+ case "line":
821
+ return this.readDrawing(line, after);
521
822
  case "pioneers":
522
823
  case "settlers":
523
- case "townplanners": {
524
- const col = parseColor(after);
525
- const four = parseCoords4(col.rest);
526
- if (!four) {
527
- failed(line);
528
- break;
529
- }
530
- elements.push(
531
- makeAttitude(ids, kw, four.a, four.b, four.c, four.d, col.color)
532
- );
533
- break;
534
- }
535
- case "url": {
536
- const open = after.indexOf("[");
537
- const close = after.lastIndexOf("]");
538
- const name = open > 0 ? after.slice(0, open).trim() : "";
539
- const address = open > 0 && close > open ? after.slice(open + 1, close).trim() : "";
540
- if (!name || !address || after.slice(close + 1).trim() !== "") {
541
- failed(line);
542
- break;
543
- }
544
- urlDefs.set(name, address);
545
- break;
546
- }
824
+ case "townplanners":
825
+ return this.readAttitude(line, after, kw);
826
+ case "url":
827
+ return this.readUrlDefinition(line, after);
547
828
  case "build":
548
829
  case "buy":
549
- case "outsource": {
550
- const node = parseNode(after);
551
- if (node) {
552
- const id = ids.alloc("cmp", node.name);
553
- const component = compact({
554
- id,
555
- elementType: "component",
556
- label: node.name,
557
- position: pos(node.coords.a, node.coords.b),
558
- labelOffset: node.labelOffset,
559
- decorators: { ...node.decorators, method: kw },
560
- color: node.color
561
- });
562
- elements.push(component);
563
- register(node.name, id);
564
- } else if (after.trim()) {
565
- pendingMethod.push({ name: after.trim(), method: kw, raw: line, lineNo });
566
- } else {
567
- rawPassthrough.push(line);
568
- }
569
- break;
570
- }
830
+ case "outsource":
831
+ return this.readMethod(line, after, kw);
571
832
  case "accelerator":
572
- case "deaccelerator": {
573
- const node = parseNode(after);
574
- if (!node) {
575
- failed(line);
576
- break;
577
- }
578
- const id = ids.alloc("accel", node.name);
579
- const accelerator = {
580
- id,
581
- elementType: "accelerator",
582
- direction: kw === "deaccelerator" ? "deaccelerate" : "accelerate",
583
- label: node.name,
584
- position: pos(node.coords.a, node.coords.b),
585
- ...node.color ? { color: node.color } : {}
586
- };
587
- elements.push(accelerator);
588
- register(node.name, id);
589
- break;
590
- }
591
- case "submap": {
592
- const node = parseNode(after);
593
- if (!node) {
594
- failed(line);
595
- break;
596
- }
597
- const id = ids.alloc("submap", node.name);
598
- const submap = {
599
- id,
600
- elementType: "submap",
601
- label: node.name,
602
- position: pos(node.coords.a, node.coords.b),
603
- ...node.color ? { color: node.color } : {}
604
- };
605
- elements.push(submap);
606
- if (node.urlRef) pendingUrlRefs.push({ index: elements.length - 1, ref: node.urlRef });
607
- register(node.name, id);
608
- break;
609
- }
833
+ case "deaccelerator":
834
+ return this.readAccelerator(line, after, kw);
835
+ case "submap":
836
+ return this.readSubmap(line, after);
610
837
  default: {
611
- if (!pushLink(line)) rawPassthrough.push(line);
838
+ const link = readLink(line, this.lineNo, this.currentLine);
839
+ if (link) this.pendingLinks.push(link);
840
+ else this.keep(line, unknownStatementMessage(line));
612
841
  }
613
842
  }
614
843
  }
615
- for (const p of pendingPipeline) {
616
- const refId = nameToId.get(p.name);
617
- const ref = elements.find((e) => e.id === refId);
618
- const visibility = p.visibility ?? (ref ? ref.position.visibility : 0.5);
619
- const id = ids.alloc("pipeline", p.name);
620
- register(p.name, id);
621
- const childIds = [];
622
- const childElements = [];
623
- for (const c of p.children) {
624
- const cid = ids.alloc("cmp", c.name);
625
- childElements.push(
626
- compact({
627
- id: cid,
628
- elementType: "component",
629
- label: c.name,
630
- position: { visibility, evolution: clamp01(c.maturity) },
631
- labelOffset: c.labelOffset,
632
- decorators: Object.keys(c.decorators).length ? c.decorators : void 0,
633
- pipelineId: id,
634
- color: c.color
635
- })
636
- );
637
- register(c.name, cid);
638
- childIds.push(cid);
844
+ readBlockChild(after) {
845
+ const blockPipeline = this.blockPipeline;
846
+ const child = parseBlockChild(after, this.report);
847
+ if (child) {
848
+ blockPipeline.children.push({
849
+ ...child,
850
+ maturity: this.clamp(child.maturity),
851
+ lineNo: this.lineNo,
852
+ text: this.currentLine
853
+ });
854
+ return true;
639
855
  }
640
- let start = p.start ?? (p.children.length ? Math.min(...p.children.map((c) => c.maturity)) : NaN);
641
- let end = p.end ?? (p.children.length ? Math.max(...p.children.map((c) => c.maturity)) : NaN);
642
- if (Number.isNaN(start) || Number.isNaN(end)) {
643
- rawPassthrough.push(p.raw);
644
- continue;
856
+ if (splitAtCoords(after)?.name) {
857
+ this.diag(
858
+ `Component with [visibility, maturity] inside the block of pipeline "${blockPipeline.name}" is not a child \u2014 use [maturity]`
859
+ );
645
860
  }
646
- start = clamp01(start);
647
- end = clamp01(end);
648
- if (end <= start) end = Math.min(1, start + 0.05);
649
- const pipeline = {
861
+ return false;
862
+ }
863
+ readAnchor(line, after) {
864
+ const node = parseNode(after, ANCHOR_SUFFIXES, this.report);
865
+ if (!node) return this.failed(line);
866
+ const label = this.nameElement(node.name, "anchor");
867
+ const id = this.ids.alloc("anchor", label);
868
+ const anchor = compact({
650
869
  id,
651
- elementType: "pipeline",
652
- label: p.name,
653
- position: { visibility, evolution: (start + end) / 2 },
654
- evolutionStart: start,
655
- evolutionEnd: end,
656
- childIds,
657
- ...p.color ? { color: p.color } : {}
658
- };
659
- elements.push(pipeline, ...childElements);
660
- }
661
- for (const ev of pendingEvolve) {
662
- const id = nameToId.get(ev.name);
663
- const idx = elements.findIndex((e) => e.id === id);
664
- if (idx < 0 || elements[idx].elementType !== "component") {
665
- rawPassthrough.push(ev.raw);
666
- diag(`evolve: component "${ev.name}" not found`, ev.lineNo, ev.raw);
667
- continue;
668
- }
669
- const movement = compact({
670
- targetEvolution: ev.target,
671
- newLabel: ev.newLabel,
672
- method: ev.method,
673
- labelOffset: ev.labelOffset
870
+ elementType: "anchor",
871
+ label,
872
+ position: this.position(node.coords.a, node.coords.b),
873
+ labelOffset: node.labelOffset,
874
+ color: node.color
674
875
  });
675
- elements[idx] = { ...elements[idx], movement };
676
- }
677
- for (const pm of pendingMethod) {
678
- const id = nameToId.get(pm.name);
679
- const idx = elements.findIndex((e) => e.id === id);
680
- const el = idx >= 0 ? elements[idx] : void 0;
681
- if (!el || el.elementType !== "component") {
682
- rawPassthrough.push(pm.raw);
683
- diag(`${pm.method}: component "${pm.name}" not found`, pm.lineNo, pm.raw);
684
- continue;
685
- }
686
- elements[idx] = { ...el, decorators: { ...el.decorators, method: pm.method } };
876
+ this.addElement(anchor);
877
+ this.register(node.name, label, id);
687
878
  }
688
- const usedUrlDefs = /* @__PURE__ */ new Set();
689
- for (const { index, ref } of pendingUrlRefs) {
690
- const fromDef = urlDefs.get(ref);
691
- if (fromDef) usedUrlDefs.add(ref);
692
- const address = fromDef ?? (/^[a-z][\w+.-]*:\/\//i.test(ref) ? ref : void 0);
693
- if (!address) continue;
694
- const el = elements[index];
695
- if (el.elementType === "component") {
696
- elements[index] = { ...el, url: address };
697
- } else if (el.elementType === "submap") {
698
- elements[index] = { ...el, urlRef: address };
879
+ /** `component`/`market`/`ecosystem` and `build`/`buy`/`outsource` lines with coordinates. */
880
+ pushComponent(after, kw) {
881
+ const keywordMethod = METHODS.has(kw) ? kw : void 0;
882
+ const node = parseNode(after, COMPONENT_SUFFIXES, this.report, keywordMethod);
883
+ if (!node) return false;
884
+ const decorators = mergeLegacy(kw, node.decorators);
885
+ const label = this.nameElement(node.name, "component");
886
+ const id = this.ids.alloc("cmp", label);
887
+ const component = compact({
888
+ id,
889
+ elementType: "component",
890
+ label,
891
+ position: this.position(node.coords.a, node.coords.b),
892
+ labelOffset: node.labelOffset,
893
+ decorators: Object.keys(decorators).length ? decorators : void 0,
894
+ color: node.color
895
+ });
896
+ this.addElement(component);
897
+ if (node.urlRef) this.addUrlRef(node.urlRef);
898
+ this.register(node.name, label, id);
899
+ return true;
900
+ }
901
+ readNote(line, after) {
902
+ const split = splitAtCoords(after);
903
+ if (!split) return this.failed(line);
904
+ const { color } = readSuffix(split.suffix, NOTE_SUFFIXES, this.report);
905
+ this.reportMisplacedSuffix(
906
+ splitTrailingGroups(split.name, { color: true, height: false }).groups,
907
+ "before the coordinates is read as part of the text",
908
+ "write it after them"
909
+ );
910
+ const textPart = this.readText(split.name.replace(/\\n/g, "\n"));
911
+ const note = compact({
912
+ id: this.ids.alloc("note", textPart || "note"),
913
+ elementType: "note",
914
+ label: textPart,
915
+ position: this.position(split.coords.a, split.coords.b),
916
+ color
917
+ });
918
+ this.addElement(note);
919
+ }
920
+ /** `pipeline X [s, e]`, `pipeline X` (block form, range from children) — optionally with `{` at the end. */
921
+ readPipeline(line, after) {
922
+ this.endUnclosedBlock();
923
+ let body = after;
924
+ let opensBlock = false;
925
+ while (body.endsWith("{")) {
926
+ if (opensBlock) this.diag('Ignored "{" \u2014 a block must directly follow a pipeline line');
927
+ opensBlock = true;
928
+ body = body.slice(0, -1).trim();
699
929
  }
930
+ const { name, range, suffixText, misplaced } = splitPipelineLine(body);
931
+ if (!name) return this.failed(line);
932
+ if (range && !range.coords) this.diag(unreadableNumberMessage(range.tuple));
933
+ this.reportMisplacedSuffix(
934
+ misplaced,
935
+ "before the coordinates is read as part of the name",
936
+ "write it after them"
937
+ );
938
+ const notes = [];
939
+ const note = (message) => notes.push(message);
940
+ const suffix = readSuffix(suffixText, PIPELINE_SUFFIXES, note);
941
+ const coords = range?.coords;
942
+ const pending = {
943
+ name,
944
+ lineNo: this.lineNo,
945
+ text: this.currentLine,
946
+ ...coords ? { start: this.clamp(coords.a), end: this.clamp(coords.b) } : {},
947
+ ...suffix.height !== void 0 ? { visibility: roundAsWritten(this.clamp(suffix.height, note)) } : {},
948
+ ...suffix.color ? { color: suffix.color } : {},
949
+ notes,
950
+ raw: line.slice(0, line.length - after.length) + body,
951
+ children: []
952
+ };
953
+ this.pendingPipeline.push(pending);
954
+ if (opensBlock) {
955
+ this.blockPipeline = pending;
956
+ this.recordBlockLine(pending, "open");
957
+ this.blockOpening = { line: this.lineNo, text: this.currentLine };
958
+ } else this.lastPipeline = pending;
700
959
  }
701
- for (const [name, address] of urlDefs) {
702
- if (!usedUrlDefs.has(name)) rawPassthrough.push(`url ${name} [${address}]`);
960
+ readEvolve(line, after) {
961
+ const notes = [];
962
+ const note = (message) => notes.push(message);
963
+ const evolve = parseEvolve(after, note);
964
+ if (!evolve) return this.failed(line);
965
+ this.pendingEvolve.push({
966
+ ...evolve,
967
+ target: this.clamp(evolve.target, note),
968
+ notes,
969
+ raw: line,
970
+ lineNo: this.lineNo,
971
+ text: this.currentLine
972
+ });
703
973
  }
704
- let depN = 0;
705
- let flowN = 0;
706
- const edges = [];
707
- for (const link of pendingLinks) {
708
- const fromId = nameToId.get(link.left);
709
- const toId = nameToId.get(link.right);
710
- if (!fromId || !toId) {
711
- rawPassthrough.push(link.raw);
712
- diag(
713
- `Link: ${!fromId ? `"${link.left}"` : `"${link.right}"`} not found`,
714
- link.lineNo,
715
- link.raw
716
- );
717
- continue;
974
+ readStyle(line, after) {
975
+ const style = after.toLowerCase();
976
+ if (KNOWN_STYLES.has(style)) {
977
+ this.setConfig("style", { ...this.config, style });
978
+ } else this.failed(line);
979
+ }
980
+ readSize(line, after) {
981
+ const split = splitAtCoords(after);
982
+ const coords = split?.coords;
983
+ if (!coords || !isRoundTrippableNumber(coords.a) || !isRoundTrippableNumber(coords.b)) {
984
+ return this.failed(line);
718
985
  }
719
- if (link.kind === "dependency") {
720
- edges.push(
721
- compact({
722
- id: `dep_${++depN}`,
723
- edgeType: "dependency",
724
- from: fromId,
725
- to: toId,
726
- label: link.label
727
- })
986
+ this.reportTextBefore(split.name);
987
+ readSuffix(split.suffix, NO_SUFFIXES, this.report);
988
+ this.setConfig("size", { ...this.config, size: { width: coords.a, height: coords.b } });
989
+ const problem = sizeOutsideLimits(coords.a, coords.b);
990
+ if (problem) this.diag(problem);
991
+ if (!Number.isInteger(coords.a) || !Number.isInteger(coords.b)) {
992
+ this.diag(
993
+ `Map size ${coords.a}\xD7${coords.b} is not in whole pixels \u2014 OWM only reads whole-pixel sizes`
728
994
  );
995
+ }
996
+ }
997
+ readEvolution(line, after) {
998
+ const parts = after.split("->").map((s) => s.trim());
999
+ if (parts.length === 4) {
1000
+ const [first, second, third, fourth] = parts.map((part) => this.readText(part));
1001
+ const evolutionLabels = [first, second, third, fourth];
1002
+ this.setConfig("evolution", { ...this.config, evolutionLabels });
729
1003
  } else {
730
- const [f, t] = link.reverse ? [toId, fromId] : [fromId, toId];
731
- edges.push(
732
- compact({
733
- id: `flow_${++flowN}`,
734
- edgeType: "flow",
735
- from: f,
736
- to: t,
737
- bidirectional: link.bidirectional ? true : void 0,
738
- flowValue: link.flowValue,
739
- label: link.label
740
- })
1004
+ const reason = `Evolution needs exactly four stages, found ${parts.length}`;
1005
+ this.keepUnusedConfigLine("evolution", line, reason);
1006
+ }
1007
+ }
1008
+ /** `y-axis Label->BottomLabel->TopLabel` — keeps the end labels losslessly too. */
1009
+ readYAxis(line, after) {
1010
+ const written = after.split("->").map((s) => s.trim());
1011
+ const [label, bottom, top] = written.filter(Boolean).map((part) => this.readText(part));
1012
+ if (!label) return this.keepUnusedConfigLine("y-axis", line, "y-axis has no label");
1013
+ const { yAxisEndLabels: _replaced, ...otherConfig } = this.config;
1014
+ const ends = bottom && top ? [bottom, top] : void 0;
1015
+ this.setConfig("y-axis", {
1016
+ ...otherConfig,
1017
+ yAxisLabel: label,
1018
+ ...ends ? { yAxisEndLabels: ends } : {}
1019
+ });
1020
+ if (written.length !== 1 && !(written.length === 3 && written.every(Boolean))) {
1021
+ const read = [label, ...ends ?? []].join("->");
1022
+ this.diag(`y-axis takes "Label" or "Label->Bottom->Top" \u2014 read as "${read}"`);
1023
+ }
1024
+ }
1025
+ readAnnotationsBox(line, after) {
1026
+ const split = splitAtCoords(after);
1027
+ if (!split) {
1028
+ return this.keep(
1029
+ line,
1030
+ "Annotations box has no position \u2014 not used; add [visibility, maturity]"
741
1031
  );
742
1032
  }
1033
+ this.reportTextBefore(split.name);
1034
+ readSuffix(split.suffix, NO_SUFFIXES, this.report);
1035
+ const annotationsBoxPosition = this.position(split.coords.a, split.coords.b);
1036
+ this.setConfig("annotations", { ...this.config, annotationsBoxPosition });
743
1037
  }
744
- const map = compact({
745
- schemaVersion: CURRENT_SCHEMA_VERSION,
746
- config,
747
- elements,
748
- edges,
749
- rawPassthrough: rawPassthrough.length ? rawPassthrough : void 0
750
- });
751
- return { map: validateMap(map), diagnostics };
752
- }
753
- function parseNode(after) {
754
- const split = splitAtCoords(after);
755
- if (!split || !split.name) return null;
756
- const col = parseColor(split.suffix);
757
- const url = parseUrlRef(col.rest);
758
- const lo = parseLabelOffset(url.rest);
759
- const dec = parseDecorators(lo.rest);
760
- return compact({
761
- name: split.name,
762
- coords: split.coords,
763
- decorators: dec.decorators,
764
- labelOffset: lo.labelOffset ?? void 0,
765
- urlRef: url.urlRef ?? void 0,
766
- color: col.color ?? void 0
1038
+ /** `annotation N <position> [(color …)] <text>`; the position is a tuple or a tuple list. */
1039
+ readAnnotation(line, after) {
1040
+ const numMatch = /^\s*(\d+)/.exec(after);
1041
+ const number = numMatch ? Number(numMatch[1]) : ++this.annotationCounter;
1042
+ if (!Number.isSafeInteger(number)) return this.failed(line);
1043
+ const found = parsePositions(after.replace(/^\s*\d+\s*/, ""));
1044
+ if (!found) {
1045
+ return this.keep(line, "Annotation has no position \u2014 not drawn; add [visibility, maturity]");
1046
+ }
1047
+ if (!found.tuples.length) return this.failed(line);
1048
+ for (const unreadable of found.unreadable) this.diag(unreadableNumberMessage(unreadable));
1049
+ this.reportTextBefore(found.before);
1050
+ const { color, rest } = splitLeadingColor(found.after);
1051
+ this.reportMisplacedSuffix(
1052
+ splitTrailingGroups(rest, { color: true, height: false }).groups,
1053
+ "after the annotation text is read as part of the text",
1054
+ "write it directly after the position"
1055
+ );
1056
+ const text = this.readText(rest.trim());
1057
+ const positions = found.tuples.map((t) => this.position(t.a, t.b));
1058
+ const annotation = {
1059
+ id: this.ids.alloc("anno", String(number)),
1060
+ elementType: "annotation",
1061
+ label: text,
1062
+ position: positions[0],
1063
+ number,
1064
+ positions,
1065
+ text,
1066
+ ...color ? { color } : {}
1067
+ };
1068
+ this.addElement(annotation);
1069
+ }
1070
+ /** Project extension (freeform drawing): `line [[v,e], [v,e], …] (closed) (dashed) (color x)`. */
1071
+ readDrawing(line, after) {
1072
+ const list = parseMultiCoords(after);
1073
+ if (!list || list.tuples.length < 2) return this.failed(line);
1074
+ for (const unreadable of list.unreadable) this.diag(unreadableNumberMessage(unreadable));
1075
+ this.reportTextBefore(list.before);
1076
+ const suffix = readSuffix(list.after, DRAWING_SUFFIXES, this.report);
1077
+ const points = list.tuples.map((t) => this.position(t.a, t.b));
1078
+ const drawing = {
1079
+ id: this.ids.alloc("draw", "line"),
1080
+ elementType: "drawing",
1081
+ label: "",
1082
+ position: points[0],
1083
+ points,
1084
+ ...suffix.closed ? { closed: true } : {},
1085
+ ...suffix.strokeStyle ? { strokeStyle: suffix.strokeStyle } : {},
1086
+ ...suffix.color ? { color: suffix.color } : {}
1087
+ };
1088
+ this.addElement(drawing);
1089
+ }
1090
+ /** Canonical OWM form: `<kind> [vis1, mat1, vis2, mat2]` (two corners, normalized). */
1091
+ readAttitude(line, after, kind) {
1092
+ const split = splitAtCoords4(after);
1093
+ if (!split) return this.failed(line);
1094
+ this.reportTextBefore(split.before);
1095
+ const { color } = readSuffix(split.after, ATTITUDE_SUFFIXES, this.report);
1096
+ const { a, b, c, d } = split.coords;
1097
+ const corners = [this.clamp(a), this.clamp(b), this.clamp(c), this.clamp(d)];
1098
+ this.addElement(makeAttitude(this.ids, kind, corners, color));
1099
+ }
1100
+ /** OWM: `url Name [https://…]` — definition, referenced via `url(Name)` on elements. */
1101
+ readUrlDefinition(line, after) {
1102
+ const definition = readUrlDefinition(after);
1103
+ if (!definition) return this.failed(line);
1104
+ this.urlDefinitions.push({ ...definition, lineNo: this.lineNo, text: this.currentLine });
1105
+ }
1106
+ /**
1107
+ * Legacy OWM: `buy <Name>` (method on an existing component) or `buy <Name> [vis, mat]` (create a
1108
+ * component with a method).
1109
+ */
1110
+ readMethod(line, after, kw) {
1111
+ if (this.pushComponent(after, kw)) return;
1112
+ if (!after) return this.keep(line, `${kw}: needs a component name \u2014 not used`);
1113
+ this.pendingMethod.push({
1114
+ name: after,
1115
+ method: kw,
1116
+ raw: line,
1117
+ lineNo: this.lineNo,
1118
+ text: this.currentLine
1119
+ });
1120
+ }
1121
+ readAccelerator(line, after, kw) {
1122
+ const node = parseNode(after, ACCELERATOR_SUFFIXES, this.report);
1123
+ if (!node) return this.failed(line);
1124
+ const label = this.nameElement(node.name, "accelerator");
1125
+ const id = this.ids.alloc("accel", label);
1126
+ const accelerator = {
1127
+ id,
1128
+ elementType: "accelerator",
1129
+ direction: kw === "deaccelerator" ? "deaccelerate" : "accelerate",
1130
+ label,
1131
+ position: this.position(node.coords.a, node.coords.b),
1132
+ ...node.color ? { color: node.color } : {}
1133
+ };
1134
+ this.addElement(accelerator);
1135
+ this.register(node.name, label, id);
1136
+ }
1137
+ readSubmap(line, after) {
1138
+ const node = parseNode(after, SUBMAP_SUFFIXES, this.report);
1139
+ if (!node) return this.failed(line);
1140
+ const label = this.nameElement(node.name, "submap");
1141
+ const id = this.ids.alloc("submap", label);
1142
+ const submap = {
1143
+ id,
1144
+ elementType: "submap",
1145
+ label,
1146
+ position: this.position(node.coords.a, node.coords.b),
1147
+ ...node.color ? { color: node.color } : {}
1148
+ };
1149
+ this.addElement(submap);
1150
+ if (node.urlRef) this.addUrlRef(node.urlRef);
1151
+ this.register(node.name, label, id);
1152
+ }
1153
+ finish() {
1154
+ const removedFromPassthrough = replacedConfigLines(
1155
+ this.unusedConfigLines,
1156
+ this.config,
1157
+ this.reportAt
1158
+ );
1159
+ this.resolvePipelines();
1160
+ const indexById = new Map(this.elements.map((el, index) => [el.id, index]));
1161
+ this.resolveEvolves(indexById);
1162
+ this.resolveMethods(indexById);
1163
+ const urlReferences = /* @__PURE__ */ new Map();
1164
+ const usedDefinitions = /* @__PURE__ */ new Set();
1165
+ const keptDefinitions = resolveUrlReferences(
1166
+ this.elements,
1167
+ this.pendingUrlRefs,
1168
+ this.urlDefinitions,
1169
+ this.reportAt,
1170
+ (element, definition) => {
1171
+ if (definition) usedDefinitions.add(definition);
1172
+ urlReferences.set(
1173
+ element.id,
1174
+ definition ? { kind: "definition", name: definition.name } : { kind: "embedded" }
1175
+ );
1176
+ }
1177
+ );
1178
+ for (const definition of keptDefinitions) {
1179
+ this.keepLine(
1180
+ `url ${definition.name} [${definition.address}]`,
1181
+ definition.lineNo,
1182
+ definition.text
1183
+ );
1184
+ }
1185
+ const declaredNames = /* @__PURE__ */ new Set([...this.idBySourceName.keys(), ...this.idByElementName.keys()]);
1186
+ const edgeLineById = /* @__PURE__ */ new Map();
1187
+ const edges = buildEdges(
1188
+ this.pendingLinks,
1189
+ (name) => this.idOfName(name),
1190
+ (link, missing) => {
1191
+ this.keepLine(link.raw, link.lineNo, link.text);
1192
+ this.diag(`Link: "${missing}" not found`, link.lineNo, link.text);
1193
+ },
1194
+ (link) => link.label && this.readText(link.label, link.lineNo, link.text),
1195
+ (edge, link) => edgeLineById.set(edge.id, link.lineNo)
1196
+ );
1197
+ const kept = this.passthrough.filter((_, index) => !removedFromPassthrough.has(index));
1198
+ const rawPassthrough = withoutClosersOfKeptComments(kept, this.reportAt);
1199
+ const sourceMap = this.sourceMap({
1200
+ removedFromPassthrough,
1201
+ usedDefinitions,
1202
+ urlReferences,
1203
+ edgeLineById,
1204
+ kept
1205
+ });
1206
+ const map = compact({
1207
+ schemaVersion: CURRENT_SCHEMA_VERSION,
1208
+ config: this.config,
1209
+ elements: this.elements,
1210
+ edges,
1211
+ rawPassthrough: rawPassthrough.length ? rawPassthrough : void 0
1212
+ });
1213
+ return {
1214
+ result: { map: validateMap(map), diagnostics: this.diagnostics },
1215
+ sourceMap,
1216
+ declaredNames,
1217
+ keywordLinks: this.keywordLinks
1218
+ };
1219
+ }
1220
+ sourceMap(parts) {
1221
+ const primaryLineOf = /* @__PURE__ */ new Map();
1222
+ const secondaryLinesOf = /* @__PURE__ */ new Map();
1223
+ const addSecondary = (key, line) => {
1224
+ const lines = secondaryLinesOf.get(key) ?? [];
1225
+ lines.push(line);
1226
+ secondaryLinesOf.set(key, lines);
1227
+ };
1228
+ const addRepeated = (key, lines) => {
1229
+ if (!lines?.length) return;
1230
+ primaryLineOf.set(key, lines[lines.length - 1]);
1231
+ for (const line of lines.slice(0, -1)) addSecondary(key, line);
1232
+ };
1233
+ for (const [keyword, lines] of this.configLinesByKeyword) {
1234
+ addRepeated(`config:${keyword}`, lines);
1235
+ }
1236
+ for (const unused of this.unusedConfigLines) {
1237
+ if (parts.removedFromPassthrough.has(unused.index)) {
1238
+ addSecondary(`config:${unused.keyword}`, unused.line);
1239
+ }
1240
+ }
1241
+ for (const definition of parts.usedDefinitions) {
1242
+ primaryLineOf.set(`url:${definition.name}`, definition.lineNo);
1243
+ }
1244
+ for (const el of this.elements) {
1245
+ const isChild = el.elementType === "component" && el.pipelineId !== void 0;
1246
+ const key = `${isChild ? "child" : "element"}:${el.id}`;
1247
+ const line = this.declarationLineById.get(el.id);
1248
+ if (line !== void 0) primaryLineOf.set(key, line);
1249
+ for (const methodLine of this.methodLinesById.get(el.id) ?? []) addSecondary(key, methodLine);
1250
+ addRepeated(`evolve:${el.id}`, this.evolveLinesById.get(el.id));
1251
+ }
1252
+ for (const [id, line] of parts.edgeLineById) primaryLineOf.set(`edge:${id}`, line);
1253
+ const blocks = /* @__PURE__ */ new Map();
1254
+ for (const [pipeline, lines] of this.blockLines) {
1255
+ const id = this.pipelineIds.get(pipeline);
1256
+ if (id !== void 0) blocks.set(id, lines);
1257
+ }
1258
+ return {
1259
+ primaryLineOf,
1260
+ secondaryLinesOf,
1261
+ passthrough: parts.kept.map((entry) => ({ line: entry.lineNo, isComment: entry.isComment })),
1262
+ blocks,
1263
+ rangeFromChildren: this.rangeFromChildren,
1264
+ urlReferences: parts.urlReferences
1265
+ };
1266
+ }
1267
+ /**
1268
+ * A pipeline pairs with the component written under its name: it takes that component's height,
1269
+ * as the serializer assumes when it leaves out `(y …)`. Block children are not such components.
1270
+ */
1271
+ resolvePipelines() {
1272
+ const componentByName = /* @__PURE__ */ new Map();
1273
+ for (const el of this.elements) {
1274
+ if (el.elementType === "component") componentByName.set(el.label, el);
1275
+ }
1276
+ for (const p of this.pendingPipeline) {
1277
+ const label = writtenName(p.name, "pipeline");
1278
+ const component = componentByName.get(label);
1279
+ const writtenRange = pipelineRange(p);
1280
+ if (!writtenRange) {
1281
+ this.keepLine(p.raw, p.lineNo, p.text);
1282
+ if (!component) {
1283
+ this.diag(
1284
+ `Pipeline "${p.name}" has no range \u2014 not drawn; add [start, end] or child components`,
1285
+ p.lineNo,
1286
+ p.text
1287
+ );
1288
+ }
1289
+ continue;
1290
+ }
1291
+ for (const message of p.notes) this.diag(message, p.lineNo, p.text);
1292
+ if (label !== p.name) this.diag(renamedMessage(p.name, label), p.lineNo, p.text);
1293
+ const range = widenEmptyRange(writtenRange);
1294
+ const widened = range.start !== writtenRange.start || range.end !== writtenRange.end;
1295
+ if (widened && !writtenRange.fromChildren) {
1296
+ this.diag(
1297
+ `Pipeline "${p.name}" range is empty or reversed \u2014 changed to [${range.start}, ${range.end}]`,
1298
+ p.lineNo,
1299
+ p.text
1300
+ );
1301
+ }
1302
+ const visibility = p.visibility ?? component?.position.visibility ?? 0.5;
1303
+ const id = this.ids.alloc("pipeline", label);
1304
+ this.pipelineIds.set(p, id);
1305
+ if (writtenRange.fromChildren) this.rangeFromChildren.add(id);
1306
+ if (this.idOfName(p.name) === void 0 && this.idOfName(label) === void 0) {
1307
+ this.register(p.name, label, id);
1308
+ }
1309
+ const childNames = p.children.map(
1310
+ (child) => this.nameElement(child.name, "component", child.lineNo, child.text)
1311
+ );
1312
+ const { pipeline, children } = pipelineElements(
1313
+ { ...p, name: label },
1314
+ id,
1315
+ visibility,
1316
+ range,
1317
+ this.ids,
1318
+ childNames
1319
+ );
1320
+ this.addElement(pipeline, p.lineNo);
1321
+ children.forEach((child, index) => {
1322
+ this.addElement(child, p.children[index].lineNo);
1323
+ this.register(p.children[index].name, child.label, child.id);
1324
+ });
1325
+ }
1326
+ }
1327
+ componentIndex(name, indexById) {
1328
+ const index = indexById.get(this.idOfName(name) ?? "");
1329
+ return index !== void 0 && this.elements[index].elementType === "component" ? index : -1;
1330
+ }
1331
+ resolveEvolves(indexById) {
1332
+ const evolveLineOf = /* @__PURE__ */ new Map();
1333
+ for (const ev of this.pendingEvolve) {
1334
+ const index = this.componentIndex(ev.name, indexById);
1335
+ if (index < 0) {
1336
+ this.keepLine(ev.raw, ev.lineNo, ev.text);
1337
+ const misplaced = splitMisplacedEvolveSuffix(ev.name);
1338
+ const hint = misplaced && this.componentIndex(misplaced.name, indexById) >= 0 ? misplacedEvolveSuffixHint(misplaced) : "";
1339
+ this.diag(`evolve: component "${ev.name}" not found${hint}`, ev.lineNo, ev.text);
1340
+ continue;
1341
+ }
1342
+ for (const message of ev.notes) this.diag(message, ev.lineNo, ev.text);
1343
+ const component = this.elements[index];
1344
+ const earlier = evolveLineOf.get(component.id);
1345
+ if (earlier !== void 0) {
1346
+ const message = `Repeated evolve for "${ev.name}" \u2014 replaces the one on line ${earlier}`;
1347
+ this.diag(message, ev.lineNo, ev.text);
1348
+ }
1349
+ evolveLineOf.set(component.id, ev.lineNo);
1350
+ const evolveLines = this.evolveLinesById.get(component.id) ?? [];
1351
+ evolveLines.push(ev.lineNo);
1352
+ this.evolveLinesById.set(component.id, evolveLines);
1353
+ const movement = compact({
1354
+ targetEvolution: ev.target,
1355
+ newLabel: ev.newLabel && this.readText(ev.newLabel, ev.lineNo, ev.text),
1356
+ method: ev.method,
1357
+ labelOffset: ev.labelOffset
1358
+ });
1359
+ this.elements[index] = { ...component, movement };
1360
+ }
1361
+ }
1362
+ /** Legacy standalone methods (`buy <name>`). */
1363
+ resolveMethods(indexById) {
1364
+ for (const pm of this.pendingMethod) {
1365
+ const index = this.componentIndex(pm.name, indexById);
1366
+ if (index < 0) {
1367
+ this.keepLine(pm.raw, pm.lineNo, pm.text);
1368
+ this.diag(`${pm.method}: component "${pm.name}" not found`, pm.lineNo, pm.text);
1369
+ continue;
1370
+ }
1371
+ const el = this.elements[index];
1372
+ const replaced = el.decorators?.method;
1373
+ if (replaced && replaced !== pm.method) {
1374
+ const message = `${pm.method}: "${pm.name}" already has the method "${replaced}" \u2014 replaced`;
1375
+ this.diag(message, pm.lineNo, pm.text);
1376
+ }
1377
+ this.elements[index] = { ...el, decorators: { ...el.decorators, method: pm.method } };
1378
+ const methodLines = this.methodLinesById.get(el.id) ?? [];
1379
+ methodLines.push(pm.lineNo);
1380
+ this.methodLinesById.set(el.id, methodLines);
1381
+ }
1382
+ }
1383
+ };
1384
+ function renamedMessage(sourceName, name) {
1385
+ return `Name "${sourceName}" renamed to "${name}" \u2014 a name cannot hold link operators ("->", "+>", "+<", "+'"), comment markers or a leading "{"`;
1386
+ }
1387
+ function withoutTrailingCarriageReturns(line) {
1388
+ let end = line.length;
1389
+ while (end > 0 && line[end - 1] === "\r") end--;
1390
+ return line.slice(0, end);
1391
+ }
1392
+ function withoutClosersOfKeptComments(entries, report) {
1393
+ const nextParse = new CommentStripper();
1394
+ return entries.map((entry) => {
1395
+ let text = entry.text;
1396
+ if (!entry.isComment && nextParse.insideBlockComment && text.includes("*/")) {
1397
+ text = text.replaceAll("*/", " ");
1398
+ report(
1399
+ 'Ignored "*/" \u2014 this line is kept after an unclosed "/*" and would end that comment',
1400
+ entry.lineNo,
1401
+ entry.source
1402
+ );
1403
+ }
1404
+ nextParse.strip(text);
1405
+ return text;
767
1406
  });
768
1407
  }
769
- function clamp01(n) {
770
- return n < 0 ? 0 : n > 1 ? 1 : n;
1408
+ function replacedConfigLines(unusedLines, config, report) {
1409
+ const configIsSet = {
1410
+ evolution: config.evolutionLabels !== void 0,
1411
+ "y-axis": config.yAxisLabel !== void 0
1412
+ };
1413
+ const replacedIndexes = /* @__PURE__ */ new Set();
1414
+ for (const unused of unusedLines) {
1415
+ const replaced = configIsSet[unused.keyword];
1416
+ if (replaced) replacedIndexes.add(unused.index);
1417
+ const outcome = replaced ? `removed; another "${unused.keyword}" line sets it` : "not used";
1418
+ report(`${unused.reason} \u2014 ${outcome}`, unused.line, unused.text);
1419
+ }
1420
+ return replacedIndexes;
771
1421
  }
772
- var SINGLE_COORD_RE = /\[\s*([-\d.]+)\s*\]/;
773
- function parseBlockChild(after) {
774
- const m = SINGLE_COORD_RE.exec(after);
775
- if (!m) return null;
776
- const maturity = Number(m[1]);
1422
+ function resolveUrlReferences(elements, refs, definitions, report, resolved) {
1423
+ const definitionByName = /* @__PURE__ */ new Map();
1424
+ const replaced = /* @__PURE__ */ new Set();
1425
+ for (const definition of definitions) {
1426
+ const earlier = definitionByName.get(definition.name);
1427
+ if (earlier) {
1428
+ replaced.add(earlier);
1429
+ report(
1430
+ `Repeated url definition "${definition.name}" \u2014 replaces the one on line ${earlier.lineNo}, which is kept unused`,
1431
+ definition.lineNo,
1432
+ definition.text
1433
+ );
1434
+ }
1435
+ definitionByName.set(definition.name, definition);
1436
+ }
1437
+ const used = /* @__PURE__ */ new Set();
1438
+ for (const { index, ref, line, text } of refs) {
1439
+ const definition = definitionByName.get(ref);
1440
+ if (definition) used.add(definition);
1441
+ const address = definition?.address ?? (/^[a-z][\w+.-]*:\/\//i.test(ref) ? ref : void 0);
1442
+ if (!address) {
1443
+ report(`url(${ref}) has no matching "url ${ref} [address]" line \u2014 ignored`, line, text);
1444
+ continue;
1445
+ }
1446
+ const el = elements[index];
1447
+ if (el.elementType === "component") elements[index] = { ...el, url: address };
1448
+ else if (el.elementType === "submap") elements[index] = { ...el, urlRef: address };
1449
+ resolved(el, definition);
1450
+ }
1451
+ return definitions.filter((definition) => replaced.has(definition) || !used.has(definition));
1452
+ }
1453
+ function parseNode(after, suffixes, report, keywordMethod) {
1454
+ const split = splitAtCoords(after);
1455
+ if (!split || !split.name) return null;
1456
+ const suffix = readSuffix(split.suffix, suffixes, report, "after the coordinates", keywordMethod);
1457
+ return compact({
1458
+ name: split.name,
1459
+ coords: split.coords,
1460
+ decorators: suffix.decorators,
1461
+ labelOffset: suffix.labelOffset,
1462
+ urlRef: suffix.urlRef,
1463
+ color: suffix.color
1464
+ });
1465
+ }
1466
+ var COMPONENT_SUFFIXES = /* @__PURE__ */ new Set(["color", "decorators", "label", "url"]);
1467
+ var PIPELINE_CHILD_SUFFIXES = /* @__PURE__ */ new Set(["color", "decorators", "label"]);
1468
+ var ANCHOR_SUFFIXES = /* @__PURE__ */ new Set(["color", "label"]);
1469
+ var SUBMAP_SUFFIXES = /* @__PURE__ */ new Set(["color", "url"]);
1470
+ var ACCELERATOR_SUFFIXES = /* @__PURE__ */ new Set(["color"]);
1471
+ var NOTE_SUFFIXES = /* @__PURE__ */ new Set(["color"]);
1472
+ var ATTITUDE_SUFFIXES = /* @__PURE__ */ new Set(["color"]);
1473
+ var PIPELINE_SUFFIXES = /* @__PURE__ */ new Set(["color", "height"]);
1474
+ var DRAWING_SUFFIXES = /* @__PURE__ */ new Set(["color", "stroke"]);
1475
+ var EVOLVE_SUFFIXES = /* @__PURE__ */ new Set(["method"]);
1476
+ var NO_SUFFIXES = /* @__PURE__ */ new Set();
1477
+ function readSuffix(text, slots, report, place = "after the coordinates", keywordMethod) {
1478
+ const reading = {};
1479
+ const decorators = keywordMethod ? { method: keywordMethod } : {};
1480
+ const seen = /* @__PURE__ */ new Set();
1481
+ const ignored = [];
1482
+ const readGroupItem = (item) => {
1483
+ if (slots.has("decorators") && (item === "market" || item === "ecosystem" || item === "inertia")) {
1484
+ decorators[item] = true;
1485
+ return true;
1486
+ }
1487
+ if ((slots.has("decorators") || slots.has("method")) && METHODS.has(item)) {
1488
+ decorators.method ??= item;
1489
+ return decorators.method === item;
1490
+ }
1491
+ if (slots.has("stroke") && item === "closed") {
1492
+ reading.closed = true;
1493
+ return true;
1494
+ }
1495
+ if (slots.has("stroke") && (item === "dashed" || item === "dotted")) {
1496
+ reading.strokeStyle ??= item;
1497
+ return reading.strokeStyle === item;
1498
+ }
1499
+ return false;
1500
+ };
1501
+ const firstOf = (token, slot) => {
1502
+ if (!slots.has(slot) || seen.has(token.kind)) return false;
1503
+ seen.add(token.kind);
1504
+ return true;
1505
+ };
1506
+ for (const token of scanSuffix(text)) {
1507
+ switch (token.kind) {
1508
+ case "color":
1509
+ if (firstOf(token, "color")) reading.color = token.color;
1510
+ else ignored.push(token);
1511
+ break;
1512
+ case "height":
1513
+ if (firstOf(token, "height")) {
1514
+ const height = readUnclampedNumber(token.value);
1515
+ if (height === null) report(unreadableNumberMessage(token.text));
1516
+ else reading.height = height;
1517
+ } else ignored.push(token);
1518
+ break;
1519
+ case "label":
1520
+ if (firstOf(token, "label")) {
1521
+ const dx = readUnclampedNumber(token.dx);
1522
+ const dy = readUnclampedNumber(token.dy);
1523
+ if (dx === null || dy === null) report(unreadableNumberMessage(token.text));
1524
+ else reading.labelOffset = { dx, dy };
1525
+ } else ignored.push(token);
1526
+ break;
1527
+ case "url":
1528
+ if (token.ref && firstOf(token, "url")) reading.urlRef = token.ref;
1529
+ else ignored.push(token);
1530
+ break;
1531
+ case "inertia":
1532
+ if (slots.has("decorators")) decorators.inertia = true;
1533
+ else ignored.push(token);
1534
+ break;
1535
+ case "group": {
1536
+ const unfit = token.items.filter((item) => !readGroupItem(item.text.toLowerCase()));
1537
+ if (unfit.length === token.items.length) ignored.push(token);
1538
+ else for (const item of unfit) ignored.push(item);
1539
+ break;
1540
+ }
1541
+ case "word":
1542
+ ignored.push(token);
1543
+ }
1544
+ }
1545
+ if (ignored.length) report(`Ignored text ${place}: ${quotedSpans(text, ignored)}`);
1546
+ return compact({ ...reading, decorators });
1547
+ }
1548
+ function quotedSpans(text, spans) {
1549
+ const pieces = [];
1550
+ let start = spans[0].at;
1551
+ let end = start + spans[0].text.length;
1552
+ for (let i = 1; i < spans.length; i++) {
1553
+ const span = spans[i];
1554
+ if (text.slice(end, span.at).trim() !== "") {
1555
+ pieces.push(text.slice(start, end));
1556
+ start = span.at;
1557
+ }
1558
+ end = span.at + span.text.length;
1559
+ }
1560
+ pieces.push(text.slice(start, end));
1561
+ return pieces.map((piece) => `"${piece}"`).join(", ");
1562
+ }
1563
+ function splitPipelineLine(body) {
1564
+ const kinds = { color: true, height: true };
1565
+ const split = splitAtTuple(body);
1566
+ if (split) {
1567
+ return {
1568
+ name: split.before,
1569
+ range: { tuple: split.tuple, coords: split.coords },
1570
+ suffixText: split.after,
1571
+ misplaced: splitTrailingGroups(split.before, kinds).groups
1572
+ };
1573
+ }
1574
+ const { rest, groups } = splitTrailingGroups(body, kinds);
1575
+ return { name: rest, range: null, suffixText: groups.join(" "), misplaced: [] };
1576
+ }
1577
+ function unreadableNumberMessage(text) {
1578
+ return `Unreadable number in "${text}" \u2014 ignored`;
1579
+ }
1580
+ function pipelineRange(p) {
1581
+ if (p.start !== void 0 && p.end !== void 0) {
1582
+ return { start: roundAsWritten(p.start), end: roundAsWritten(p.end) };
1583
+ }
1584
+ const [first, ...others] = p.children;
1585
+ if (!first) return null;
1586
+ let start = first.maturity;
1587
+ let end = first.maturity;
1588
+ for (const child of others) {
1589
+ start = Math.min(start, child.maturity);
1590
+ end = Math.max(end, child.maturity);
1591
+ }
1592
+ return { start: roundAsWritten(start), end: roundAsWritten(end), fromChildren: true };
1593
+ }
1594
+ function widenEmptyRange({ start, end }) {
1595
+ if (end > start) return { start, end };
1596
+ const widenedStart = start >= 1 ? 0.95 : start;
1597
+ return { start: widenedStart, end: roundAsWritten(Math.min(1, widenedStart + 0.05)) };
1598
+ }
1599
+ function pipelineElements(p, id, visibility, range, ids, childNames) {
1600
+ const children = p.children.map(
1601
+ (c, index) => compact({
1602
+ id: ids.alloc("cmp", childNames[index]),
1603
+ elementType: "component",
1604
+ label: childNames[index],
1605
+ position: { visibility, evolution: c.maturity },
1606
+ labelOffset: c.labelOffset,
1607
+ decorators: Object.keys(c.decorators).length ? c.decorators : void 0,
1608
+ pipelineId: id,
1609
+ color: c.color
1610
+ })
1611
+ );
1612
+ const pipeline = {
1613
+ id,
1614
+ elementType: "pipeline",
1615
+ label: p.name,
1616
+ position: { visibility, evolution: (range.start + range.end) / 2 },
1617
+ evolutionStart: range.start,
1618
+ evolutionEnd: range.end,
1619
+ childIds: children.map((child) => child.id),
1620
+ ...p.color ? { color: p.color } : {}
1621
+ };
1622
+ return { pipeline, children };
1623
+ }
1624
+ function parseBlockChild(after, report) {
1625
+ const split = splitAtFirstChildTuple(after);
1626
+ if (!split?.before || split.values.length !== 1) return null;
1627
+ const maturity = Number(split.values[0]);
777
1628
  if (Number.isNaN(maturity)) return null;
778
- const name = after.slice(0, m.index).trim();
779
- if (!name) return null;
780
- const suffix = after.slice(m.index + m[0].length);
781
- const col = parseColor(suffix);
782
- const lo = parseLabelOffset(col.rest);
783
- const dec = parseDecorators(lo.rest);
1629
+ const suffix = readSuffix(split.after, PIPELINE_CHILD_SUFFIXES, report);
784
1630
  return compact({
785
- name,
1631
+ name: split.before,
786
1632
  maturity,
787
- decorators: dec.decorators,
788
- labelOffset: lo.labelOffset ?? void 0,
789
- color: col.color ?? void 0
1633
+ decorators: suffix.decorators,
1634
+ labelOffset: suffix.labelOffset,
1635
+ color: suffix.color
790
1636
  });
791
1637
  }
792
- function makeAttitude(ids, kind, v1, m1, v2, m2, color) {
1638
+ function makeAttitude(ids, kind, [v1, m1, v2, m2], color) {
793
1639
  return {
794
1640
  id: ids.alloc("attitude", kind),
795
1641
  elementType: "attitude",
@@ -797,12 +1643,12 @@ function makeAttitude(ids, kind, v1, m1, v2, m2, color) {
797
1643
  label: "",
798
1644
  ...color ? { color } : {},
799
1645
  position: {
800
- visibility: clamp01(Math.max(v1, v2)),
801
- evolution: clamp01(Math.min(m1, m2))
1646
+ visibility: Math.max(v1, v2),
1647
+ evolution: Math.min(m1, m2)
802
1648
  },
803
1649
  corner2: {
804
- visibility: clamp01(Math.min(v1, v2)),
805
- evolution: clamp01(Math.max(m1, m2))
1650
+ visibility: Math.min(v1, v2),
1651
+ evolution: Math.max(m1, m2)
806
1652
  }
807
1653
  };
808
1654
  }
@@ -810,18 +1656,36 @@ function mergeLegacy(kw, dec) {
810
1656
  const merged = { ...dec };
811
1657
  if (kw === "market") merged["market"] = true;
812
1658
  if (kw === "ecosystem") merged["ecosystem"] = true;
1659
+ if (METHODS.has(kw)) merged["method"] = kw;
813
1660
  return compact(merged);
814
1661
  }
815
- function parseEvolve(after) {
1662
+ var MISPLACED_EVOLVE_SUFFIX_RE = /(?:\((build|buy|outsource)\)|\binertia)$/i;
1663
+ function splitMisplacedEvolveSuffix(name) {
1664
+ const m = MISPLACED_EVOLVE_SUFFIX_RE.exec(name);
1665
+ if (!m) return null;
1666
+ const rest = name.slice(0, m.index).trimEnd();
1667
+ return rest ? { name: rest, suffix: m[0] } : null;
1668
+ }
1669
+ function misplacedEvolveSuffixHint({ name, suffix }) {
1670
+ return suffix.startsWith("(") ? ` \u2014 for component "${name}", write "${suffix}" after the target` : ` \u2014 for component "${name}", write "${suffix}" on its component line`;
1671
+ }
1672
+ var NUMBER_TOKEN_RE = /(^|\s)([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?)(?=\s|\(|$)/gi;
1673
+ function parseEvolve(after, report) {
816
1674
  const lo = parseLabelOffset(after);
817
- const dec = parseDecorators(lo.rest);
818
- const tokens = dec.rest.trim().split(/\s+/);
819
- if (tokens.length < 2) return null;
820
- const last = tokens[tokens.length - 1];
821
- const target = Number(last);
822
- if (Number.isNaN(target)) return null;
823
- const namePart = tokens.slice(0, -1).join(" ").trim();
824
- if (!namePart) return null;
1675
+ let targetMatch;
1676
+ for (const match of lo.rest.matchAll(NUMBER_TOKEN_RE)) targetMatch = match;
1677
+ if (!targetMatch) return null;
1678
+ const targetAt = targetMatch.index + targetMatch[1].length;
1679
+ const namePart = lo.rest.slice(0, targetAt).trim();
1680
+ const target = Number(targetMatch[2]);
1681
+ if (!namePart || !Number.isFinite(target)) return null;
1682
+ if (lo.unreadable) report(unreadableNumberMessage(lo.unreadable));
1683
+ const tail = readSuffix(
1684
+ lo.rest.slice(targetAt + targetMatch[2].length),
1685
+ EVOLVE_SUFFIXES,
1686
+ report,
1687
+ "after the evolve target"
1688
+ );
825
1689
  const renameIdx = namePart.indexOf("->");
826
1690
  const name = renameIdx >= 0 ? namePart.slice(0, renameIdx).trim() : namePart;
827
1691
  const newLabel = renameIdx >= 0 ? namePart.slice(renameIdx + 2).trim() : void 0;
@@ -829,10 +1693,21 @@ function parseEvolve(after) {
829
1693
  name,
830
1694
  newLabel: newLabel || void 0,
831
1695
  target,
832
- method: dec.decorators.method,
1696
+ method: tail.decorators.method,
833
1697
  labelOffset: lo.labelOffset ?? void 0
834
1698
  });
835
1699
  }
1700
+ function sizeOutsideLimits(width, height) {
1701
+ const below = width < PLOT_MIN.width || height < PLOT_MIN.height;
1702
+ const above = width > PLOT_MAX.width || height > PLOT_MAX.height;
1703
+ if (!below && !above) return null;
1704
+ const drawnWidth = drawnPlotLength(width, "width");
1705
+ const drawnHeight = drawnPlotLength(height, "height");
1706
+ const minimum = `${PLOT_MIN.width}\xD7${PLOT_MIN.height}`;
1707
+ const maximum = `${PLOT_MAX.width}\xD7${PLOT_MAX.height}`;
1708
+ const limit = below && above ? `outside ${minimum} to ${maximum}` : below ? `below the minimum ${minimum}` : `above the maximum ${maximum}`;
1709
+ return `Map size ${width}\xD7${height} is ${limit} \u2014 drawn at ${drawnWidth}\xD7${drawnHeight}`;
1710
+ }
836
1711
 
837
1712
  // src/serializer.ts
838
1713
  function urlOf(el) {
@@ -841,26 +1716,59 @@ function urlOf(el) {
841
1716
  return void 0;
842
1717
  }
843
1718
  function r(n) {
844
- return String(Math.round(n * 1e3) / 1e3);
845
- }
846
- var NAMED_TYPES = /* @__PURE__ */ new Set(["anchor", "component", "accelerator", "submap"]);
847
- function defaultName(type) {
848
- return type === "anchor" ? "User" : type === "accelerator" ? "Accelerator" : type === "submap" ? "Submap" : "Component";
1719
+ return String(roundAsWritten(n));
849
1720
  }
850
1721
  function uniqueNames(map) {
851
- const used = /* @__PURE__ */ new Set();
1722
+ const namesInUse = new UniqueNames();
852
1723
  const byId = /* @__PURE__ */ new Map();
853
1724
  for (const el of map.elements) {
854
- if (!NAMED_TYPES.has(el.elementType)) continue;
855
- const base = el.label.trim().replace(/->/g, "\u2192") || defaultName(el.elementType);
856
- let name = base;
857
- let i = 2;
858
- while (used.has(name)) name = `${base} ${i++}`;
859
- used.add(name);
860
- byId.set(el.id, name);
1725
+ if (NAMED_TYPES.has(el.elementType)) {
1726
+ byId.set(el.id, namesInUse.claim(writtenName(el.label, el.elementType)));
1727
+ } else if (el.elementType === "pipeline") {
1728
+ byId.set(el.id, writtenName(el.label, el.elementType));
1729
+ }
861
1730
  }
862
1731
  return byId;
863
1732
  }
1733
+ var EMBEDDABLE_ADDRESS_RE = /^[a-z][\w+.-]*:\/\/[^\s()]*$/i;
1734
+ function planUrls(map, nameOf, keptDefinitionNames, hints) {
1735
+ const namesInUse = new UniqueNames();
1736
+ for (const name of keptDefinitionNames) namesInUse.claim(name);
1737
+ const addressByHintedName = /* @__PURE__ */ new Map();
1738
+ const definitionNameById = /* @__PURE__ */ new Map();
1739
+ const referenceById = /* @__PURE__ */ new Map();
1740
+ for (const el of map.elements) {
1741
+ const address = urlOf(el);
1742
+ const hint = hints?.get(el.id);
1743
+ if (!address || !hint) continue;
1744
+ if (hint.kind === "embedded") {
1745
+ if (EMBEDDABLE_ADDRESS_RE.test(address)) referenceById.set(el.id, address);
1746
+ continue;
1747
+ }
1748
+ const hintedAddress = addressByHintedName.get(hint.name);
1749
+ if (hintedAddress === void 0) {
1750
+ addressByHintedName.set(hint.name, address);
1751
+ namesInUse.reserve(hint.name);
1752
+ } else if (hintedAddress !== address) continue;
1753
+ definitionNameById.set(el.id, hint.name);
1754
+ }
1755
+ const definitions = [];
1756
+ const written = /* @__PURE__ */ new Set();
1757
+ for (const el of map.elements) {
1758
+ const address = urlOf(el);
1759
+ if (!address || referenceById.has(el.id)) continue;
1760
+ let name = definitionNameById.get(el.id);
1761
+ if (name === void 0) {
1762
+ const readable = nameOf(el).replace(/[()[\]<>]/g, " ").replace(/\s+/g, " ").trim();
1763
+ name = namesInUse.claim(`${readable} URL`.trim());
1764
+ }
1765
+ referenceById.set(el.id, name);
1766
+ if (written.has(name)) continue;
1767
+ written.add(name);
1768
+ definitions.push({ name, address });
1769
+ }
1770
+ return { definitions, referenceById };
1771
+ }
864
1772
  function offsetSuffix(lo) {
865
1773
  return lo ? ` label [${r(lo.dx)}, ${r(lo.dy)}]` : "";
866
1774
  }
@@ -878,34 +1786,83 @@ function decoratorSuffix(dec) {
878
1786
  if (dec.inertia) out += " inertia";
879
1787
  return out;
880
1788
  }
881
- function serializeDSL(map) {
1789
+ function configLines(config) {
1790
+ const lines = [{ key: "config:title", text: `title ${writtenText(config.title)}` }];
1791
+ const add = (keyword, text) => lines.push({ key: `config:${keyword}`, text });
1792
+ if (config.style) add("style", `style ${config.style}`);
1793
+ if (config.size) add("size", `size [${r(config.size.width)}, ${r(config.size.height)}]`);
1794
+ if (config.evolutionLabels) {
1795
+ add("evolution", `evolution ${config.evolutionLabels.map(writtenText).join("->")}`);
1796
+ }
1797
+ if (config.yAxisLabel) {
1798
+ const ends = config.yAxisEndLabels;
1799
+ const endLabels = ends ? `->${writtenText(ends[0])}->${writtenText(ends[1])}` : "";
1800
+ add("y-axis", `y-axis ${writtenText(config.yAxisLabel)}${endLabels}`);
1801
+ }
1802
+ if (config.annotationsBoxPosition) {
1803
+ const b = config.annotationsBoxPosition;
1804
+ add("annotations", `annotations [${r(b.visibility)}, ${r(b.evolution)}]`);
1805
+ }
1806
+ return lines;
1807
+ }
1808
+ function passthroughLines(map) {
1809
+ const emitted = /* @__PURE__ */ new Set();
1810
+ if (map.config.evolutionLabels) emitted.add("evolution");
1811
+ if (map.config.yAxisLabel) emitted.add("y-axis");
1812
+ const comments = new CommentStripper();
882
1813
  const lines = [];
883
- const names = uniqueNames(map);
884
- const nameOf = (el) => names.get(el.id) ?? el.label;
885
- lines.push(`title ${map.config.title}`);
886
- if (map.config.style) lines.push(`style ${map.config.style}`);
887
- if (map.config.size)
888
- lines.push(`size [${r(map.config.size.width)}, ${r(map.config.size.height)}]`);
889
- if (map.config.evolutionLabels) lines.push(`evolution ${map.config.evolutionLabels.join("->")}`);
890
- if (map.config.yAxisLabel) {
891
- const ends = map.config.yAxisEndLabels;
892
- lines.push(`y-axis ${map.config.yAxisLabel}${ends ? `->${ends[0]}->${ends[1]}` : ""}`);
893
- }
894
- if (map.config.annotationsBoxPosition) {
895
- const b = map.config.annotationsBoxPosition;
896
- lines.push(`annotations [${r(b.visibility)}, ${r(b.evolution)}]`);
897
- }
898
- const urlDefNames = /* @__PURE__ */ new Map();
1814
+ const urlDefinitionNames = [];
1815
+ (map.rawPassthrough ?? []).forEach((raw, index) => {
1816
+ const code = comments.strip(raw).code;
1817
+ const keyword = keywordOf(code);
1818
+ if (emitted.has(keyword)) return;
1819
+ lines.push({ key: `raw:${index}`, text: raw });
1820
+ const definition = keyword === "url" ? readUrlDefinition(code.trim().slice(3)) : null;
1821
+ if (definition) urlDefinitionNames.push(definition.name);
1822
+ });
1823
+ return { lines, urlDefinitionNames };
1824
+ }
1825
+ function pipelineHeights(map, pipelineIds, nameOf) {
1826
+ const componentVisibilityByName = /* @__PURE__ */ new Map();
899
1827
  for (const el of map.elements) {
900
- const address = urlOf(el);
901
- if (!address) continue;
902
- const defName = `${nameOf(el)} URL`;
903
- urlDefNames.set(el.id, defName);
904
- lines.push(`url ${defName} [${address}]`);
1828
+ if (el.elementType !== "component") continue;
1829
+ const isChild = !!el.pipelineId && pipelineIds.has(el.pipelineId);
1830
+ if (!isChild) componentVisibilityByName.set(nameOf(el), el.position.visibility);
1831
+ }
1832
+ return (el) => {
1833
+ if (el.elementType !== "pipeline") return "";
1834
+ const derived = componentVisibilityByName.get(nameOf(el)) ?? 0.5;
1835
+ const written = r(el.position.visibility);
1836
+ return written !== r(derived) ? ` (y ${written})` : "";
1837
+ };
1838
+ }
1839
+ function edgeLines(map, nameOf) {
1840
+ const namesById = new Map(map.elements.map((el) => [el.id, nameOf(el)]));
1841
+ return map.edges.map((edge) => {
1842
+ const from = namesById.get(edge.from) ?? edge.from;
1843
+ const to = namesById.get(edge.to) ?? edge.to;
1844
+ const annotation = edge.label ? `; ${writtenText(edge.label)}` : "";
1845
+ const key = `edge:${edge.id}`;
1846
+ if (edge.edgeType === "dependency") return { key, text: `${from} -> ${to}${annotation}` };
1847
+ const op = edge.flowValue ? `+'${edge.flowValue}'${edge.bidirectional ? "<>" : ">"}` : edge.bidirectional ? "+<>" : "+>";
1848
+ return { key, text: `${from} ${op} ${to}${annotation}` };
1849
+ });
1850
+ }
1851
+ function serializeDSL(map) {
1852
+ return [...serializeKeyedLines(map).map((line) => line.text), ""].join("\n");
1853
+ }
1854
+ function serializeKeyedLines(map, hints = {}) {
1855
+ const names = uniqueNames(map);
1856
+ const nameOf = (el) => names.get(el.id) ?? writtenText(el.label);
1857
+ const passthrough = passthroughLines(map);
1858
+ const lines = configLines(map.config);
1859
+ const urls = planUrls(map, nameOf, passthrough.urlDefinitionNames, hints.urlReferences);
1860
+ for (const { name, address } of urls.definitions) {
1861
+ lines.push({ key: `url:${name}`, text: `url ${name} [${address}]` });
905
1862
  }
906
1863
  const urlSuffix = (el) => {
907
- const def = urlDefNames.get(el.id);
908
- return def ? ` url(${def})` : "";
1864
+ const reference = urls.referenceById.get(el.id);
1865
+ return reference ? ` url(${reference})` : "";
909
1866
  };
910
1867
  const pipelineIds = new Set(
911
1868
  map.elements.filter((e) => e.elementType === "pipeline").map((e) => e.id)
@@ -919,61 +1876,32 @@ function serializeDSL(map) {
919
1876
  list.push(el);
920
1877
  childrenByPipeline.set(el.pipelineId, list);
921
1878
  }
922
- const isPipelineChild = (el) => el.elementType === "component" && !!el.pipelineId && pipelineIds.has(el.pipelineId);
1879
+ const pipelineHeight = pipelineHeights(map, pipelineIds, nameOf);
923
1880
  const evolveLines = [];
924
- const componentVisByLabel = /* @__PURE__ */ new Map();
925
- for (const el of map.elements) {
926
- if (el.elementType === "component" && !componentVisByLabel.has(el.label)) {
927
- componentVisByLabel.set(el.label, el.position.visibility);
928
- }
929
- }
930
- const pipelineYSuffix = (el) => {
931
- if (el.elementType !== "pipeline") return "";
932
- const derived = componentVisByLabel.get(el.label) ?? 0.5;
933
- return Math.abs(el.position.visibility - derived) > 5e-4 ? ` (y ${r(el.position.visibility)})` : "";
934
- };
935
1881
  for (const el of map.elements) {
936
1882
  if (el.elementType === "component" && el.movement) {
937
- evolveLines.push(evolveLine(el, nameOf(el)));
938
- }
939
- if (isPipelineChild(el)) continue;
940
- lines.push(elementLine(el, nameOf(el)) + pipelineYSuffix(el) + urlSuffix(el));
941
- if (el.elementType === "pipeline") {
942
- const kids = childrenByPipeline.get(el.id) ?? [];
943
- if (kids.length) {
944
- lines.push("{");
945
- for (const k of kids) {
946
- lines.push(
947
- ` component ${nameOf(k)} [${r(k.position.evolution)}]${decoratorSuffix(k.decorators)}${colorSuffix(k)}${offsetSuffix(k.labelOffset)}`
948
- );
949
- }
950
- lines.push("}");
951
- }
1883
+ evolveLines.push({ key: `evolve:${el.id}`, text: evolveLine(el, nameOf(el)) });
952
1884
  }
953
- }
954
- for (const line of evolveLines) lines.push(line);
955
- const labelsById = new Map(map.elements.map((el) => [el.id, el.label]));
956
- for (const edge of map.edges) {
957
- const from = names.get(edge.from) ?? labelsById.get(edge.from) ?? edge.from;
958
- const to = names.get(edge.to) ?? labelsById.get(edge.to) ?? edge.to;
959
- const annotation = edge.label ? `; ${edge.label}` : "";
960
- if (edge.edgeType === "dependency") {
961
- lines.push(`${from} -> ${to}${annotation}`);
962
- } else {
963
- const op = edge.flowValue ? `+'${edge.flowValue}'${edge.bidirectional ? "<>" : ">"}` : edge.bidirectional ? "+<>" : "+>";
964
- lines.push(`${from} ${op} ${to}${annotation}`);
1885
+ if (el.elementType === "component" && el.pipelineId && pipelineIds.has(el.pipelineId)) {
1886
+ continue;
965
1887
  }
966
- }
967
- if (map.rawPassthrough) {
968
- const emitted = /* @__PURE__ */ new Set();
969
- if (map.config.evolutionLabels) emitted.add("evolution");
970
- if (map.config.yAxisLabel) emitted.add("y-axis");
971
- for (const raw of map.rawPassthrough) {
972
- if (emitted.has(raw.trim().split(/\s+/)[0])) continue;
973
- lines.push(raw);
1888
+ lines.push({
1889
+ key: `element:${el.id}`,
1890
+ text: elementLine(el, nameOf(el)) + pipelineHeight(el) + urlSuffix(el)
1891
+ });
1892
+ const kids = childrenByPipeline.get(el.id) ?? [];
1893
+ if (kids.length) {
1894
+ lines.push({ key: `block-open:${el.id}`, text: "{" });
1895
+ for (const k of kids) {
1896
+ lines.push({
1897
+ key: `child:${k.id}`,
1898
+ text: ` component ${nameOf(k)} [${r(k.position.evolution)}]${decoratorSuffix(k.decorators)}${colorSuffix(k)}${offsetSuffix(k.labelOffset)}`
1899
+ });
1900
+ }
1901
+ lines.push({ key: `block-close:${el.id}`, text: "}" });
974
1902
  }
975
1903
  }
976
- return lines.join("\n") + "\n";
1904
+ return [...lines, ...evolveLines, ...edgeLines(map, nameOf), ...passthrough.lines];
977
1905
  }
978
1906
  function elementLine(el, name) {
979
1907
  const p = el.position;
@@ -983,14 +1911,14 @@ function elementLine(el, name) {
983
1911
  case "component":
984
1912
  return `component ${name} [${r(p.visibility)}, ${r(p.evolution)}]${decoratorSuffix(el.decorators)}${colorSuffix(el)}${offsetSuffix(el.labelOffset)}`;
985
1913
  case "note":
986
- return `note ${name.replace(/\n/g, "\\n")} [${r(p.visibility)}, ${r(p.evolution)}]${colorSuffix(el)}`;
1914
+ return `note ${writtenNoteText(el.label)} [${r(p.visibility)}, ${r(p.evolution)}]${colorSuffix(el)}`;
987
1915
  case "pipeline":
988
1916
  return `pipeline ${name} [${r(el.evolutionStart)}, ${r(el.evolutionEnd)}]${colorSuffix(el)}`;
989
1917
  case "submap":
990
1918
  return `submap ${name} [${r(p.visibility)}, ${r(p.evolution)}]${colorSuffix(el)}`;
991
1919
  case "annotation": {
992
1920
  const pos = el.positions.length > 1 ? `[${el.positions.map((q) => `[${r(q.visibility)}, ${r(q.evolution)}]`).join(", ")}]` : `[${r(p.visibility)}, ${r(p.evolution)}]`;
993
- return `annotation ${el.number} ${pos}${colorSuffix(el)} ${el.text}`;
1921
+ return `annotation ${el.number} ${pos}${colorSuffix(el)} ${writtenText(el.text)}`;
994
1922
  }
995
1923
  case "accelerator":
996
1924
  return `${el.direction === "deaccelerate" ? "deaccelerator" : "accelerator"} ${name} [${r(p.visibility)}, ${r(p.evolution)}]${colorSuffix(el)}`;
@@ -1006,11 +1934,576 @@ function elementLine(el, name) {
1006
1934
  }
1007
1935
  function evolveLine(el, name) {
1008
1936
  const mv = el.movement;
1009
- const label = mv.newLabel ? `${name}->${mv.newLabel}` : name;
1937
+ const label = mv.newLabel ? `${name}->${writtenText(mv.newLabel)}` : name;
1010
1938
  const method = mv.method ? ` (${mv.method})` : "";
1011
1939
  return `evolve ${label} ${r(mv.targetEvolution)}${method}${offsetSuffix(mv.labelOffset)}`;
1012
1940
  }
1013
1941
 
1014
- export { keywordOf, parseCoords, parseDSL, parseDSLWithDiagnostics, parseDecorators, parseLabelOffset, serializeDSL, slug };
1942
+ // src/patch.ts
1943
+ function patchDSL(originalText, map, options = {}) {
1944
+ return patchDSLWithOutcome(originalText, map, options).text;
1945
+ }
1946
+ function patchDSLWithOutcome(originalText, map, options = {}) {
1947
+ const original = typeof originalText === "string" ? originalText : "";
1948
+ let canonical;
1949
+ try {
1950
+ canonical = serializeDSL(map);
1951
+ } catch {
1952
+ return { text: original, outcome: "unchanged" };
1953
+ }
1954
+ try {
1955
+ const expected = fingerprint(parseDSL(canonical));
1956
+ const source = readSource(original);
1957
+ const edited = alignToSource(source.map, map, options.previous);
1958
+ for (const mode of ["minimal", "rewrite"]) {
1959
+ const text = patchLines(source, edited, mode);
1960
+ if (text !== null && fingerprint(parseDSL(text)) === expected) {
1961
+ return { text, outcome: mode === "minimal" ? "patched" : "rewritten" };
1962
+ }
1963
+ }
1964
+ return { text: withLineBreaksOf(source, canonical), outcome: "serialized" };
1965
+ } catch {
1966
+ return { text: canonical, outcome: "serialized" };
1967
+ }
1968
+ }
1969
+ function readSource(text) {
1970
+ const lines = splitLines(text);
1971
+ const parsed = parseDSLWithSourceMap(text);
1972
+ const crlf = (text.match(/\r\n/g) ?? []).length;
1973
+ const lf = (text.match(/\n/g) ?? []).length - crlf;
1974
+ return {
1975
+ lines,
1976
+ shapes: shapeLines(lines),
1977
+ map: parsed.map,
1978
+ sourceMap: parsed.sourceMap,
1979
+ lineBreak: crlf > lf ? "\r\n" : "\n",
1980
+ endsWithLineBreak: text === "" || text.endsWith("\n")
1981
+ };
1982
+ }
1983
+ function splitLines(text) {
1984
+ const lines = [];
1985
+ const lineBreaks = /\r?\n/g;
1986
+ let start = 0;
1987
+ for (let match = lineBreaks.exec(text); match; match = lineBreaks.exec(text)) {
1988
+ lines.push({ text: text.slice(start, match.index), lineBreak: match[0] });
1989
+ start = match.index + match[0].length;
1990
+ }
1991
+ if (start < text.length) lines.push({ text: text.slice(start), lineBreak: "" });
1992
+ return lines;
1993
+ }
1994
+ function withoutTrailingCarriageReturns2(text) {
1995
+ let end = text.length;
1996
+ while (end > 0 && text.charCodeAt(end - 1) === 13) end--;
1997
+ return text.slice(0, end);
1998
+ }
1999
+ function shapeLines(lines) {
2000
+ const comments = new CommentStripper();
2001
+ return lines.map(({ text }) => {
2002
+ const raw = withoutTrailingCarriageReturns2(text);
2003
+ const startsInBlockComment = comments.insideBlockComment;
2004
+ let fragments = comments.strip(raw).comments;
2005
+ let rest = raw;
2006
+ let commentHead = "";
2007
+ let commentTail = "";
2008
+ let editable = true;
2009
+ if (startsInBlockComment) {
2010
+ const head = fragments[0];
2011
+ if (head?.endsWith("*/") && raw.startsWith(head)) {
2012
+ commentHead = head;
2013
+ rest = raw.slice(head.length);
2014
+ fragments = fragments.slice(1);
2015
+ } else {
2016
+ editable = false;
2017
+ }
2018
+ }
2019
+ let codePart = rest;
2020
+ if (editable && fragments.length) {
2021
+ const comment = fragments[0];
2022
+ if (fragments.length > 1 || !rest.endsWith(comment)) {
2023
+ editable = false;
2024
+ } else {
2025
+ const beforeComment = rest.slice(0, rest.length - comment.length);
2026
+ codePart = beforeComment.trimEnd();
2027
+ commentTail = beforeComment.slice(codePart.length) + comment;
2028
+ }
2029
+ }
2030
+ return {
2031
+ indent: /^\s*/.exec(codePart)[0],
2032
+ code: codePart.trim(),
2033
+ commentHead,
2034
+ commentTail,
2035
+ editable,
2036
+ endsInBlockComment: comments.insideBlockComment
2037
+ };
2038
+ });
2039
+ }
2040
+ function withLineBreaksOf(source, text) {
2041
+ if (source.lines.length === 0) return text;
2042
+ const withBreaks = source.lineBreak === "\n" ? text : text.replace(/\n/g, source.lineBreak);
2043
+ return source.endsWithLineBreak ? withBreaks : withBreaks.replace(/\r?\n$/, "");
2044
+ }
2045
+ function identityOf(el) {
2046
+ switch (el.elementType) {
2047
+ case "annotation":
2048
+ return `annotation\0${el.number}`;
2049
+ case "attitude":
2050
+ return `attitude\0${el.kind}`;
2051
+ default:
2052
+ return `${el.elementType}\0${el.label}`;
2053
+ }
2054
+ }
2055
+ function edgeIdentityOf(edge) {
2056
+ return `${edge.edgeType}\0${edge.from}\0${edge.to}`;
2057
+ }
2058
+ function matchElements(source, edited, hint = /* @__PURE__ */ new Map()) {
2059
+ const unmatchedSource = new Map(source.elements.map((el) => [el.id, el]));
2060
+ const idByEditedId = /* @__PURE__ */ new Map();
2061
+ const claim = (editedId, sourceId) => {
2062
+ idByEditedId.set(editedId, sourceId);
2063
+ unmatchedSource.delete(sourceId);
2064
+ };
2065
+ const unclaimed = () => edited.elements.filter((el) => !idByEditedId.has(el.id));
2066
+ for (const el of edited.elements) {
2067
+ const same = unmatchedSource.get(el.id);
2068
+ if (same && identityOf(same) === identityOf(el)) claim(el.id, el.id);
2069
+ }
2070
+ for (const el of unclaimed()) {
2071
+ const hinted = hint.get(el.id);
2072
+ const candidate = hinted === void 0 ? void 0 : unmatchedSource.get(hinted);
2073
+ if (candidate?.elementType === el.elementType) claim(el.id, candidate.id);
2074
+ }
2075
+ const sourceIdsByIdentity = /* @__PURE__ */ new Map();
2076
+ for (const el of unmatchedSource.values()) {
2077
+ const ids = sourceIdsByIdentity.get(identityOf(el)) ?? [];
2078
+ ids.push(el.id);
2079
+ sourceIdsByIdentity.set(identityOf(el), ids);
2080
+ }
2081
+ for (const el of unclaimed()) {
2082
+ const match = sourceIdsByIdentity.get(identityOf(el))?.shift();
2083
+ if (match !== void 0) claim(el.id, match);
2084
+ }
2085
+ for (const el of unclaimed()) {
2086
+ if (unmatchedSource.get(el.id)?.elementType === el.elementType) claim(el.id, el.id);
2087
+ }
2088
+ return idByEditedId;
2089
+ }
2090
+ function alignToSource(source, edited, previous) {
2091
+ const hint = previous ? matchElements(source, previous) : void 0;
2092
+ const idByEditedId = matchElements(source, edited, hint);
2093
+ const usedIds = /* @__PURE__ */ new Set([...source.elements.map((el) => el.id), ...idByEditedId.values()]);
2094
+ const freshId = (id) => {
2095
+ let candidate = id;
2096
+ for (let suffix = 2; usedIds.has(candidate); suffix++) candidate = `${id}~${suffix}`;
2097
+ usedIds.add(candidate);
2098
+ return candidate;
2099
+ };
2100
+ for (const el of edited.elements) {
2101
+ if (!idByEditedId.has(el.id)) idByEditedId.set(el.id, freshId(el.id));
2102
+ }
2103
+ const rename = (id) => idByEditedId.get(id) ?? id;
2104
+ const elements = edited.elements.map((el) => {
2105
+ const renamed = { ...el, id: rename(el.id) };
2106
+ if (renamed.elementType === "component" && renamed.pipelineId !== void 0) {
2107
+ return { ...renamed, pipelineId: rename(renamed.pipelineId) };
2108
+ }
2109
+ if (renamed.elementType === "pipeline") {
2110
+ return { ...renamed, childIds: renamed.childIds.map(rename) };
2111
+ }
2112
+ return renamed;
2113
+ });
2114
+ const edges = alignEdges(
2115
+ source.edges,
2116
+ edited.edges.map((edge) => ({ ...edge, from: rename(edge.from), to: rename(edge.to) }))
2117
+ );
2118
+ return {
2119
+ ...edited,
2120
+ elements: inSourceOrder(elements, source.elements),
2121
+ edges: inSourceOrder(edges, source.edges)
2122
+ };
2123
+ }
2124
+ function alignEdges(sourceEdges, editedEdges) {
2125
+ const unmatchedSource = new Map(sourceEdges.map((edge) => [edge.id, edge]));
2126
+ const idByIndex = /* @__PURE__ */ new Map();
2127
+ const claim = (index, id) => {
2128
+ idByIndex.set(index, id);
2129
+ unmatchedSource.delete(id);
2130
+ };
2131
+ editedEdges.forEach((edge, index) => {
2132
+ const same = unmatchedSource.get(edge.id);
2133
+ if (same && edgeIdentityOf(same) === edgeIdentityOf(edge)) claim(index, edge.id);
2134
+ });
2135
+ editedEdges.forEach((edge, index) => {
2136
+ if (idByIndex.has(index)) return;
2137
+ const match = [...unmatchedSource.values()].find(
2138
+ (candidate) => edgeIdentityOf(candidate) === edgeIdentityOf(edge)
2139
+ );
2140
+ if (match) claim(index, match.id);
2141
+ });
2142
+ editedEdges.forEach((edge, index) => {
2143
+ if (idByIndex.has(index)) return;
2144
+ if (unmatchedSource.get(edge.id)?.edgeType === edge.edgeType) claim(index, edge.id);
2145
+ });
2146
+ const usedIds = /* @__PURE__ */ new Set([...sourceEdges.map((edge) => edge.id), ...idByIndex.values()]);
2147
+ return editedEdges.map((edge, index) => {
2148
+ let id = idByIndex.get(index);
2149
+ if (id === void 0) {
2150
+ id = edge.id;
2151
+ for (let suffix = 2; usedIds.has(id); suffix++) id = `${edge.id}~${suffix}`;
2152
+ usedIds.add(id);
2153
+ }
2154
+ return { ...edge, id };
2155
+ });
2156
+ }
2157
+ function inSourceOrder(items, sourceItems) {
2158
+ const sourceIndex = new Map(sourceItems.map((item, index) => [item.id, index]));
2159
+ const position = (item) => sourceIndex.get(item.id) ?? Number.POSITIVE_INFINITY;
2160
+ return items.map((item, index) => ({ item, index })).sort((a, b) => position(a.item) - position(b.item) || a.index - b.index).map(({ item }) => item);
2161
+ }
2162
+ var isRawKey = (key) => key.startsWith("raw:");
2163
+ function keyedTexts(lines) {
2164
+ return new Map(lines.filter((line) => !isRawKey(line.key)).map((line) => [line.key, line.text]));
2165
+ }
2166
+ function listsByLine(lineCount) {
2167
+ return Array.from({ length: lineCount }, () => []);
2168
+ }
2169
+ function diffPassthrough(before, after) {
2170
+ const remainingByText = /* @__PURE__ */ new Map();
2171
+ for (const line of before.filter((entry) => isRawKey(entry.key))) {
2172
+ const indexes = remainingByText.get(line.text) ?? [];
2173
+ indexes.push(Number(line.key.slice("raw:".length)));
2174
+ remainingByText.set(line.text, indexes);
2175
+ }
2176
+ const added = [];
2177
+ for (const line of after.filter((entry) => isRawKey(entry.key))) {
2178
+ if (remainingByText.get(line.text)?.shift() === void 0) added.push(line);
2179
+ }
2180
+ return { removed: new Set([...remainingByText.values()].flat()), added };
2181
+ }
2182
+ function pipelineOfEachChild(map) {
2183
+ const pipelineById = /* @__PURE__ */ new Map();
2184
+ for (const el of map.elements) {
2185
+ if (el.elementType === "component" && el.pipelineId !== void 0) {
2186
+ pipelineById.set(el.id, el.pipelineId);
2187
+ }
2188
+ }
2189
+ return pipelineById;
2190
+ }
2191
+ function reparentedChildKeys(source, edited) {
2192
+ const pipelineBefore = pipelineOfEachChild(source);
2193
+ const keys = /* @__PURE__ */ new Set();
2194
+ for (const [id, pipelineId] of pipelineOfEachChild(edited)) {
2195
+ const previous = pipelineBefore.get(id);
2196
+ if (previous !== void 0 && previous !== pipelineId) keys.add(`child:${id}`);
2197
+ }
2198
+ return keys;
2199
+ }
2200
+ function pipelinesNoLongerSpannedByChildren(edited, rangeFromChildren) {
2201
+ const keys = /* @__PURE__ */ new Set();
2202
+ if (rangeFromChildren.size === 0) return keys;
2203
+ const evolutionsByPipeline = /* @__PURE__ */ new Map();
2204
+ for (const el of edited.elements) {
2205
+ if (el.elementType !== "component" || el.pipelineId === void 0) continue;
2206
+ const evolutions = evolutionsByPipeline.get(el.pipelineId) ?? [];
2207
+ evolutions.push(roundAsWritten(el.position.evolution));
2208
+ evolutionsByPipeline.set(el.pipelineId, evolutions);
2209
+ }
2210
+ for (const el of edited.elements) {
2211
+ if (el.elementType !== "pipeline" || !rangeFromChildren.has(el.id)) continue;
2212
+ const evolutions = evolutionsByPipeline.get(el.id) ?? [];
2213
+ const read = evolutions.length > 0 ? widenEmptyRange({ start: Math.min(...evolutions), end: Math.max(...evolutions) }) : void 0;
2214
+ const spanned = read !== void 0 && read.start === roundAsWritten(el.evolutionStart) && read.end === roundAsWritten(el.evolutionEnd);
2215
+ if (!spanned) keys.add(`element:${el.id}`);
2216
+ }
2217
+ return keys;
2218
+ }
2219
+ function patchLines(source, edited, mode) {
2220
+ const { lines, shapes, sourceMap } = source;
2221
+ const hints = { urlReferences: sourceMap.urlReferences };
2222
+ const before = serializeKeyedLines(source.map, hints);
2223
+ const after = serializeKeyedLines(edited, hints);
2224
+ const textBefore = keyedTexts(before);
2225
+ const textAfter = keyedTexts(after);
2226
+ const passthrough = diffPassthrough(before, after);
2227
+ const reparented = reparentedChildKeys(source.map, edited);
2228
+ const unspanned = pipelinesNoLongerSpannedByChildren(edited, sourceMap.rangeFromChildren);
2229
+ const statusOf = (key) => {
2230
+ const written = textAfter.get(key);
2231
+ if (written === void 0 || reparented.has(key)) return "deleted";
2232
+ if (mode === "rewrite" || written !== textBefore.get(key) || unspanned.has(key)) {
2233
+ return "changed";
2234
+ }
2235
+ return "same";
2236
+ };
2237
+ const primaryKeysByLine = listsByLine(lines.length);
2238
+ for (const [key, line] of sourceMap.primaryLineOf) {
2239
+ if (textBefore.has(key)) primaryKeysByLine[line - 1]?.push(key);
2240
+ }
2241
+ const secondaryKeysByLine = listsByLine(lines.length);
2242
+ for (const [key, secondaryLines] of sourceMap.secondaryLinesOf) {
2243
+ if (!textBefore.has(key)) continue;
2244
+ for (const line of secondaryLines) secondaryKeysByLine[line - 1]?.push(key);
2245
+ }
2246
+ const passthroughByLine = listsByLine(lines.length);
2247
+ sourceMap.passthrough.forEach((entry, index) => passthroughByLine[entry.line - 1]?.push(index));
2248
+ const bracesByLine = listsByLine(lines.length);
2249
+ for (const [pipelineId, block] of sourceMap.blocks) {
2250
+ if (block.open !== void 0) {
2251
+ bracesByLine[block.open - 1]?.push({ pipelineId, end: "open" });
2252
+ }
2253
+ if (block.close !== void 0) {
2254
+ bracesByLine[block.close - 1]?.push({ pipelineId, end: "close" });
2255
+ }
2256
+ }
2257
+ const braceRemoved = (pipelineId) => !textAfter.has(`block-open:${pipelineId}`) && (textBefore.has(`block-open:${pipelineId}`) || !textAfter.has(`element:${pipelineId}`));
2258
+ const result = [];
2259
+ for (let index = 0; index < lines.length; index++) {
2260
+ const patched = patchLine(index);
2261
+ if (patched === void 0) return null;
2262
+ result.push(patched);
2263
+ }
2264
+ function patchLine(index) {
2265
+ const line = lines[index];
2266
+ const shape = shapes[index];
2267
+ const primaries = primaryKeysByLine[index];
2268
+ const removedPassthrough = passthroughByLine[index].filter(
2269
+ (entry) => passthrough.removed.has(entry)
2270
+ );
2271
+ const braces = bracesByLine[index];
2272
+ const changed = primaries.some((key) => statusOf(key) !== "same") || secondaryKeysByLine[index].some((key) => statusOf(key) !== "same") || removedPassthrough.length > 0 || braces.some((brace) => braceRemoved(brace.pipelineId));
2273
+ if (!changed) return line.text;
2274
+ if (!shape.editable || primaries.length > 1) return void 0;
2275
+ if (removedPassthrough.some((entry) => sourceMap.passthrough[entry].isComment)) {
2276
+ return void 0;
2277
+ }
2278
+ let statement = null;
2279
+ const primary = primaries[0];
2280
+ if (primary !== void 0) {
2281
+ const status = statusOf(primary);
2282
+ if (status === "changed") statement = textAfter.get(primary).trim();
2283
+ else if (status === "deleted") statement = "";
2284
+ } else if (secondaryKeysByLine[index].length || removedPassthrough.length) {
2285
+ statement = "";
2286
+ }
2287
+ const open = braces.find((brace) => brace.end === "open");
2288
+ const close = braces.find((brace) => brace.end === "close");
2289
+ let rest = shape.code;
2290
+ let prefix = "";
2291
+ let suffix = "";
2292
+ if (open && primary !== `element:${open.pipelineId}` && rest.startsWith("{")) {
2293
+ prefix = braceRemoved(open.pipelineId) ? "" : "{";
2294
+ rest = rest.slice(1).trimStart();
2295
+ } else if (open && rest.endsWith("{")) {
2296
+ suffix = braceRemoved(open.pipelineId) ? "" : "{";
2297
+ rest = rest.slice(0, -1).trimEnd();
2298
+ } else if (open) return void 0;
2299
+ if (close && rest.endsWith("}") && !(open && suffix)) {
2300
+ suffix = braceRemoved(close.pipelineId) ? "" : "}";
2301
+ rest = rest.slice(0, -1).trimEnd();
2302
+ } else if (close) return void 0;
2303
+ const assembled = [prefix, statement ?? rest, suffix].filter(Boolean).join(" ");
2304
+ if (assembled) return shape.commentHead + shape.indent + assembled + shape.commentTail;
2305
+ if (shape.commentHead) return shape.commentHead + shape.commentTail;
2306
+ return shape.commentTail ? shape.indent + shape.commentTail.trimStart() : null;
2307
+ }
2308
+ const insertions = planInsertions(source, edited, after, textBefore, textAfter, reparented);
2309
+ if (!insertions) return null;
2310
+ passthrough.added.forEach((line, index) => {
2311
+ addInsertion(insertions, lines.length - 1, line.text, after.length + index);
2312
+ });
2313
+ return assemble(source, result, insertions);
2314
+ }
2315
+ function addInsertion(insertions, afterLine, text, order) {
2316
+ const list = insertions.get(afterLine) ?? [];
2317
+ list.push({ text, order });
2318
+ insertions.set(afterLine, list);
2319
+ }
2320
+ function planInsertions(source, edited, after, textBefore, textAfter, reparented) {
2321
+ const { lines, shapes, sourceMap } = source;
2322
+ const lastLine = lines.length - 1;
2323
+ const lineOf = (key) => {
2324
+ const line = sourceMap.primaryLineOf.get(key);
2325
+ return line === void 0 ? void 0 : line - 1;
2326
+ };
2327
+ const pipelineLineOf = (pipelineId) => lineOf(`element:${pipelineId}`);
2328
+ const childLinesOf = (pipelineId) => source.map.elements.flatMap((el) => {
2329
+ if (el.elementType !== "component" || el.pipelineId !== pipelineId) return [];
2330
+ const line = lineOf(`child:${el.id}`);
2331
+ return line === void 0 ? [] : [line];
2332
+ });
2333
+ const blockEndOf = (pipelineId) => {
2334
+ const block = sourceMap.blocks.get(pipelineId);
2335
+ if (block?.open === void 0 || pipelineLineOf(pipelineId) === void 0) return void 0;
2336
+ if (block.close !== void 0) return block.close - 1;
2337
+ return Math.max(block.open - 1, ...childLinesOf(pipelineId));
2338
+ };
2339
+ const anchorInBlock = (pipelineId) => {
2340
+ const block = sourceMap.blocks.get(pipelineId);
2341
+ let anchor;
2342
+ if (block.close === void 0) anchor = blockEndOf(pipelineId);
2343
+ else if (block.close !== block.open && shapes[block.close - 1].code === "}") {
2344
+ anchor = block.close - 2;
2345
+ } else return null;
2346
+ return shapes[anchor]?.endsInBlockComment ? null : anchor;
2347
+ };
2348
+ const hasSourceBlock = (pipelineId) => blockEndOf(pipelineId) !== void 0;
2349
+ const endOf = (key) => {
2350
+ const line = lineOf(key);
2351
+ if (line === void 0 || !key.startsWith("element:")) return line;
2352
+ return Math.max(line, blockEndOf(key.slice("element:".length)) ?? line);
2353
+ };
2354
+ const sourceElementTypes = new Map(source.map.elements.map((el) => [el.id, el.elementType]));
2355
+ const editedElementById = new Map(edited.elements.map((el) => [el.id, el]));
2356
+ const lastLineOf = (accepts) => {
2357
+ let last;
2358
+ for (const key of sourceMap.primaryLineOf.keys()) {
2359
+ if (!accepts(key) || !textBefore.has(key)) continue;
2360
+ const end = endOf(key);
2361
+ if (end !== void 0 && (last === void 0 || end > last)) last = end;
2362
+ }
2363
+ return last;
2364
+ };
2365
+ const isElementOfType = (type) => (key) => key.startsWith("element:") && sourceElementTypes.get(key.slice("element:".length)) === type;
2366
+ const startsWith = (prefix) => (key) => key.startsWith(prefix);
2367
+ const settle = (line) => {
2368
+ if (line < 0) return -1;
2369
+ let settled = line;
2370
+ for (const pipelineId of sourceMap.blocks.keys()) {
2371
+ const start = pipelineLineOf(pipelineId);
2372
+ const end = blockEndOf(pipelineId);
2373
+ if (start === void 0 || end === void 0) continue;
2374
+ if (settled >= start && settled < end) settled = end;
2375
+ }
2376
+ while (settled < lastLine && shapes[settled].endsInBlockComment) settled++;
2377
+ return settled;
2378
+ };
2379
+ const firstOf = (...candidates) => {
2380
+ for (const candidate of candidates) if (candidate !== void 0) return candidate;
2381
+ return lastLine;
2382
+ };
2383
+ const needsInsertion = (key) => reparented.has(key) || !sourceMap.primaryLineOf.has(key) && textBefore.get(key) !== textAfter.get(key);
2384
+ const anchorOfElement = (id) => {
2385
+ const type = editedElementById.get(id)?.elementType ?? "";
2386
+ return settle(
2387
+ firstOf(
2388
+ lastLineOf(isElementOfType(type)),
2389
+ lastLineOf(startsWith("element:")),
2390
+ lastLineOf(startsWith("url:")),
2391
+ lastLineOf(startsWith("config:"))
2392
+ )
2393
+ );
2394
+ };
2395
+ const anchorOfNewBlock = (pipelineId) => pipelineLineOf(pipelineId) ?? anchorOfElement(pipelineId);
2396
+ const insertions = /* @__PURE__ */ new Map();
2397
+ for (let order = 0; order < after.length; order++) {
2398
+ const { key, text } = after[order];
2399
+ if (isRawKey(key)) continue;
2400
+ const separator = key.indexOf(":");
2401
+ const kind = key.slice(0, separator);
2402
+ const id = key.slice(separator + 1);
2403
+ let anchor;
2404
+ if (kind === "block-open" || kind === "block-close") {
2405
+ if (textBefore.has(`block-open:${id}`)) continue;
2406
+ if (hasSourceBlock(id)) {
2407
+ if (anchorInBlock(id) === null) return null;
2408
+ continue;
2409
+ }
2410
+ anchor = anchorOfNewBlock(id);
2411
+ } else if (!needsInsertion(key)) {
2412
+ continue;
2413
+ } else if (kind === "config") {
2414
+ anchor = settle(firstOf(lastLineOf(startsWith("config:")), -1));
2415
+ } else if (kind === "url") {
2416
+ const lastUrl = lastLineOf(startsWith("url:"));
2417
+ anchor = settle(firstOf(lastUrl, lastLineOf(startsWith("config:")), -1));
2418
+ } else if (kind === "element") {
2419
+ anchor = anchorOfElement(id);
2420
+ } else if (kind === "child") {
2421
+ const child = editedElementById.get(id);
2422
+ const pipelineId = child?.elementType === "component" ? child.pipelineId : void 0;
2423
+ if (pipelineId === void 0) return null;
2424
+ anchor = hasSourceBlock(pipelineId) ? anchorInBlock(pipelineId) : anchorOfNewBlock(pipelineId);
2425
+ } else if (kind === "evolve") {
2426
+ anchor = settle(firstOf(lastLineOf(startsWith("evolve:")), endOf(`element:${id}`)));
2427
+ } else if (kind === "edge") {
2428
+ anchor = settle(firstOf(lastLineOf(startsWith("edge:"))));
2429
+ } else return null;
2430
+ if (anchor === null) return null;
2431
+ addInsertion(insertions, anchor, text, order);
2432
+ }
2433
+ return insertions;
2434
+ }
2435
+ function assemble(source, result, insertions) {
2436
+ const output = [];
2437
+ const insertAfter = (line) => {
2438
+ const list = [...insertions.get(line) ?? []].sort((a, b) => a.order - b.order);
2439
+ for (const { text } of list) output.push({ text, lineBreak: "" });
2440
+ };
2441
+ insertAfter(-1);
2442
+ result.forEach((text, index) => {
2443
+ if (text !== null) output.push({ text, lineBreak: source.lines[index].lineBreak });
2444
+ insertAfter(index);
2445
+ });
2446
+ return output.map(({ text, lineBreak }, index) => {
2447
+ const isLast = index === output.length - 1;
2448
+ if (isLast && !source.endsWithLineBreak) return text;
2449
+ return text + (lineBreak || source.lineBreak);
2450
+ }).join("");
2451
+ }
2452
+ function normalized(value) {
2453
+ if (typeof value === "number") return roundAsWritten(value);
2454
+ if (Array.isArray(value)) return value.map(normalized);
2455
+ if (value !== null && typeof value === "object") {
2456
+ return Object.fromEntries(
2457
+ Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => [key, normalized(entry)])
2458
+ );
2459
+ }
2460
+ return value;
2461
+ }
2462
+ function fingerprint(map) {
2463
+ const elementById = new Map(map.elements.map((el) => [el.id, el]));
2464
+ const reference = (id) => {
2465
+ const el = elementById.get(id);
2466
+ return el ? `${el.elementType}:${el.label}` : `?${id}`;
2467
+ };
2468
+ const entries = [`config ${JSON.stringify(normalized(map.config))}`];
2469
+ for (const el of map.elements) {
2470
+ const { id: _id, ...rest } = el;
2471
+ const described = { ...rest };
2472
+ if (el.elementType === "component" && el.pipelineId !== void 0) {
2473
+ described["pipelineId"] = reference(el.pipelineId);
2474
+ }
2475
+ if (el.elementType === "pipeline") described["childIds"] = el.childIds.map(reference).sort();
2476
+ entries.push(`element ${JSON.stringify(normalized(described))}`);
2477
+ }
2478
+ for (const edge of map.edges) {
2479
+ const { id: _id, ...rest } = edge;
2480
+ const described = { ...rest, from: reference(edge.from), to: reference(edge.to) };
2481
+ entries.push(`edge ${JSON.stringify(normalized(described))}`);
2482
+ }
2483
+ for (const raw of map.rawPassthrough ?? []) entries.push(`raw ${raw}`);
2484
+ return entries.sort().join("\n");
2485
+ }
2486
+
2487
+ // src/raw-passthrough.ts
2488
+ function withoutRawStatements(rawPassthrough, keyword) {
2489
+ if (!rawPassthrough) return rawPassthrough;
2490
+ const wanted = keyword.toLowerCase();
2491
+ const comments = new CommentStripper();
2492
+ let changed = false;
2493
+ const kept = [];
2494
+ for (const raw of rawPassthrough) {
2495
+ const stripped = comments.strip(raw);
2496
+ if (keywordOf(stripped.code) !== wanted) {
2497
+ kept.push(raw);
2498
+ continue;
2499
+ }
2500
+ changed = true;
2501
+ if (stripped.comments.length) kept.push(stripped.comments.join(" "));
2502
+ }
2503
+ if (!changed) return rawPassthrough;
2504
+ return kept.length ? kept : void 0;
2505
+ }
2506
+
2507
+ export { keywordOf, parseCoords, parseDSL, parseDSLWithDiagnostics, parseDecorators, parseLabelOffset, patchDSL, serializeDSL, slug, withoutRawStatements };
1015
2508
  //# sourceMappingURL=index.js.map
1016
2509
  //# sourceMappingURL=index.js.map