@diagrammo/dgmo 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/dist/auto.js +1 -1
  2. package/dist/auto.mjs +1 -1
  3. package/dist/element.js +1 -1
  4. package/dist/element.mjs +1 -1
  5. package/package.json +19 -70
  6. package/dist/advanced.cjs +0 -71648
  7. package/dist/advanced.d.cts +0 -5719
  8. package/dist/auto.cjs +0 -70648
  9. package/dist/auto.d.cts +0 -54
  10. package/dist/block.cjs +0 -70208
  11. package/dist/block.d.cts +0 -115
  12. package/dist/editor.cjs +0 -526
  13. package/dist/editor.d.cts +0 -26
  14. package/dist/element.cjs +0 -70530
  15. package/dist/element.d.cts +0 -62
  16. package/dist/highlight.cjs +0 -852
  17. package/dist/highlight.d.cts +0 -49
  18. package/dist/index.cjs +0 -70491
  19. package/dist/index.d.cts +0 -160
  20. package/dist/pert.cjs +0 -325
  21. package/dist/pert.d.cts +0 -559
  22. package/dist/themes-1-CuKpeH.d.cts +0 -908
  23. package/src/advanced.ts +0 -873
  24. package/src/arc/parser.ts +0 -15
  25. package/src/arc/renderer.ts +0 -633
  26. package/src/auto/index.ts +0 -621
  27. package/src/auto/shared.ts +0 -370
  28. package/src/auto/styles.ts +0 -73
  29. package/src/block/layout.ts +0 -198
  30. package/src/block/parser.ts +0 -427
  31. package/src/block/renderer.ts +0 -484
  32. package/src/block/types.ts +0 -67
  33. package/src/boxes-and-lines/collapse.ts +0 -96
  34. package/src/boxes-and-lines/focus.ts +0 -257
  35. package/src/boxes-and-lines/label-placement.ts +0 -339
  36. package/src/boxes-and-lines/layout-grouped.ts +0 -912
  37. package/src/boxes-and-lines/layout-layered.ts +0 -722
  38. package/src/boxes-and-lines/layout-search.ts +0 -1678
  39. package/src/boxes-and-lines/layout.ts +0 -398
  40. package/src/boxes-and-lines/parser.ts +0 -1181
  41. package/src/boxes-and-lines/renderer.ts +0 -1465
  42. package/src/boxes-and-lines/types.ts +0 -66
  43. package/src/c4/layout.ts +0 -2441
  44. package/src/c4/parser.ts +0 -1158
  45. package/src/c4/renderer.ts +0 -2008
  46. package/src/c4/types.ts +0 -89
  47. package/src/chart-type-registry.ts +0 -529
  48. package/src/chart-types.ts +0 -225
  49. package/src/chart.ts +0 -685
  50. package/src/charts-d3/bar.ts +0 -338
  51. package/src/charts-d3/chord.ts +0 -140
  52. package/src/charts-d3/function.ts +0 -147
  53. package/src/charts-d3/funnel.ts +0 -104
  54. package/src/charts-d3/heatmap.ts +0 -145
  55. package/src/charts-d3/index.ts +0 -337
  56. package/src/charts-d3/interactions.ts +0 -477
  57. package/src/charts-d3/line.ts +0 -344
  58. package/src/charts-d3/mount.ts +0 -151
  59. package/src/charts-d3/pie.ts +0 -117
  60. package/src/charts-d3/polar.ts +0 -89
  61. package/src/charts-d3/radar.ts +0 -0
  62. package/src/charts-d3/sankey.ts +0 -0
  63. package/src/charts-d3/scatter.ts +0 -185
  64. package/src/charts-d3/shared.ts +0 -208
  65. package/src/class/layout.ts +0 -326
  66. package/src/class/parser.ts +0 -635
  67. package/src/class/renderer.ts +0 -793
  68. package/src/class/types.ts +0 -58
  69. package/src/cli-banner.ts +0 -106
  70. package/src/cli.ts +0 -1080
  71. package/src/colors-diagnostics.ts +0 -35
  72. package/src/colors.ts +0 -379
  73. package/src/completion-types.ts +0 -27
  74. package/src/completion.ts +0 -2668
  75. package/src/cycle/layout.ts +0 -1026
  76. package/src/cycle/parser.ts +0 -387
  77. package/src/cycle/renderer.ts +0 -653
  78. package/src/cycle/types.ts +0 -101
  79. package/src/d3.ts +0 -1434
  80. package/src/data-chart-parser.ts +0 -1007
  81. package/src/dgmo-router.ts +0 -296
  82. package/src/diagnostics-registry.ts +0 -108
  83. package/src/diagnostics.ts +0 -0
  84. package/src/dimensions.ts +0 -20
  85. package/src/directives-registry.ts +0 -396
  86. package/src/editor/dgmo.grammar +0 -76
  87. package/src/editor/dgmo.grammar.d.ts +0 -2
  88. package/src/editor/dgmo.grammar.js +0 -18
  89. package/src/editor/dgmo.grammar.terms.d.ts +0 -5
  90. package/src/editor/dgmo.grammar.terms.js +0 -35
  91. package/src/editor/highlight-api.ts +0 -596
  92. package/src/editor/highlight.ts +0 -36
  93. package/src/editor/index.ts +0 -27
  94. package/src/editor/keywords.ts +0 -128
  95. package/src/editor/tokens.ts +0 -30
  96. package/src/element/index.ts +0 -432
  97. package/src/embed/css.ts +0 -312
  98. package/src/embed/escape.ts +0 -15
  99. package/src/embed/index.ts +0 -280
  100. package/src/er/classify.ts +0 -228
  101. package/src/er/layout.ts +0 -530
  102. package/src/er/parser.ts +0 -750
  103. package/src/er/renderer.ts +0 -725
  104. package/src/er/types.ts +0 -52
  105. package/src/error-card.ts +0 -269
  106. package/src/event-line/diagnostics.ts +0 -117
  107. package/src/event-line/parser.ts +0 -643
  108. package/src/event-line/renderer.ts +0 -1742
  109. package/src/event-line/types.ts +0 -74
  110. package/src/fonts.ts +0 -3
  111. package/src/gantt/calculator.ts +0 -979
  112. package/src/gantt/parser.ts +0 -1641
  113. package/src/gantt/renderer.ts +0 -3787
  114. package/src/gantt/resolver.ts +0 -172
  115. package/src/gantt/types.ts +0 -206
  116. package/src/graph/diagnostics.ts +0 -64
  117. package/src/graph/edge-spline.ts +0 -29
  118. package/src/graph/flowchart-parser.ts +0 -759
  119. package/src/graph/flowchart-renderer.ts +0 -817
  120. package/src/graph/layout.ts +0 -472
  121. package/src/graph/notes.ts +0 -21
  122. package/src/graph/state-collapse.ts +0 -78
  123. package/src/graph/state-parser.ts +0 -574
  124. package/src/graph/state-renderer.ts +0 -653
  125. package/src/graph/types.ts +0 -65
  126. package/src/index.ts +0 -261
  127. package/src/infra/compute.ts +0 -1385
  128. package/src/infra/layout.ts +0 -888
  129. package/src/infra/parser.ts +0 -1234
  130. package/src/infra/renderer.ts +0 -2534
  131. package/src/infra/roles.ts +0 -75
  132. package/src/infra/types.ts +0 -216
  133. package/src/infra/validation.ts +0 -201
  134. package/src/journey-map/layout.ts +0 -490
  135. package/src/journey-map/parser.ts +0 -557
  136. package/src/journey-map/renderer.ts +0 -1580
  137. package/src/journey-map/types.ts +0 -47
  138. package/src/kanban/mutations.ts +0 -175
  139. package/src/kanban/parser.ts +0 -509
  140. package/src/kanban/renderer.ts +0 -1449
  141. package/src/kanban/types.ts +0 -39
  142. package/src/label-layout.ts +0 -368
  143. package/src/map/colorize.ts +0 -54
  144. package/src/map/completion.ts +0 -316
  145. package/src/map/context-labels.ts +0 -609
  146. package/src/map/data/PROVENANCE.json +0 -1
  147. package/src/map/data/README.md +0 -40
  148. package/src/map/data/airport-collisions.json +0 -1
  149. package/src/map/data/airports.json +0 -1
  150. package/src/map/data/gazetteer.json +0 -1
  151. package/src/map/data/lakes.json +0 -1
  152. package/src/map/data/mountain-ranges.json +0 -1
  153. package/src/map/data/na-lakes.json +0 -1
  154. package/src/map/data/na-land.json +0 -1
  155. package/src/map/data/region-names.json +0 -1
  156. package/src/map/data/rivers.json +0 -1
  157. package/src/map/data/types.ts +0 -121
  158. package/src/map/data/us-states.json +0 -1
  159. package/src/map/data/water-bodies.json +0 -1
  160. package/src/map/data/world-coarse.json +0 -1
  161. package/src/map/data/world-detail.json +0 -1
  162. package/src/map/diagnostics.ts +0 -134
  163. package/src/map/dimensions.ts +0 -150
  164. package/src/map/geo-query.ts +0 -295
  165. package/src/map/geo.ts +0 -438
  166. package/src/map/invert.ts +0 -111
  167. package/src/map/layout.ts +0 -5069
  168. package/src/map/legend-band.ts +0 -127
  169. package/src/map/load-data.ts +0 -186
  170. package/src/map/parser.ts +0 -783
  171. package/src/map/renderer.ts +0 -1445
  172. package/src/map/resolved-types.ts +0 -160
  173. package/src/map/resolver.ts +0 -1146
  174. package/src/map/types.ts +0 -194
  175. package/src/mindmap/collapse.ts +0 -67
  176. package/src/mindmap/layout.ts +0 -649
  177. package/src/mindmap/parser.ts +0 -430
  178. package/src/mindmap/renderer.ts +0 -637
  179. package/src/mindmap/text-wrap.ts +0 -218
  180. package/src/mindmap/types.ts +0 -56
  181. package/src/org/collapse.ts +0 -151
  182. package/src/org/layout.ts +0 -1262
  183. package/src/org/parser.ts +0 -519
  184. package/src/org/renderer.ts +0 -866
  185. package/src/org/resolver.ts +0 -636
  186. package/src/palettes/atlas.ts +0 -77
  187. package/src/palettes/blueprint.ts +0 -73
  188. package/src/palettes/catppuccin.ts +0 -84
  189. package/src/palettes/color-utils.ts +0 -443
  190. package/src/palettes/index.ts +0 -67
  191. package/src/palettes/nord.ts +0 -67
  192. package/src/palettes/registry.ts +0 -114
  193. package/src/palettes/slate.ts +0 -73
  194. package/src/palettes/tidewater.ts +0 -73
  195. package/src/palettes/tokyo-night.ts +0 -86
  196. package/src/palettes/types.ts +0 -88
  197. package/src/pert/analyzer.ts +0 -1183
  198. package/src/pert/diagnostics.ts +0 -110
  199. package/src/pert/index.ts +0 -43
  200. package/src/pert/internal.ts +0 -252
  201. package/src/pert/layout.ts +0 -971
  202. package/src/pert/monte-carlo.ts +0 -446
  203. package/src/pert/parser.ts +0 -1606
  204. package/src/pert/renderer.ts +0 -4009
  205. package/src/pert/share-normalize.ts +0 -62
  206. package/src/pert/types.ts +0 -604
  207. package/src/pyramid/parser.ts +0 -185
  208. package/src/pyramid/renderer.ts +0 -768
  209. package/src/pyramid/types.ts +0 -28
  210. package/src/quadrant/parser.ts +0 -18
  211. package/src/quadrant/renderer.ts +0 -638
  212. package/src/raci/diagnostics.ts +0 -213
  213. package/src/raci/index.ts +0 -23
  214. package/src/raci/mutations.ts +0 -321
  215. package/src/raci/parser.ts +0 -699
  216. package/src/raci/renderer.ts +0 -1627
  217. package/src/raci/types.ts +0 -82
  218. package/src/raci/variants.ts +0 -320
  219. package/src/render.ts +0 -268
  220. package/src/ring/parser.ts +0 -212
  221. package/src/ring/renderer.ts +0 -490
  222. package/src/ring/types.ts +0 -27
  223. package/src/sequence/collapse.ts +0 -174
  224. package/src/sequence/parser.ts +0 -1596
  225. package/src/sequence/participant-inference.ts +0 -152
  226. package/src/sequence/renderer.ts +0 -3168
  227. package/src/sequence/tag-resolution.ts +0 -164
  228. package/src/sharing.ts +0 -211
  229. package/src/sitemap/collapse.ts +0 -100
  230. package/src/sitemap/layout.ts +0 -925
  231. package/src/sitemap/parser.ts +0 -755
  232. package/src/sitemap/renderer.ts +0 -828
  233. package/src/sitemap/types.ts +0 -42
  234. package/src/slope/parser.ts +0 -18
  235. package/src/slope/renderer.ts +0 -378
  236. package/src/swimlane/diagnostics.ts +0 -94
  237. package/src/swimlane/layout.ts +0 -597
  238. package/src/swimlane/parser.ts +0 -613
  239. package/src/swimlane/renderer.ts +0 -681
  240. package/src/swimlane/types.ts +0 -151
  241. package/src/tech-radar/interactive.ts +0 -1129
  242. package/src/tech-radar/layout.ts +0 -197
  243. package/src/tech-radar/parser.ts +0 -436
  244. package/src/tech-radar/renderer.ts +0 -1239
  245. package/src/tech-radar/shared.ts +0 -151
  246. package/src/tech-radar/types.ts +0 -86
  247. package/src/themes.ts +0 -22
  248. package/src/timeline/parser.ts +0 -472
  249. package/src/timeline/renderer.ts +0 -3024
  250. package/src/timeline/types.ts +0 -33
  251. package/src/timeline/viz-parser.ts +0 -21
  252. package/src/treemap/diagnostics.ts +0 -62
  253. package/src/treemap/layout-radial.ts +0 -233
  254. package/src/treemap/layout.ts +0 -189
  255. package/src/treemap/parser.ts +0 -463
  256. package/src/treemap/renderer-radial.ts +0 -438
  257. package/src/treemap/renderer.ts +0 -572
  258. package/src/treemap/treemap-shared.ts +0 -309
  259. package/src/treemap/types.ts +0 -60
  260. package/src/utils/arrow-markers.ts +0 -51
  261. package/src/utils/arrows-diagnostics.ts +0 -62
  262. package/src/utils/arrows.ts +0 -227
  263. package/src/utils/brand.ts +0 -61
  264. package/src/utils/card.ts +0 -183
  265. package/src/utils/collapse-engine/tree-edges.ts +0 -115
  266. package/src/utils/collapse-engine/tree.ts +0 -117
  267. package/src/utils/d3-helpers.ts +0 -219
  268. package/src/utils/d3-types.ts +0 -9
  269. package/src/utils/description-helpers.ts +0 -38
  270. package/src/utils/duration.ts +0 -312
  271. package/src/utils/export-container.ts +0 -41
  272. package/src/utils/expr-eval.ts +0 -27
  273. package/src/utils/fit-canvas.ts +0 -64
  274. package/src/utils/hover-styles.ts +0 -673
  275. package/src/utils/inline-markdown.ts +0 -96
  276. package/src/utils/legend-constants.ts +0 -48
  277. package/src/utils/legend-d3.ts +0 -618
  278. package/src/utils/legend-integration.ts +0 -107
  279. package/src/utils/legend-layout.ts +0 -776
  280. package/src/utils/legend-svg.ts +0 -214
  281. package/src/utils/legend-types.ts +0 -272
  282. package/src/utils/name-normalize.ts +0 -163
  283. package/src/utils/note-box/constants.ts +0 -25
  284. package/src/utils/note-box/index.ts +0 -11
  285. package/src/utils/note-box/metrics.ts +0 -90
  286. package/src/utils/note-box/svg.ts +0 -331
  287. package/src/utils/notes/bounds.ts +0 -30
  288. package/src/utils/notes/build.ts +0 -131
  289. package/src/utils/notes/index.ts +0 -18
  290. package/src/utils/notes/model.ts +0 -19
  291. package/src/utils/notes/parse.ts +0 -131
  292. package/src/utils/notes/place.ts +0 -177
  293. package/src/utils/notes/resolve.ts +0 -88
  294. package/src/utils/number-format.ts +0 -36
  295. package/src/utils/parsing.ts +0 -953
  296. package/src/utils/reserved-key-registry.ts +0 -239
  297. package/src/utils/safe-href.ts +0 -38
  298. package/src/utils/scaling.ts +0 -97
  299. package/src/utils/svg-embed.ts +0 -251
  300. package/src/utils/tag-groups.ts +0 -607
  301. package/src/utils/text-measure.ts +0 -122
  302. package/src/utils/time-ticks.ts +0 -253
  303. package/src/utils/title-constants.ts +0 -24
  304. package/src/utils/visual-conventions.ts +0 -61
  305. package/src/utils/wrapped-desc.ts +0 -87
  306. package/src/venn/parser.ts +0 -18
  307. package/src/venn/renderer.ts +0 -1047
  308. package/src/version-control/diagnostics.ts +0 -67
  309. package/src/version-control/parser.ts +0 -544
  310. package/src/version-control/renderer.ts +0 -724
  311. package/src/version-control/types.ts +0 -100
  312. package/src/visualizations/parse.ts +0 -1560
  313. package/src/visualizations/types.ts +0 -262
  314. package/src/wireframe/layout.ts +0 -479
  315. package/src/wireframe/parser.ts +0 -1114
  316. package/src/wireframe/renderer.ts +0 -1318
  317. package/src/wireframe/types.ts +0 -110
  318. package/src/wordcloud/parser.ts +0 -18
  319. package/src/wordcloud/renderer.ts +0 -357
@@ -1,953 +0,0 @@
1
- /**
2
- * Shared parser utilities — extracted from individual parsers to eliminate
3
- * duplication of measureIndent, extractColor, header regexes, and
4
- * pipe-metadata parsing.
5
- */
6
-
7
- import {
8
- RECOGNIZED_COLOR_NAMES,
9
- resolveColor,
10
- resolveColorWithDiagnostic,
11
- invalidColorDiagnostic,
12
- } from '../colors';
13
- import {
14
- emptyMetadataValueMessage,
15
- makeDgmoError,
16
- METADATA_DIAGNOSTIC_CODES,
17
- suggest,
18
- type DgmoError,
19
- } from '../diagnostics';
20
- import type { PaletteColors } from '../palettes';
21
- import {
22
- isReservedKey,
23
- type ReservedKeyRegistry,
24
- } from './reserved-key-registry';
25
-
26
- const RECOGNIZED_COLOR_SET: ReadonlySet<string> = new Set(
27
- RECOGNIZED_COLOR_NAMES
28
- );
29
-
30
- // ── All known chart types ────────────────────────────────────
31
- /** Complete set of recognized chart type identifiers. */
32
- export const ALL_CHART_TYPES = new Set([
33
- // data charts
34
- 'bar',
35
- 'line',
36
- 'pie',
37
- 'polar-area',
38
- 'radar',
39
- 'scatter',
40
- 'sankey',
41
- 'function',
42
- 'heatmap',
43
- 'funnel',
44
- // visualizations
45
- 'slope',
46
- 'wordcloud',
47
- 'arc',
48
- 'timeline',
49
- 'event-line',
50
- 'venn',
51
- 'quadrant',
52
- // diagrams
53
- 'sequence',
54
- 'flowchart',
55
- 'class',
56
- 'er',
57
- 'org',
58
- 'kanban',
59
- 'c4',
60
- 'state',
61
- 'sitemap',
62
- 'infra',
63
- 'gantt',
64
- 'pert',
65
- 'boxes-and-lines',
66
- 'swimlane',
67
- 'version-control',
68
- 'mindmap',
69
- 'wireframe',
70
- 'tech-radar',
71
- 'cycle',
72
- 'journey-map',
73
- 'pyramid',
74
- 'ring',
75
- 'treemap',
76
- 'block',
77
- 'raci',
78
- 'map',
79
- ]);
80
-
81
- /** Measure leading whitespace of a line, normalizing tabs to 4 spaces. */
82
- export function measureIndent(line: string): number {
83
- let indent = 0;
84
- for (const ch of line) {
85
- if (ch === ' ') indent++;
86
- else if (ch === '\t') indent += 4;
87
- else break;
88
- }
89
- return indent;
90
- }
91
-
92
- /**
93
- * Trailing-token color rule (see docs/dgmo-language-spec.md §1.5).
94
- *
95
- * Caller contract: `label` must be a pre-split LABEL REGION — the parser is
96
- * responsible for stripping structural terminators (`as <alias>`, `| pipe
97
- * metadata`, numeric values, date ranges, brackets, arrow constructs) BEFORE
98
- * invoking this function. The color rule operates only on what remains.
99
- *
100
- * Algorithm: split the label on whitespace; if the final token is exactly one
101
- * of `RECOGNIZED_COLOR_NAMES` (case-sensitive, lowercase only), peel it off
102
- * as color and return the rest as the label. Otherwise the entire input
103
- * stays as the label, no color.
104
- *
105
- * Case-sensitivity is deliberate: it provides the escape hatch (`Red`,
106
- * `Yellow`, `Green` stay as labels — useful for traffic-light tag groups).
107
- *
108
- * Returns `{ label, color? }` where `color` is the palette-resolved hex string
109
- * (or undefined if no color word matched).
110
- */
111
- export function extractColor(
112
- label: string,
113
- palette?: PaletteColors,
114
- diagnostics?: DgmoError[],
115
- line?: number
116
- ): { label: string; color?: string } {
117
- const lastSpaceIdx = Math.max(
118
- label.lastIndexOf(' '),
119
- label.lastIndexOf('\t')
120
- );
121
- if (lastSpaceIdx < 0) return { label };
122
- const trailing = label.substring(lastSpaceIdx + 1);
123
- // Case-sensitive lowercase match against the closed 11-name palette.
124
- if (!RECOGNIZED_COLOR_SET.has(trailing)) {
125
- // Not a valid color. If it nonetheless LOOKS like an intended color (a hex
126
- // literal or a CSS color name like `pink`), flag it — otherwise the
127
- // trailing-token rule would silently swallow it into the label with no
128
- // diagnostic, and the MCP color gate would have nothing to block on. A
129
- // genuine label word (`Zinfandel`) is not color-like, so it stays as-is.
130
- if (diagnostics && line !== undefined) {
131
- const diag = invalidColorDiagnostic(trailing, line);
132
- if (diag) diagnostics.push(diag);
133
- }
134
- return { label };
135
- }
136
- let color: string | undefined;
137
- if (diagnostics && line !== undefined) {
138
- color = resolveColorWithDiagnostic(trailing, line, diagnostics, palette);
139
- } else {
140
- color = resolveColor(trailing, palette) ?? undefined;
141
- }
142
- return {
143
- label: label.substring(0, lastSpaceIdx).trimEnd(),
144
- ...(color !== undefined && { color }),
145
- };
146
- }
147
-
148
- /** Matches `option value` header lines (space-separated, no colon). */
149
- export const OPTION_NOCOLON_RE = /^([a-z][a-z0-9-]*)\s+(.+)$/i;
150
-
151
- /**
152
- * Cross-chart-type bare-boolean directives recognized in every chart parser.
153
- * Add new universal flags here so each parser's `tryParseSharedOption()` call
154
- * picks them up uniformly without per-parser changes.
155
- */
156
- export const GLOBAL_BOOLEANS: ReadonlySet<string> = new Set([
157
- 'solid-fill',
158
- 'no-title',
159
- 'no-notes',
160
- ]);
161
-
162
- /**
163
- * If `token` (after trim, case-insensitive) matches a registered cross-cutting
164
- * boolean directive, returns its canonical key. Otherwise returns null.
165
- */
166
- export function recognizeGlobalBoolean(token: string): string | null {
167
- const t = token.trim().toLowerCase();
168
- return GLOBAL_BOOLEANS.has(t) ? t : null;
169
- }
170
-
171
- /**
172
- * Try to parse a line as a cross-chart-type bare-keyword option. Returns true
173
- * if the line matched (and the option was set on `options[key] = 'on'`).
174
- *
175
- * Use inside each parser's option block so the keyword is recognized uniformly
176
- * across all chart types without each parser duplicating the regex.
177
- */
178
- export function tryParseSharedOption(
179
- line: string,
180
- options: Record<string, string>
181
- ): boolean {
182
- const key = recognizeGlobalBoolean(line);
183
- if (key) {
184
- options[key] = 'on';
185
- return true;
186
- }
187
- return false;
188
- }
189
-
190
- // ── New shared utilities ─────────────────────────────────────
191
-
192
- /**
193
- * Parse the first non-empty, non-comment line to extract chart type and optional title.
194
- * The first token is matched against `ALL_CHART_TYPES`; the remainder is the title.
195
- *
196
- * Returns `null` if the first token is not a recognized chart type.
197
- */
198
- export function parseFirstLine(
199
- line: string
200
- ): { chartType: string; title: string | undefined } | null {
201
- const trimmed = line.trim();
202
- if (!trimmed || trimmed.startsWith('//')) return null;
203
-
204
- // First token is chart type, rest is title
205
- const spaceIdx = trimmed.indexOf(' ');
206
- if (spaceIdx === -1) {
207
- const ct = trimmed.toLowerCase();
208
- return ALL_CHART_TYPES.has(ct) ? { chartType: ct, title: undefined } : null;
209
- }
210
- const firstToken = trimmed.substring(0, spaceIdx).toLowerCase();
211
- if (!ALL_CHART_TYPES.has(firstToken)) return null;
212
- return {
213
- chartType: firstToken,
214
- title: trimmed.substring(spaceIdx + 1).trim() || undefined,
215
- };
216
- }
217
-
218
- /** Result of `prescanOptions()` — options collected from a two-pass scan. */
219
- interface PrescanResult {
220
- /** Key-value options, e.g., `direction LR` → `{ direction: 'LR' }` */
221
- options: Record<string, string>;
222
- /** Presence-based boolean options, e.g., `critical-path` → Set('critical-path') */
223
- booleans: Set<string>;
224
- /** Negated booleans, e.g., `no-dependencies` → Set('dependencies') */
225
- negated: Set<string>;
226
- }
227
-
228
- /**
229
- * Pre-scan all lines to collect options that can appear anywhere in the file.
230
- *
231
- * For each non-indented, non-comment line:
232
- * - If the first token is a known option key and the line has more tokens → key-value option
233
- * - If the first token is a known boolean key (bare keyword) → boolean enabled
234
- * - If the first token starts with `no-` and the rest is a known boolean → negated
235
- *
236
- * Comment handling: full comment lines (`// ...`) are skipped. Inline comments
237
- * are stripped before extraction (`direction LR // override` → option `direction: LR`).
238
- *
239
- * @param lines All lines of the document
240
- * @param knownOptions Set of recognized option key names (e.g., `direction`, `start`, `notation`)
241
- * @param knownBooleans Set of recognized boolean option names (e.g., `critical-path`, `animate`)
242
- */
243
- export function prescanOptions(
244
- lines: string[],
245
- knownOptions: Set<string>,
246
- knownBooleans: Set<string> = new Set()
247
- ): PrescanResult {
248
- const options: Record<string, string> = {};
249
- const booleans = new Set<string>();
250
- const negated = new Set<string>();
251
-
252
- for (const raw of lines) {
253
- // Skip indented lines — these are content, not top-level options
254
- if (raw.length > 0 && (raw[0] === ' ' || raw[0] === '\t')) continue;
255
-
256
- const trimmed = raw.trim();
257
- if (!trimmed || trimmed.startsWith('//')) continue;
258
-
259
- // Strip inline comments
260
- const commentIdx = trimmed.indexOf(' //');
261
- const effective =
262
- commentIdx >= 0 ? trimmed.substring(0, commentIdx).trim() : trimmed;
263
- if (!effective) continue;
264
-
265
- // Extract first token
266
- const spaceIdx = effective.indexOf(' ');
267
- const firstToken = (
268
- spaceIdx === -1 ? effective : effective.substring(0, spaceIdx)
269
- ).toLowerCase();
270
-
271
- // Check for bare boolean (presence = on)
272
- if (spaceIdx === -1 && knownBooleans.has(firstToken)) {
273
- booleans.add(firstToken);
274
- continue;
275
- }
276
-
277
- // Check for negated boolean: `no-X` where X is a known boolean
278
- if (spaceIdx === -1 && firstToken.startsWith('no-')) {
279
- const base = firstToken.substring(3);
280
- if (knownBooleans.has(base)) {
281
- negated.add(base);
282
- continue;
283
- }
284
- }
285
-
286
- // Check for boolean with a value (e.g., `today-marker 2026-03-26`) —
287
- // must come before pure key-value check so booleans flag is also set
288
- if (spaceIdx !== -1 && knownBooleans.has(firstToken)) {
289
- booleans.add(firstToken);
290
- options[firstToken] = effective.substring(spaceIdx + 1).trim();
291
- continue;
292
- }
293
-
294
- // Check for key-value option
295
- if (spaceIdx !== -1 && knownOptions.has(firstToken)) {
296
- options[firstToken] = effective.substring(spaceIdx + 1).trim();
297
- continue;
298
- }
299
- }
300
-
301
- return { options, booleans, negated };
302
- }
303
-
304
- /**
305
- * Normalize a numeric token with visual separators (commas or underscores) to a plain number string.
306
- *
307
- * Supported formats:
308
- * - Comma-grouped integers: `1,000` → `'1000'`, `1,234,567` → `'1234567'` (strict 3-digit grouping)
309
- * - Comma-grouped decimals: `1,234.56` → `'1234.56'`
310
- * - Underscore-separated integers: `1_000` → `'1000'`, `10_00_000` → `'1000000'` (any grouping)
311
- * - Underscore-separated decimals: `1_234.56` → `'1234.56'` (no underscores in decimal part)
312
- * - Negatives: `-1,000` → `'-1000'`, `-1_000` → `'-1000'`
313
- *
314
- * Returns `null` if:
315
- * - Token has no commas or underscores (caller should use raw token as-is)
316
- * - Token has BOTH commas and underscores (mixed separators rejected)
317
- * - Token has separators but doesn't match any valid pattern
318
- */
319
- export function normalizeNumericToken(token: string): string | null {
320
- // No separators → null (caller uses raw token)
321
- if (!token.includes(',') && !token.includes('_')) return null;
322
- // Mixed separators → rejected
323
- if (token.includes(',') && token.includes('_')) return null;
324
-
325
- // Strip optional leading minus sign
326
- let sign = '';
327
- let unsigned = token;
328
- if (unsigned.startsWith('-')) {
329
- sign = '-';
330
- unsigned = unsigned.substring(1);
331
- }
332
- if (!unsigned) return null;
333
-
334
- if (unsigned.includes(',')) {
335
- // Comma-grouped integers: 1,000 or 1,234,567
336
- if (/^\d{1,3}(,\d{3})+$/.test(unsigned))
337
- return sign + unsigned.replace(/,/g, '');
338
- // Comma-grouped decimals: 1,234.56
339
- if (/^\d{1,3}(,\d{3})+\.\d+$/.test(unsigned))
340
- return sign + unsigned.replace(/,/g, '');
341
- return null;
342
- }
343
-
344
- // Underscore-separated integers: 1_000, 10_00_000
345
- if (/^\d+(_\d+)+$/.test(unsigned)) return sign + unsigned.replace(/_/g, '');
346
- // Underscore-separated decimals: 1_234.56 (no underscores in decimal part)
347
- if (/^\d+(_\d+)*\.\d+$/.test(unsigned) && unsigned.includes('_'))
348
- return sign + unsigned.replace(/_/g, '');
349
- return null;
350
- }
351
-
352
- /**
353
- * Strip surrounding quotes (`"` or `'`) from a token.
354
- * Returns the unquoted content, or the original string if not quoted.
355
- */
356
- export function stripQuotes(token: string): string {
357
- if (token.length >= 2) {
358
- if (
359
- (token[0] === '"' && token[token.length - 1] === '"') ||
360
- (token[0] === "'" && token[token.length - 1] === "'")
361
- ) {
362
- return token.substring(1, token.length - 1);
363
- }
364
- }
365
- return token;
366
- }
367
-
368
- /**
369
- * Quote-aware tokenizer — splits a string by whitespace but keeps quoted
370
- * substrings (`"double"` or `'single'`) as single tokens.
371
- * Quotes are preserved in the output tokens — call `stripQuotes()` to remove them.
372
- */
373
- export function tokenizeQuoteAware(input: string): string[] {
374
- const tokens: string[] = [];
375
- let i = 0;
376
- while (i < input.length) {
377
- // Skip whitespace
378
- if (input[i] === ' ' || input[i] === '\t') {
379
- i++;
380
- continue;
381
- }
382
-
383
- // Quoted token
384
- if (input[i] === '"' || input[i] === "'") {
385
- const quote = input[i];
386
- const start = i;
387
- i++; // skip opening quote
388
- while (i < input.length && input[i] !== quote) i++;
389
- if (i < input.length) i++; // skip closing quote
390
- tokens.push(input.substring(start, i));
391
- continue;
392
- }
393
-
394
- // Unquoted token
395
- const start = i;
396
- while (i < input.length && input[i] !== ' ' && input[i] !== '\t') i++;
397
- tokens.push(input.substring(start, i));
398
- }
399
- return tokens;
400
- }
401
-
402
- /**
403
- * Collect indented continuation lines as individual values.
404
- * Used when a property like `series:` has an empty value — subsequent
405
- * indented lines each become one value entry.
406
- *
407
- * - Skips blank lines and `//` comment lines within the block
408
- * - Stops at first non-indented non-empty line (or EOF)
409
- * - Strips trailing commas from values (user habit tolerance)
410
- * - Returns `newIndex` so caller does `i = newIndex` and the loop's `i++` lands correctly
411
- */
412
- export function collectIndentedValues(
413
- lines: string[],
414
- startIndex: number
415
- ): { values: string[]; lineNumbers: number[]; newIndex: number } {
416
- const values: string[] = [];
417
- const lineNumbers: number[] = [];
418
- let j = startIndex + 1;
419
- for (; j < lines.length; j++) {
420
- // In-bounds by loop guard.
421
- const raw = lines[j]!;
422
- const trimmed = raw.trim();
423
- // Skip blank lines within the block
424
- if (!trimmed) continue;
425
- // Skip comment lines within the block
426
- if (trimmed.startsWith('//')) continue;
427
- // Stop at non-indented lines (first char is not whitespace)
428
- if (raw[0] !== ' ' && raw[0] !== '\t') break;
429
- // Strip trailing comma and collect
430
- values.push(trimmed.replace(/,\s*$/, ''));
431
- lineNumbers.push(j + 1); // 1-based
432
- }
433
- return { values, lineNumbers, newIndex: j - 1 };
434
- }
435
-
436
- /**
437
- * Parse series names from a `series:` value or indented block, extracting
438
- * optional per-name color suffixes. Shared between chart.ts and echarts.ts.
439
- *
440
- * Returns the parsed names, optional colors, and the raw series string
441
- * (for single-series display), plus `newIndex` if indented values were consumed.
442
- */
443
- export function parseSeriesNames(
444
- value: string,
445
- lines: string[],
446
- lineIndex: number,
447
- palette?: PaletteColors,
448
- diagnostics?: DgmoError[]
449
- ): {
450
- series: string;
451
- names: string[];
452
- nameColors: (string | undefined)[];
453
- nameLineNumbers: number[];
454
- newIndex: number;
455
- /** Per-name axis assignment — present only for the grouped (dual-axis) form. */
456
- axes?: ('left' | 'right')[];
457
- /** Left/right axis labels carried by the grouped form's headers. */
458
- leftLabel?: string;
459
- rightLabel?: string;
460
- } {
461
- let rawNames: string[];
462
- let series: string;
463
- let newIndex = lineIndex;
464
- let nameLineNumbers: number[] = []; // eslint-disable-line no-useless-assignment
465
- if (value) {
466
- series = value;
467
- rawNames = value
468
- .split(',')
469
- .map((s) => s.trim())
470
- .filter(Boolean);
471
- // Inline series names all share the same line number
472
- nameLineNumbers = rawNames.map(() => lineIndex + 1);
473
- } else {
474
- const collected = collectIndentedValues(lines, lineIndex);
475
- newIndex = collected.newIndex;
476
- rawNames = collected.values;
477
- nameLineNumbers = collected.lineNumbers;
478
- series = rawNames.join(', ');
479
- }
480
-
481
- // Grouped (dual-axis) form: the indented block contains `y-label` /
482
- // `y-right-label` header lines that partition the series across two y-axes
483
- // (§15.1). Detected by the presence of any header line. Order is preserved:
484
- // series accumulate under the most recent header (default left).
485
- const isHeader = (s: string): 'left' | 'right' | null => {
486
- const tok = s.split(/\s+/, 1)[0];
487
- if (tok === 'y-label') return 'left';
488
- if (tok === 'y-right-label') return 'right';
489
- return null;
490
- };
491
- if (rawNames.some((r) => isHeader(r) !== null)) {
492
- const names: string[] = [];
493
- const nameColors: (string | undefined)[] = [];
494
- const axes: ('left' | 'right')[] = [];
495
- const memberLineNumbers: number[] = [];
496
- let leftLabel: string | undefined;
497
- let rightLabel: string | undefined;
498
- let currentAxis: 'left' | 'right' = 'left';
499
- for (let i = 0; i < rawNames.length; i++) {
500
- const raw = rawNames[i]!;
501
- const side = isHeader(raw);
502
- if (side !== null) {
503
- const label = raw.slice(raw.indexOf(' ') + 1).trim();
504
- currentAxis = side;
505
- if (side === 'left') leftLabel = label || leftLabel;
506
- else rightLabel = label || rightLabel;
507
- continue;
508
- }
509
- const extracted = extractColor(
510
- raw,
511
- palette,
512
- diagnostics,
513
- nameLineNumbers[i]!
514
- );
515
- names.push(extracted.label);
516
- nameColors.push(extracted.color);
517
- axes.push(currentAxis);
518
- memberLineNumbers.push(nameLineNumbers[i]!);
519
- }
520
- return {
521
- series: names.join(', '),
522
- names,
523
- nameColors,
524
- nameLineNumbers: memberLineNumbers,
525
- newIndex,
526
- axes,
527
- ...(leftLabel !== undefined && { leftLabel }),
528
- ...(rightLabel !== undefined && { rightLabel }),
529
- };
530
- }
531
-
532
- const names: string[] = [];
533
- const nameColors: (string | undefined)[] = [];
534
- for (let i = 0; i < rawNames.length; i++) {
535
- // Loop bound guarantees both are defined; nameLineNumbers is built
536
- // 1:1 with rawNames in both upstream branches.
537
- const raw = rawNames[i]!;
538
- const extracted = extractColor(
539
- raw,
540
- palette,
541
- diagnostics,
542
- nameLineNumbers[i]!
543
- );
544
- nameColors.push(extracted.color);
545
- names.push(extracted.label);
546
- }
547
- if (names.length === 1) {
548
- series = names[0]!;
549
- }
550
- return { series, names, nameColors, nameLineNumbers, newIndex };
551
- }
552
-
553
- /**
554
- * Peel a trailing recognized color name from a label region, returning the
555
- * raw color name (not a resolved hex). Used by chart types that pair the
556
- * universal trailing-token shortcut with their own pipe-metadata `color: …`
557
- * long form (cycle, pyramid, ring, raci, boxes-and-lines).
558
- *
559
- * Caller contract: `label` must already have pipe metadata stripped — this
560
- * function operates only on the label region.
561
- *
562
- * Returns `{ label, colorName? }`. If the trailing token is not a recognized
563
- * lowercase color, returns the original label and `colorName: undefined`.
564
- */
565
- export function peelTrailingColorName(label: string): {
566
- label: string;
567
- colorName?: string;
568
- } {
569
- const lastSpaceIdx = Math.max(
570
- label.lastIndexOf(' '),
571
- label.lastIndexOf('\t')
572
- );
573
- if (lastSpaceIdx < 0) return { label };
574
- const trailing = label.substring(lastSpaceIdx + 1);
575
- if (!RECOGNIZED_COLOR_SET.has(trailing)) return { label };
576
- return {
577
- label: label.substring(0, lastSpaceIdx).trimEnd(),
578
- colorName: trailing,
579
- };
580
- }
581
-
582
- /**
583
- * Peel up to TWO trailing recognized color names from a label region — the
584
- * shared value-ramp coloring convention (`<metric> <low?> <high?>`). Peels from
585
- * the right, stops at the first non-color token, peels AT MOST 2, and NEVER
586
- * reduces the label to empty (a 2nd peel that would empty the label is left as
587
- * label text).
588
- *
589
- * Mapping (locked): one peeled color ⇒ `{ high }` only (today's neutral→hue
590
- * meaning); two peeled ⇒ first(left) = `low`, second(right) = `high`.
591
- * Order-respecting — NO sorting, NO "did-you-mean" intent detection.
592
- *
593
- * Shared by any value-ramp chart type (map `region-heat`, b&l `heat`,
594
- * and future ramps). `peelTrailingColorName` (single-token) stays untouched for
595
- * the non-ramp callers (d3, sitemap, cycle, …).
596
- */
597
- export function peelRampColors(label: string): {
598
- label: string;
599
- low?: string;
600
- high?: string;
601
- } {
602
- // Peel a single trailing recognized color, but only if a token remains in
603
- // front of it (a lone token is never peeled — that would empty the label).
604
- const peelOne = (s: string): { rest: string; color?: string } => {
605
- const idx = Math.max(s.lastIndexOf(' '), s.lastIndexOf('\t'));
606
- if (idx < 0) return { rest: s };
607
- const trailing = s.substring(idx + 1);
608
- if (!RECOGNIZED_COLOR_SET.has(trailing)) return { rest: s };
609
- return { rest: s.substring(0, idx).trimEnd(), color: trailing };
610
- };
611
- // High (rightmost) first.
612
- const first = peelOne(label);
613
- if (first.color === undefined) return { label };
614
- // Low (second-from-right) — only if a non-empty label still remains after.
615
- const second = peelOne(first.rest);
616
- if (second.color === undefined) {
617
- return { label: first.rest, high: first.color };
618
- }
619
- return { label: second.rest, low: second.color, high: first.color };
620
- }
621
-
622
- // ============================================================
623
- // Unified Metadata Grammar (§1.4) — splitNameAndMeta
624
- // ============================================================
625
- //
626
- // Same-line metadata split for the unified §1.4 grammar.
627
- //
628
- // Cut order on the input line (per §1.5):
629
- // 1. Locate the first reserved-key `<key>:` token (anchors the
630
- // name region / metadata region boundary).
631
- // 2. Strip `as <alias>` postfix from the right side of the name
632
- // region.
633
- // 3. Apply §1.5 trailing-token color to whatever remains of the
634
- // name region.
635
- //
636
- // Quoted name tokens (`"Auth: Service"`) are tokenized as one unit
637
- // BEFORE the first-`:`-token scan — colons inside quoted strings do
638
- // not trigger the metadata cut.
639
- //
640
- // Quoted metadata values (`description: "with, commas"`) escape the
641
- // comma terminator within the metadata region.
642
-
643
- export interface SplitNameAndMetaResult {
644
- /** Name region with color and `as <alias>` postfix stripped. */
645
- name: string;
646
- /** Parsed metadata key/value pairs (alias-resolved per the registry). */
647
- meta: Record<string, string>;
648
- /**
649
- * Trailing-token color name from the name region, if any
650
- * (raw color word like "blue" — NOT a resolved hex string).
651
- * Callers wanting hex should pass the result through `resolveColor()`.
652
- */
653
- color?: string;
654
- /** Alias declared via `as <alias>` postfix, if any. */
655
- alias?: string;
656
- }
657
-
658
- const RESERVED_KEY_RE = /^[A-Za-z][A-Za-z0-9_-]*$/;
659
- const AS_ALIAS_RE = /\s+as\s+([A-Za-z][A-Za-z0-9_]{0,11})$/;
660
-
661
- /**
662
- * Tokenize a line for the §1.4 metadata-cut scan:
663
- * preserves quoted strings (`"..."` / `'...'`) as single tokens and
664
- * tracks the byte offset of each token's start in the original line
665
- * so callers can recover the exact name-region substring.
666
- */
667
- interface ScanToken {
668
- /** Token text (with surrounding quotes preserved for quoted tokens). */
669
- readonly text: string;
670
- /** Start offset in the original line. */
671
- readonly start: number;
672
- /** End offset (exclusive) in the original line. */
673
- readonly end: number;
674
- /** True if this token was quoted (`"..."` / `'...'`). */
675
- readonly quoted: boolean;
676
- }
677
-
678
- function scanTokens(line: string): ScanToken[] {
679
- const tokens: ScanToken[] = [];
680
- let i = 0;
681
- while (i < line.length) {
682
- // Skip whitespace
683
- if (line[i] === ' ' || line[i] === '\t') {
684
- i++;
685
- continue;
686
- }
687
- if (line[i] === '"' || line[i] === "'") {
688
- const quote = line[i];
689
- const start = i;
690
- i++; // skip opening quote
691
- while (i < line.length && line[i] !== quote) i++;
692
- if (i < line.length) i++; // skip closing quote
693
- tokens.push({
694
- text: line.substring(start, i),
695
- start,
696
- end: i,
697
- quoted: true,
698
- });
699
- continue;
700
- }
701
- const start = i;
702
- while (i < line.length && line[i] !== ' ' && line[i] !== '\t') i++;
703
- tokens.push({
704
- text: line.substring(start, i),
705
- start,
706
- end: i,
707
- quoted: false,
708
- });
709
- }
710
- return tokens;
711
- }
712
-
713
- /**
714
- * Locate the first colon-bearing position whose preceding identifier
715
- * matches a reserved key, tolerating whitespace around `:` (per spec
716
- * §1.4.1). Returns the byte offset in the original line where the
717
- * name region ends (i.e. start of the key token), or `-1` if no
718
- * metadata cut applies.
719
- *
720
- * Quoted-token contents (a `:` inside `"..."`) never trigger the cut.
721
- */
722
- function findMetadataCutOffset(
723
- line: string,
724
- tokens: ScanToken[],
725
- registry: ReservedKeyRegistry
726
- ): number {
727
- for (let i = 0; i < tokens.length; i++) {
728
- const tok = tokens[i]!;
729
- if (tok.quoted) continue;
730
- const inlineColon = tok.text.indexOf(':');
731
-
732
- if (inlineColon > 0) {
733
- // Shape `<key>:[...]` inside this token (no whitespace before `:`).
734
- const keyPart = tok.text.substring(0, inlineColon);
735
- if (
736
- RESERVED_KEY_RE.test(keyPart) &&
737
- isReservedKey(registry, keyPart.toLowerCase())
738
- ) {
739
- return tok.start;
740
- }
741
- } else if (inlineColon < 0) {
742
- // Token has no colon — check whether (a) the whole token is a
743
- // reserved key and (b) the next non-empty content begins with `:`.
744
- if (
745
- RESERVED_KEY_RE.test(tok.text) &&
746
- isReservedKey(registry, tok.text.toLowerCase())
747
- ) {
748
- const tail = line.substring(tok.end).replace(/^[ \t]+/, '');
749
- if (tail.startsWith(':')) {
750
- return tok.start;
751
- }
752
- }
753
- }
754
- // `inlineColon === 0` — token starts with `:`, e.g. `:Bar` after
755
- // a bare key. Skip; the bare-key path above (one iteration earlier)
756
- // already considered the preceding token.
757
- }
758
- return -1;
759
- }
760
-
761
- /**
762
- * Parse the metadata region (substring starting at the metadata cut
763
- * token through end-of-line) into a key/value record. Handles
764
- * quoted values (`"with, commas"`) for comma escape, whitespace
765
- * tolerance around `:`, empty-value diagnostics, and tag-alias
766
- * resolution via the supplied aliasMap (callers responsible for
767
- * converting `tag Concern as c` declarations into `c → concern`).
768
- */
769
- function parseMetadataRegion(
770
- region: string,
771
- aliasMap: Map<string, string>,
772
- diagnostics?: DgmoError[],
773
- line?: number
774
- ): Record<string, string> {
775
- const meta: Record<string, string> = {};
776
- let i = 0;
777
- while (i < region.length) {
778
- // Skip leading whitespace + commas (commas separate pairs)
779
- while (
780
- i < region.length &&
781
- (region[i] === ' ' || region[i] === '\t' || region[i] === ',')
782
- )
783
- i++;
784
- if (i >= region.length) break;
785
- // Read key
786
- const keyStart = i;
787
- while (i < region.length && region[i] !== ':' && region[i] !== ',') i++;
788
- if (i >= region.length || region[i] !== ':') break;
789
- const rawKey = region.substring(keyStart, i).trim().toLowerCase();
790
- if (!rawKey) break;
791
- i++; // skip ':'
792
- // Skip whitespace after colon
793
- while (i < region.length && (region[i] === ' ' || region[i] === '\t')) i++;
794
- // Read value — quoted (everything up to closing quote) or
795
- // unquoted (everything up to next unquoted comma).
796
- let value: string;
797
- if (i < region.length && (region[i] === '"' || region[i] === "'")) {
798
- const quote = region[i];
799
- i++; // skip opening quote
800
- const vStart = i;
801
- while (i < region.length && region[i] !== quote) i++;
802
- value = region.substring(vStart, i);
803
- if (i < region.length) i++; // skip closing quote
804
- // Skip trailing whitespace; next iteration handles comma.
805
- while (i < region.length && (region[i] === ' ' || region[i] === '\t'))
806
- i++;
807
- } else {
808
- const vStart = i;
809
- while (i < region.length && region[i] !== ',') i++;
810
- value = region.substring(vStart, i).trim();
811
- }
812
- const key = aliasMap.get(rawKey) ?? rawKey;
813
- if (!value) {
814
- if (diagnostics && line !== undefined) {
815
- diagnostics.push(
816
- makeDgmoError(
817
- line,
818
- emptyMetadataValueMessage(rawKey),
819
- 'warning',
820
- METADATA_DIAGNOSTIC_CODES.EMPTY_METADATA_VALUE
821
- )
822
- );
823
- }
824
- // Drop the empty-value pair per §1.4.1.
825
- continue;
826
- }
827
- meta[key] = value;
828
- }
829
- return meta;
830
- }
831
-
832
- /**
833
- * Split a single line into name region + metadata per the unified
834
- * §1.4 metadata grammar.
835
- *
836
- * Applies the §1.5 cut order: metadata-cut first, then `as <alias>`
837
- * postfix strip, then trailing-token color on what remains of the
838
- * name region.
839
- *
840
- * @param line The source line (already trimmed of leading indent).
841
- * @param registry Active reserved-key registry for this chart type.
842
- * @param aliasMap Optional tag-alias → canonical-key map (e.g. `c → concern`).
843
- * @param palette Optional palette for color resolution.
844
- * @param diagnostics Optional accumulator for `W_EMPTY_METADATA_VALUE`.
845
- * @param lineNumber 1-based line number for diagnostics.
846
- */
847
- export interface SplitNameAndMetaOptions {
848
- /**
849
- * When `false`, the §1.5 `as <alias>` postfix peel is skipped.
850
- * Set this for parsers whose name region can legitimately contain
851
- * the word "as" followed by a short identifier (e.g. tech-radar's
852
- * `Infrastructure as Code` blip name). Chart types that own an
853
- * alias form via their own keywords (`alias <a>`, `aka <a>`) are
854
- * the typical reason to disable. Default: true.
855
- */
856
- readonly peelAlias?: boolean;
857
- }
858
-
859
- export function splitNameAndMeta(
860
- line: string,
861
- registry: ReservedKeyRegistry,
862
- aliasMap: Map<string, string> = new Map(),
863
- palette?: PaletteColors,
864
- diagnostics?: DgmoError[],
865
- lineNumber?: number,
866
- options: SplitNameAndMetaOptions = {}
867
- ): SplitNameAndMetaResult {
868
- const tokens = scanTokens(line);
869
- const cutOffset = findMetadataCutOffset(line, tokens, registry);
870
-
871
- let nameRegion: string;
872
- let metaRegion: string;
873
-
874
- if (cutOffset === -1) {
875
- nameRegion = line.trim();
876
- metaRegion = '';
877
- } else {
878
- nameRegion = line.substring(0, cutOffset).trimEnd();
879
- metaRegion = line.substring(cutOffset);
880
- }
881
-
882
- // §1.5 cut order on the name region:
883
- // (1) trailing-token color, (2) `as <alias>` postfix.
884
- // Aliases sit *between* the label and the trailing color in source
885
- // order (`<label> as <alias> <color>`), so peeling color first
886
- // exposes the alias at end-of-string for the regex.
887
- // Use the raw-color-name peel (not the hex-resolved one) so the
888
- // returned `color` field matches the storage shape most parsers
889
- // expect — callers wanting hex pass through `resolveColor()`.
890
- const colorResult = peelTrailingColorName(nameRegion);
891
- let postColorName = colorResult.label;
892
-
893
- let alias: string | undefined;
894
- if (options.peelAlias !== false) {
895
- const aliasMatch = postColorName.match(AS_ALIAS_RE);
896
- if (aliasMatch) {
897
- alias = aliasMatch[1];
898
- postColorName = postColorName.substring(0, aliasMatch.index).trimEnd();
899
- }
900
- }
901
-
902
- const meta =
903
- metaRegion.length > 0
904
- ? parseMetadataRegion(metaRegion, aliasMap, diagnostics, lineNumber)
905
- : {};
906
-
907
- // Mark palette/diagnostics as intentionally unused for the
908
- // current peel path (kept on the signature for future hex-mode
909
- // callers); reference them once so eslint no-unused-vars is happy.
910
- void palette;
911
- // Avoid breaking call sites that pass diagnostics — currently we
912
- // only emit W_EMPTY_METADATA_VALUE from inside parseMetadataRegion.
913
- // The lineNumber + palette stay for symmetry with extractColor.
914
-
915
- return {
916
- name: postColorName,
917
- meta,
918
- ...(colorResult.colorName !== undefined && {
919
- color: colorResult.colorName,
920
- }),
921
- ...(alias !== undefined && { alias }),
922
- };
923
- }
924
-
925
- const POTENTIAL_META_RE = /\b([\w-]+)\s*:/;
926
-
927
- export function warnUnknownMetaKeys(
928
- meta: Record<string, string>,
929
- registry: ReservedKeyRegistry,
930
- warn: (message: string) => void,
931
- nameToScan?: string
932
- ): void {
933
- const candidates = Array.from(registry.keys);
934
-
935
- for (const key of Object.keys(meta)) {
936
- if (isReservedKey(registry, key)) continue;
937
- const hint = suggest(key, candidates);
938
- warn(`Unknown metadata key "${key}".${hint ? ' ' + hint : ''}`);
939
- }
940
-
941
- if (nameToScan) {
942
- const m = nameToScan.match(POTENTIAL_META_RE);
943
- if (m) {
944
- const key = m[1]!.toLowerCase();
945
- if (!isReservedKey(registry, key)) {
946
- const hint = suggest(key, candidates);
947
- if (hint) {
948
- warn(`Unknown metadata key "${key}". ${hint}`);
949
- }
950
- }
951
- }
952
- }
953
- }