agentic-mermaid 0.1.1 → 0.1.2

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 (336) hide show
  1. package/CHANGELOG.md +144 -4
  2. package/LICENSES/Apache-2.0.txt +202 -0
  3. package/README.md +25 -32
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/dist/agent-core.d.ts +463 -0
  6. package/dist/agent-core.js +397 -0
  7. package/dist/agent.d.ts +73 -1868
  8. package/dist/agent.js +336 -37325
  9. package/dist/agentic-mermaid-mcp.js +7 -38399
  10. package/dist/am.js +33632 -40445
  11. package/dist/chunk-4QECACIA.js +4702 -0
  12. package/dist/chunk-CDPKJ2BQ.js +37 -0
  13. package/dist/chunk-QKDLMOJJ.js +3487 -0
  14. package/dist/chunk-WI35L7IR.js +615 -0
  15. package/dist/chunk-WN3YDOBG.js +149 -0
  16. package/dist/chunk-ZYMMKQ3I.js +62637 -0
  17. package/dist/index-D54dqSdC.d.ts +6777 -0
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +310 -33014
  20. package/dist/mcp-cli-SBQSTJFC.js +17 -0
  21. package/docs/README.md +14 -6
  22. package/docs/schemas/style-spec.schema.json +1221 -30
  23. package/examples/styles/catalog.json +54 -0
  24. package/examples/styles/cloudflare-workers-inspired-prototype.mmd +9 -0
  25. package/examples/styles/cloudflare-workers-inspired-prototype.style.json +110 -0
  26. package/examples/styles/cupertino-prototype.mmd +10 -0
  27. package/examples/styles/cupertino-prototype.style.json +63 -0
  28. package/examples/styles/mid-century-report.style.json +2 -2
  29. package/examples/styles/star-chart-atlas.style.json +2 -1
  30. package/examples/styles/transit-route-map.style.json +2 -2
  31. package/examples/styles/vercel-inspired-prototype.mmd +6 -0
  32. package/examples/styles/vercel-inspired-prototype.style.json +87 -0
  33. package/package.json +68 -43
  34. package/server.json +2 -2
  35. package/skills/agentic-mermaid-diagram-workflow/SKILL.md +17 -36
  36. package/skills/agentic-mermaid-diagram-workflow/references/cli.md +4 -5
  37. package/skills/agentic-mermaid-diagram-workflow/references/code-mode.md +15 -31
  38. package/skills/agentic-mermaid-diagram-workflow/references/sequence.md +10 -14
  39. package/skills/agentic-mermaid-live-editor/SKILL.md +100 -206
  40. package/AGENT_NATIVE.md +0 -607
  41. package/Instructions_for_agents.md +0 -89
  42. package/TODO.md +0 -684
  43. package/assets/hero.png +0 -0
  44. package/dist/index-wjRjbsP-.d.ts +0 -1102
  45. package/docs/agent-api-cookbook.md +0 -308
  46. package/docs/agent-mutation-policy.md +0 -104
  47. package/docs/agent-workflow-examples.md +0 -46
  48. package/docs/api.md +0 -211
  49. package/docs/ascii.md +0 -103
  50. package/docs/assets/improvements/box-start-connector.png +0 -0
  51. package/docs/assets/improvements/comment-dropped-lint.png +0 -0
  52. package/docs/assets/improvements/er-content-loss.png +0 -0
  53. package/docs/assets/improvements/fan-in-trunks.png +0 -0
  54. package/docs/assets/improvements/gantt-family.png +0 -0
  55. package/docs/assets/improvements/gantt-milestone-clamp.png +0 -0
  56. package/docs/assets/improvements/gantt-verify-seam.png +0 -0
  57. package/docs/assets/improvements/subgraph-container-edges.png +0 -0
  58. package/docs/assets/improvements/wrapper-frontmatter.png +0 -0
  59. package/docs/assets/improvements/wrapper-init-directive.png +0 -0
  60. package/docs/assets/improvements/wrapper-leading-comment.png +0 -0
  61. package/docs/assets/style-cookbook/mid-century-report.png +0 -0
  62. package/docs/assets/style-cookbook/star-chart-atlas.png +0 -0
  63. package/docs/assets/style-cookbook/transit-route-map.png +0 -0
  64. package/docs/comparison.md +0 -94
  65. package/docs/config.md +0 -105
  66. package/docs/contributing/adding-diagram-types.md +0 -144
  67. package/docs/contributing/diagram-family-citizenship.matrix.json +0 -2127
  68. package/docs/contributing/diagram-family-citizenship.md +0 -82
  69. package/docs/contributing/harvesting-upstream-tests.md +0 -126
  70. package/docs/contributing/lessons-learned.md +0 -276
  71. package/docs/contributing/releasing.md +0 -82
  72. package/docs/contributing/visual-review-evidence.md +0 -53
  73. package/docs/custom-style-cookbook.md +0 -154
  74. package/docs/design/families/README.md +0 -26
  75. package/docs/design/families/architecture-beta.md +0 -48
  76. package/docs/design/families/flowchart-parser-conformance.md +0 -22
  77. package/docs/design/families/gantt-research.md +0 -137
  78. package/docs/design/families/gantt.md +0 -329
  79. package/docs/design/families/journey-agentic-cards-before.png +0 -0
  80. package/docs/design/families/journey-experience-curve-implementation.png +0 -0
  81. package/docs/design/families/journey-mermaid-classic-implementation.png +0 -0
  82. package/docs/design/families/journey-mermaid-classic-prototype.png +0 -0
  83. package/docs/design/families/journey-mermaid-classic-prototype.svg +0 -163
  84. package/docs/design/families/journey-mermaid-classic-prototype.svg.png +0 -0
  85. package/docs/design/families/journey-migration-parity.md +0 -439
  86. package/docs/design/families/journey-section-overlap-after.png +0 -0
  87. package/docs/design/families/journey-section-overlap-before.png +0 -0
  88. package/docs/design/families/journey-usage-research.md +0 -423
  89. package/docs/design/families/journey.md +0 -153
  90. package/docs/design/families/xychart.md +0 -85
  91. package/docs/design/system/README.md +0 -45
  92. package/docs/design/system/abstraction-audit.md +0 -224
  93. package/docs/design/system/abstraction-recommendations.md +0 -655
  94. package/docs/design/system/architecture.mmd +0 -29
  95. package/docs/design/system/architecture.svg +0 -137
  96. package/docs/design/system/layout-guarantees-and-robustness.md +0 -351
  97. package/docs/design/system/layout-rubric.md +0 -138
  98. package/docs/design/system/route-contracts.md +0 -848
  99. package/docs/design/system/source-preservation-ladder.md +0 -52
  100. package/docs/design/system/styles-rollout.md +0 -216
  101. package/docs/design/system/ugly-layouts.md +0 -119
  102. package/docs/diagram-families.md +0 -193
  103. package/docs/features.md +0 -147
  104. package/docs/fork-differences.md +0 -130
  105. package/docs/getting-started.md +0 -175
  106. package/docs/issue-derived-test-cases.md +0 -156
  107. package/docs/layout-characterization/README.md +0 -245
  108. package/docs/layout-characterization/contact-sheet-families.md +0 -498
  109. package/docs/layout-characterization/contact-sheet.md +0 -638
  110. package/docs/layout-characterization/properties.md +0 -281
  111. package/docs/layout-characterization/visual-quality.md +0 -160
  112. package/docs/layout-characterization/visual-snapshots/architecture.svg +0 -79
  113. package/docs/layout-characterization/visual-snapshots/class.svg +0 -60
  114. package/docs/layout-characterization/visual-snapshots/er.svg +0 -61
  115. package/docs/layout-characterization/visual-snapshots/flowchart.svg +0 -58
  116. package/docs/layout-characterization/visual-snapshots/gantt.svg +0 -52
  117. package/docs/layout-characterization/visual-snapshots/journey.svg +0 -98
  118. package/docs/layout-characterization/visual-snapshots/pie.svg +0 -36
  119. package/docs/layout-characterization/visual-snapshots/quadrant.svg +0 -47
  120. package/docs/layout-characterization/visual-snapshots/sequence.svg +0 -59
  121. package/docs/layout-characterization/visual-snapshots/state.svg +0 -52
  122. package/docs/layout-characterization/visual-snapshots/timeline.svg +0 -64
  123. package/docs/layout-characterization/visual-snapshots/xychart.svg +0 -97
  124. package/docs/mcp-code-mode-rationale.md +0 -101
  125. package/docs/mcp-http-transport.md +0 -223
  126. package/docs/mermaid-layout-complaints.md +0 -837
  127. package/docs/mutation-testing.md +0 -206
  128. package/docs/project/divergences.md +0 -98
  129. package/docs/project/dogfooding-docs-strategy.md +0 -66
  130. package/docs/project/hosted-mcp-cloudflare-plan.md +0 -338
  131. package/docs/project/lessons-learned.md +0 -1019
  132. package/docs/project/remove-role-styling-plan.md +0 -176
  133. package/docs/quality.md +0 -215
  134. package/docs/react.md +0 -97
  135. package/docs/style-authoring.md +0 -133
  136. package/docs/testing-strategy.md +0 -335
  137. package/docs/theming.md +0 -162
  138. package/examples/agent-improve-auth-flow.ts +0 -206
  139. package/examples/agent-loop.ts +0 -53
  140. package/examples/mcp-vs-cli-complex-diagrams.ts +0 -133
  141. package/llms.txt +0 -104
  142. package/skill-evals/README.md +0 -77
  143. package/skill-evals/fixtures/architecture-cache/input.mmd +0 -5
  144. package/skill-evals/fixtures/class-payment/input.mmd +0 -4
  145. package/skill-evals/fixtures/er-orders/input.mmd +0 -10
  146. package/skill-evals/fixtures/flowchart-cache/input.mmd +0 -3
  147. package/skill-evals/fixtures/gantt-release/input.mmd +0 -7
  148. package/skill-evals/fixtures/journey-checkout/input.mmd +0 -6
  149. package/skill-evals/fixtures/pie-exports/input.mmd +0 -5
  150. package/skill-evals/fixtures/quadrant-priorities/input.mmd +0 -11
  151. package/skill-evals/fixtures/sequence-retry/input.mmd +0 -8
  152. package/skill-evals/fixtures/state-lifecycle/input.mmd +0 -5
  153. package/skill-evals/fixtures/timeline-release/input.mmd +0 -6
  154. package/skill-evals/fixtures/xychart-growth/input.mmd +0 -5
  155. package/skill-evals/shared-benchmark.json +0 -510
  156. package/src/agent/analyze.ts +0 -157
  157. package/src/agent/apply.ts +0 -146
  158. package/src/agent/architecture-body.ts +0 -458
  159. package/src/agent/certificates.ts +0 -110
  160. package/src/agent/class-body.ts +0 -319
  161. package/src/agent/core.ts +0 -207
  162. package/src/agent/create.ts +0 -106
  163. package/src/agent/describe.ts +0 -368
  164. package/src/agent/er-body.ts +0 -224
  165. package/src/agent/facts.ts +0 -360
  166. package/src/agent/families-builtin.ts +0 -920
  167. package/src/agent/families.ts +0 -232
  168. package/src/agent/family-layouts.ts +0 -832
  169. package/src/agent/flowchart-body.ts +0 -372
  170. package/src/agent/flowchart-unsupported.ts +0 -243
  171. package/src/agent/font-coverage.ts +0 -288
  172. package/src/agent/gantt-body.ts +0 -495
  173. package/src/agent/index.ts +0 -10
  174. package/src/agent/journey-body.ts +0 -374
  175. package/src/agent/label-metrics.ts +0 -28
  176. package/src/agent/layout-to-rendered.ts +0 -63
  177. package/src/agent/mutate.ts +0 -97
  178. package/src/agent/mutation-ops.ts +0 -51
  179. package/src/agent/op-schema.ts +0 -443
  180. package/src/agent/parse.ts +0 -223
  181. package/src/agent/pie-body.ts +0 -270
  182. package/src/agent/png.ts +0 -171
  183. package/src/agent/quadrant-body.ts +0 -336
  184. package/src/agent/quality.ts +0 -363
  185. package/src/agent/readability-audit.ts +0 -92
  186. package/src/agent/rendered-route-audit.ts +0 -61
  187. package/src/agent/sequence-body.ts +0 -345
  188. package/src/agent/serialize.ts +0 -214
  189. package/src/agent/state-body.ts +0 -589
  190. package/src/agent/structural-count.ts +0 -150
  191. package/src/agent/timeline-body.ts +0 -280
  192. package/src/agent/trace-log.ts +0 -43
  193. package/src/agent/types.ts +0 -995
  194. package/src/agent/verify.ts +0 -603
  195. package/src/agent/xychart-body.ts +0 -472
  196. package/src/architecture/config.ts +0 -282
  197. package/src/architecture/layout.ts +0 -496
  198. package/src/architecture/parser.ts +0 -375
  199. package/src/architecture/renderer.ts +0 -611
  200. package/src/architecture/types.ts +0 -113
  201. package/src/ascii/ansi.ts +0 -423
  202. package/src/ascii/architecture.ts +0 -210
  203. package/src/ascii/canvas.ts +0 -443
  204. package/src/ascii/class-diagram.ts +0 -697
  205. package/src/ascii/converter.ts +0 -475
  206. package/src/ascii/draw.ts +0 -1693
  207. package/src/ascii/edge-bundling.ts +0 -328
  208. package/src/ascii/edge-routing.ts +0 -330
  209. package/src/ascii/er-diagram.ts +0 -439
  210. package/src/ascii/gantt.ts +0 -276
  211. package/src/ascii/grid.ts +0 -747
  212. package/src/ascii/index.ts +0 -196
  213. package/src/ascii/journey.ts +0 -169
  214. package/src/ascii/meta.ts +0 -244
  215. package/src/ascii/multiline-utils.ts +0 -80
  216. package/src/ascii/pathfinder.ts +0 -301
  217. package/src/ascii/pie.ts +0 -67
  218. package/src/ascii/quadrant.ts +0 -158
  219. package/src/ascii/reverse.ts +0 -216
  220. package/src/ascii/sequence.ts +0 -499
  221. package/src/ascii/shapes/circle.ts +0 -27
  222. package/src/ascii/shapes/corners.ts +0 -143
  223. package/src/ascii/shapes/diamond.ts +0 -27
  224. package/src/ascii/shapes/hexagon.ts +0 -27
  225. package/src/ascii/shapes/index.ts +0 -106
  226. package/src/ascii/shapes/rectangle.ts +0 -168
  227. package/src/ascii/shapes/rounded.ts +0 -27
  228. package/src/ascii/shapes/special.ts +0 -332
  229. package/src/ascii/shapes/stadium.ts +0 -110
  230. package/src/ascii/shapes/state.ts +0 -192
  231. package/src/ascii/shapes/types.ts +0 -73
  232. package/src/ascii/timeline.ts +0 -141
  233. package/src/ascii/types.ts +0 -312
  234. package/src/ascii/validate.ts +0 -120
  235. package/src/ascii/width.ts +0 -81
  236. package/src/ascii/wrap.ts +0 -131
  237. package/src/ascii/xychart.ts +0 -919
  238. package/src/browser.ts +0 -29
  239. package/src/class/layout.ts +0 -240
  240. package/src/class/parser.ts +0 -332
  241. package/src/class/renderer.ts +0 -638
  242. package/src/class/types.ts +0 -129
  243. package/src/cli/agent-instructions.ts +0 -1
  244. package/src/cli/am-bin.ts +0 -6
  245. package/src/cli/exit-codes.ts +0 -18
  246. package/src/cli/index.ts +0 -1132
  247. package/src/cli/init-agent.ts +0 -147
  248. package/src/cli/run-entrypoint.ts +0 -10
  249. package/src/color-resolver.ts +0 -152
  250. package/src/elk-instance.ts +0 -114
  251. package/src/er/layout.ts +0 -187
  252. package/src/er/parser.ts +0 -226
  253. package/src/er/renderer.ts +0 -792
  254. package/src/er/types.ts +0 -99
  255. package/src/family-rubric.ts +0 -425
  256. package/src/font-manifest.ts +0 -31
  257. package/src/gantt/layout.ts +0 -365
  258. package/src/gantt/parser.ts +0 -282
  259. package/src/gantt/pipeline.ts +0 -27
  260. package/src/gantt/renderer.ts +0 -414
  261. package/src/gantt/schedule.ts +0 -513
  262. package/src/gantt/types.ts +0 -255
  263. package/src/index.ts +0 -368
  264. package/src/journey/layout.ts +0 -554
  265. package/src/journey/parse-core.ts +0 -251
  266. package/src/journey/parser.ts +0 -101
  267. package/src/journey/renderer.ts +0 -917
  268. package/src/journey/types.ts +0 -144
  269. package/src/layout/geometry.ts +0 -182
  270. package/src/layout/pass.ts +0 -142
  271. package/src/layout/passes/index.ts +0 -3916
  272. package/src/layout-engine.ts +0 -1565
  273. package/src/layout-rubric.ts +0 -659
  274. package/src/mcp/artifacts.ts +0 -137
  275. package/src/mcp/dynamic-harness.ts +0 -31
  276. package/src/mcp/dynamic-modules.d.ts +0 -7
  277. package/src/mcp/facade.ts +0 -608
  278. package/src/mcp/harness-runtime.ts +0 -203
  279. package/src/mcp/hosted-server.ts +0 -468
  280. package/src/mcp/mcp-bin.ts +0 -3
  281. package/src/mcp/mcp-cli.ts +0 -82
  282. package/src/mcp/protocol.ts +0 -13
  283. package/src/mcp/sandbox.ts +0 -195
  284. package/src/mcp/sdk-decl.ts +0 -391
  285. package/src/mcp/server.ts +0 -362
  286. package/src/mcp/tool-surface.ts +0 -146
  287. package/src/mermaid-source.ts +0 -655
  288. package/src/multiline-utils.ts +0 -228
  289. package/src/parser.ts +0 -1031
  290. package/src/pie/layout.ts +0 -168
  291. package/src/pie/parser.ts +0 -136
  292. package/src/pie/renderer.ts +0 -234
  293. package/src/pie/types.ts +0 -82
  294. package/src/quadrant/layout.ts +0 -191
  295. package/src/quadrant/parser.ts +0 -183
  296. package/src/quadrant/renderer.ts +0 -322
  297. package/src/quadrant/types.ts +0 -113
  298. package/src/render-family-hooks.ts +0 -244
  299. package/src/renderer.ts +0 -1099
  300. package/src/route-contracts.ts +0 -2723
  301. package/src/scene/backend.ts +0 -76
  302. package/src/scene/fidelity.ts +0 -183
  303. package/src/scene/hybrid-backend.ts +0 -174
  304. package/src/scene/ir.ts +0 -181
  305. package/src/scene/marks.ts +0 -127
  306. package/src/scene/rough-backend.ts +0 -378
  307. package/src/scene/seed.ts +0 -46
  308. package/src/scene/style-registry.ts +0 -556
  309. package/src/sequence/layout.ts +0 -456
  310. package/src/sequence/parser.ts +0 -255
  311. package/src/sequence/renderer.ts +0 -604
  312. package/src/sequence/types.ts +0 -154
  313. package/src/shape-clipping.ts +0 -351
  314. package/src/shared/accessibility-directives.ts +0 -22
  315. package/src/shared/batched.ts +0 -61
  316. package/src/shared/color-math.ts +0 -93
  317. package/src/shared/svg-a11y.ts +0 -29
  318. package/src/shared/syntax-error.ts +0 -17
  319. package/src/shared/unicode-ranges.ts +0 -135
  320. package/src/styles.ts +0 -318
  321. package/src/svg-paths.ts +0 -28
  322. package/src/text-metrics.ts +0 -248
  323. package/src/theme.ts +0 -710
  324. package/src/timeline/layout.ts +0 -381
  325. package/src/timeline/parser.ts +0 -215
  326. package/src/timeline/renderer.ts +0 -538
  327. package/src/timeline/types.ts +0 -105
  328. package/src/types.ts +0 -462
  329. package/src/website-worker-modules.d.ts +0 -18
  330. package/src/xychart/axis-utils.ts +0 -109
  331. package/src/xychart/colors.ts +0 -124
  332. package/src/xychart/config.ts +0 -88
  333. package/src/xychart/layout.ts +0 -656
  334. package/src/xychart/parser.ts +0 -504
  335. package/src/xychart/renderer.ts +0 -640
  336. package/src/xychart/types.ts +0 -282
@@ -1,920 +0,0 @@
1
- // ============================================================================
2
- // Built-in family registrations.
3
- //
4
- // Registers all built-in families with the plugin registry. Structured families own
5
- // their parse/serialize/mutate here (BUILD-3 consolidation): parseMermaid,
6
- // serializeMermaid, and mutate dispatch through these hooks, so adding a
7
- // family means one registration plus a body module — no core edits.
8
- //
9
- // Flowchart registers through `flowchartFamilyHooks('flowchart')` over the
10
- // legacy MermaidGraph body (error semantics, contributes a SourceMap).
11
- //
12
- // State registers through `structuredFamilyHooks('state', …)` over the
13
- // dedicated StateBody IR (BUILD-19): structured-or-opaque parse, state-shaped
14
- // ops, an `asState` narrower, and a verify hook that runs body-level Tier 1
15
- // checks (verify.ts adds the geometric Tier 2 pass via the graph projection).
16
- // ============================================================================
17
-
18
- import { registerFamily, extractLabelsGeneric, type ExtractedLabel, type FamilyPlugin } from './families.ts'
19
- import type { DiagramBody, DiagramKind, AnyMutationOp, MutationError, Result, LayoutWarning, SourceMap, ClassBody, ErBody, XyChartBody, PieBody, QuadrantBody, GanttBody } from './types.ts'
20
- import { ok, err } from './types.ts'
21
- import { verifyClass, parseClassBody, renderClass, mutateClass } from './class-body.ts'
22
- import { verifyErBody, parseErBody, renderEr, mutateEr } from './er-body.ts'
23
- import { parseSequenceBody, renderSequence, mutateSequence } from './sequence-body.ts'
24
- import { parseTimelineBody, renderTimeline, mutateTimeline } from './timeline-body.ts'
25
- import { parseJourneyBody, renderJourney, mutateJourney, verifyJourney } from './journey-body.ts'
26
- import { walkJourneyLines, type JourneyParseIssue } from '../journey/parse-core.ts'
27
- import { parseArchitectureBody, renderArchitecture, mutateArchitecture, verifyArchitecture } from './architecture-body.ts'
28
- import { parseXyChartBody, renderXyChart, mutateXyChart, verifyXyChart } from './xychart-body.ts'
29
- import { parsePieBody, renderPie, mutatePie, verifyPie } from './pie-body.ts'
30
- import { parseQuadrantBody, renderQuadrant, mutateQuadrant, verifyQuadrant } from './quadrant-body.ts'
31
- import { parseStateBody, renderState, mutateState, verifyState } from './state-body.ts'
32
- import { parseGanttBody, renderGantt, mutateGantt, verifyGantt } from './gantt-body.ts'
33
- import { parseFlowchartBody, renderFlowchart, mutateFlowchart, buildFlowchartSourceMap, type FlowchartBody } from './flowchart-body.ts'
34
- import { containsFlowchartOpaqueSyntax } from './flowchart-unsupported.ts'
35
-
36
- // Build the structured-or-opaque hook set shared by every structured family
37
- // that is not flowchart/state. `headerOk` gates structured parsing: families
38
- // with meaningful header suffixes (timeline, journey) stay opaque when the
39
- // header carries one, so the suffix round-trips verbatim.
40
- function structuredFamilyHooks<K extends DiagramBody['kind'] & DiagramKind>(
41
- kind: K,
42
- opts: {
43
- headerOk?: (header: string) => boolean
44
- parseBody: (lines: string[]) => Extract<DiagramBody, { kind: K }> | null
45
- serialize: (body: Extract<DiagramBody, { kind: K }>) => string
46
- mutate: (body: Extract<DiagramBody, { kind: K }>, op: never) => Result<Extract<DiagramBody, { kind: K }>, MutationError>
47
- },
48
- ): Pick<FamilyPlugin, 'parse' | 'serialize' | 'mutate'> {
49
- return {
50
- parse: (lines, opaqueSource) => {
51
- const headerOk = opts.headerOk?.(lines[0]?.trim() ?? '') ?? true
52
- const body = headerOk ? opts.parseBody(lines.slice(1)) : null
53
- return ok(body ?? { kind: 'opaque', family: kind, source: opaqueSource })
54
- },
55
- serialize: body => {
56
- if (body.kind !== kind) throw new Error(`${kind} serializer received body kind ${body.kind}`)
57
- return opts.serialize(body as Extract<DiagramBody, { kind: K }>)
58
- },
59
- mutate: (body: DiagramBody, op: AnyMutationOp) => {
60
- if (body.kind !== kind) return err<MutationError>({ code: 'INVALID_OP', message: `${kind} mutator received body kind ${body.kind}` })
61
- return opts.mutate(body as Extract<DiagramBody, { kind: K }>, op as never)
62
- },
63
- }
64
- }
65
-
66
- // ---- Flowchart ------------------------------------------------------------
67
- // Flowchart-specific label extraction:
68
- // - `A["text"]`, `A(text)`, `A([text])`, `A{text}`, `A{{text}}`, etc.
69
- // - `A -- text --> B`, `A -->|text| B`
70
- const FLOWCHART_LABEL_RE = /(?:\["((?:[^"\\]|\\.)*)"\]|\[(["'`]?)([^\]\n]+?)\2\]|\(\(([^)\n]+?)\)\)|\(([^)\n]+?)\)|\{([^}\n]+?)\}|\|([^|\n]+?)\||\>([^\]\n]+?)\])/g
71
-
72
- function extractFlowchartLabels(source: string): ExtractedLabel[] {
73
- const out: ExtractedLabel[] = []
74
- const lines = source.split(/\r?\n/)
75
- for (let i = 0; i < lines.length; i++) {
76
- const raw = lines[i]!.trim()
77
- if (!raw || raw.startsWith('%%')) continue
78
- const idMatch = raw.match(/^([A-Za-z_][\w-]*)/)
79
- const target = idMatch ? idMatch[1]! : `line${i + 1}`
80
- for (const m of raw.matchAll(FLOWCHART_LABEL_RE)) {
81
- const text = (m[1] ?? m[3] ?? m[4] ?? m[5] ?? m[6] ?? m[7] ?? m[8] ?? '').trim()
82
- if (text) out.push({ text, target })
83
- }
84
- }
85
- return out
86
- }
87
-
88
- // Flowchart owns the legacy MermaidGraph body: the diagram kind selects the
89
- // plugin, which binds the flowchart header.
90
- function flowchartFamilyHooks(): Pick<FamilyPlugin, 'parse' | 'buildSourceMap' | 'serialize' | 'mutate'> {
91
- return {
92
- parse: (_lines, opaqueSource, _meta, canonicalSource) => {
93
- if (containsFlowchartOpaqueSyntax(canonicalSource)) return ok<DiagramBody>({ kind: 'opaque', family: 'flowchart', source: opaqueSource })
94
- return parseFlowchartBody(canonicalSource)
95
- },
96
- buildSourceMap: (body, canonicalSource) =>
97
- body.kind === 'flowchart' ? buildFlowchartSourceMap(body as FlowchartBody, canonicalSource) : { nodes: new Map(), edges: new Map(), groups: new Map(), labels: new Map() },
98
- serialize: body => {
99
- if (body.kind !== 'flowchart') throw new Error(`flowchart serializer received body kind ${body.kind}`)
100
- return renderFlowchart(body.graph, 'flowchart')
101
- },
102
- mutate: (body, op) => {
103
- if (body.kind !== 'flowchart') return err<MutationError>({ code: 'INVALID_OP', message: `flowchart mutator received body kind ${body.kind}` })
104
- return mutateFlowchart(body, op as never)
105
- },
106
- }
107
- }
108
-
109
- registerFamily({
110
- id: 'flowchart',
111
- detect: l => l.startsWith('flowchart') || l.startsWith('graph'),
112
- extractLabels: extractFlowchartLabels,
113
- ...flowchartFamilyHooks(),
114
- })
115
-
116
- // ---- State ----------------------------------------------------------------
117
- // BUILD-19: state owns a dedicated StateBody IR (no longer the flowchart body).
118
- // State label extraction for opaque fallbacks: `state "Label" as id`,
119
- // `id : Description`, and transition labels `from --> to : label`.
120
- function extractStateLabels(source: string): ExtractedLabel[] {
121
- const out: ExtractedLabel[] = []
122
- const lines = source.split(/\r?\n/)
123
- for (let i = 0; i < lines.length; i++) {
124
- const raw = lines[i]!.trim()
125
- if (!raw || raw.startsWith('%%')) continue
126
- const target = `line${i + 1}`
127
- let m
128
- if ((m = raw.match(/^state\s+"([^"]+)"\s+as\s+/i))) {
129
- out.push({ text: m[1]!.trim(), target })
130
- } else if (raw.includes('-->') && raw.includes(':')) {
131
- const colon = raw.indexOf(':')
132
- out.push({ text: raw.slice(colon + 1).trim(), target })
133
- } else if ((m = raw.match(/^[\w\p{L}-]+\s*:\s*(.+)$/u))) {
134
- out.push({ text: m[1]!.trim(), target })
135
- } else if ((m = raw.match(/^note\s+(?:left of|right of)\s+\S+\s*:\s*(.+)$/i))) {
136
- out.push({ text: m[1]!.trim(), target })
137
- }
138
- }
139
- return out
140
- }
141
-
142
- registerFamily({
143
- id: 'state',
144
- detect: l => l.startsWith('statediagram') || l.startsWith('statediagram-v2'),
145
- extractLabels: extractStateLabels,
146
- // The verify hook covers body-level structural Tier 1 (EMPTY/MISANCHORED/
147
- // LABEL_OVERFLOW); verify.ts adds geometric Tier 2 via the graph projection.
148
- verify: (body, opts) => body.kind === 'state' ? verifyState(body, opts) : [],
149
- ...structuredFamilyHooks('state', {
150
- headerOk: h => /^statediagram(?:-v2)?\s*$/i.test(h),
151
- parseBody: parseStateBody, serialize: renderState, mutate: mutateState,
152
- }),
153
- })
154
-
155
- // ---- Sequence -------------------------------------------------------------
156
- // Sequence labels: messages (`A->>B: text`), participants (`participant X as Label`,
157
- // `actor X as Label`), notes (`Note over A: text`, `Note left of A: text`),
158
- // block headers (`loop label`, `alt label`, `else label`, `opt label`, `par label`).
159
- function extractSequenceLabels(source: string): ExtractedLabel[] {
160
- const out: ExtractedLabel[] = []
161
- const lines = source.split(/\r?\n/)
162
- for (let i = 0; i < lines.length; i++) {
163
- const raw = lines[i]!.trim()
164
- if (!raw || raw.startsWith('%%')) continue
165
- let m
166
- if ((m = raw.match(/^(?:participant|actor)\s+\S+\s+as\s+(.+)$/i))) {
167
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
168
- } else if ((m = raw.match(/^Note\s+(?:over|left of|right of)\s+[\w,\s]+?:\s*(.+)$/i))) {
169
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
170
- } else if ((m = raw.match(/->>?|-->>?|->|-->|-x|--x/)) && raw.includes(':')) {
171
- const colon = raw.indexOf(':')
172
- out.push({ text: raw.slice(colon + 1).trim(), target: `line${i + 1}` })
173
- } else if ((m = raw.match(/^(?:loop|alt|else|opt|par|and|critical|break|rect)\s+(.+)$/i))) {
174
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
175
- } else if ((m = raw.match(/^title\s+(.+)$/i))) {
176
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
177
- }
178
- }
179
- return out
180
- }
181
-
182
- // Sequence parse needs the RAW (indentation-preserving) body lines so
183
- // opaque-block segments round-trip verbatim. `opaqueSource` is the normalized
184
- // body INCLUDING the header line, with original indentation/blank lines/
185
- // comments intact — drop its header and pass alongside the trimmed lines.
186
- registerFamily({
187
- id: 'sequence',
188
- detect: l => l.startsWith('sequencediagram'),
189
- extractLabels: extractSequenceLabels,
190
- parse: (lines, opaqueSource) => {
191
- const expandedLines = expandInlineSequenceStatements(lines)
192
- const rawBodyLines = sequenceRawBodyLines(opaqueSource, expandedLines)
193
- const body = parseSequenceBody(expandedLines.slice(1), rawBodyLines)
194
- return ok(body ?? { kind: 'opaque', family: 'sequence', source: opaqueSource })
195
- },
196
- serialize: body => {
197
- if (body.kind !== 'sequence') throw new Error(`sequence serializer received body kind ${body.kind}`)
198
- return renderSequence(body)
199
- },
200
- mutate: (body, op) => {
201
- if (body.kind !== 'sequence') return err<MutationError>({ code: 'INVALID_OP', message: `sequence mutator received body kind ${body.kind}` })
202
- return mutateSequence(body, op as never)
203
- },
204
- })
205
-
206
- function expandInlineSequenceStatements(lines: string[]): string[] {
207
- const header = lines[0]?.trim() ?? ''
208
- if (!/^sequenceDiagram\s*;/i.test(header)) return lines
209
- return [...header.split(';').map(part => part.trim()).filter(Boolean), ...lines.slice(1)]
210
- }
211
-
212
- function sequenceRawBodyLines(opaqueSource: string, expandedLines: string[]): string[] {
213
- const raw = opaqueSource.split(/\r?\n/)
214
- const headerAt = raw.findIndex(l => /^sequenceDiagram\b/i.test(l.trim()))
215
- if (headerAt >= 0 && raw[headerAt]!.includes(';')) return expandedLines.slice(1)
216
- return headerAt >= 0 ? raw.slice(headerAt + 1) : raw.slice(1)
217
- }
218
-
219
- // ---- Timeline -------------------------------------------------------------
220
- function extractTimelineLabels(source: string): ExtractedLabel[] {
221
- const out: ExtractedLabel[] = []
222
- const lines = source.split(/\r?\n/)
223
- for (let i = 0; i < lines.length; i++) {
224
- const raw = lines[i]!.trim()
225
- if (!raw || raw.startsWith('%%')) continue
226
- let m
227
- if ((m = raw.match(/^title\s+(.+)$/i))) {
228
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
229
- } else if ((m = raw.match(/^section\s+(.+)$/i))) {
230
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
231
- } else if (raw.includes(':')) {
232
- // `<period> : <event> [: <event>...]` or continuation `: <event>`
233
- const parts = raw.split(':').map(p => p.trim()).filter(Boolean)
234
- for (const p of parts) out.push({ text: p, target: `line${i + 1}` })
235
- }
236
- }
237
- return out
238
- }
239
-
240
- registerFamily({
241
- id: 'timeline',
242
- detect: l => l.startsWith('timeline'),
243
- extractLabels: extractTimelineLabels,
244
- ...structuredFamilyHooks('timeline', {
245
- headerOk: h => /^timeline\s*$/i.test(h),
246
- parseBody: parseTimelineBody, serialize: renderTimeline, mutate: mutateTimeline,
247
- }),
248
- })
249
-
250
- // ---- Class ---------------------------------------------------------------
251
- // class Name { +member ... }, Class : +member, class A as "Display Label"
252
- function emptySourceMap(): SourceMap { return { nodes: new Map(), edges: new Map(), groups: new Map(), labels: new Map() } }
253
- function loc(line: number, col: number): { line: number; col: number } { return { line, col: Math.max(1, col) } }
254
- function firstIndex(line: string, text: string): number { const i = line.indexOf(text); return i >= 0 ? i + 1 : 1 }
255
-
256
- function buildClassSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
257
- const map = emptySourceMap()
258
- if (body.kind !== 'class') return map
259
- const b = body as ClassBody
260
- const lines = canonicalSource.split(/\r?\n/)
261
- for (const c of b.classes) {
262
- for (let i = 0; i < lines.length; i++) {
263
- const line = lines[i]!
264
- if (new RegExp(`\\b${escapeSourceMapRegex(c.id)}\\b`).test(line)) { map.nodes.set(c.id, loc(i + 1, firstIndex(line, c.id))); break }
265
- }
266
- c.members.forEach((member, index) => {
267
- for (let i = 0; i < lines.length; i++) {
268
- const col = lines[i]!.indexOf(member)
269
- if (col >= 0) { map.labels.set(`class:${c.id}:member#${index}`, loc(i + 1, col + 1)); break }
270
- }
271
- })
272
- }
273
- b.relations.forEach((r, index) => {
274
- for (let i = 0; i < lines.length; i++) {
275
- const line = lines[i]!
276
- if (!line.includes(r.from) || !line.includes(r.to)) continue
277
- const key = `rel#${index}:${r.from}->${r.to}`
278
- map.edges.set(key, loc(i + 1, firstIndex(line, r.from)))
279
- if (r.label) {
280
- const labelCol = line.lastIndexOf(r.label)
281
- if (labelCol >= 0) map.labels.set(key, loc(i + 1, labelCol + 1))
282
- }
283
- if (r.fromCardinality) {
284
- const col = line.indexOf(`"${r.fromCardinality}"`)
285
- if (col >= 0) map.labels.set(`${key}:fromCardinality`, loc(i + 1, col + 2))
286
- }
287
- if (r.toCardinality) {
288
- const col = line.indexOf(`"${r.toCardinality}"`)
289
- if (col >= 0) map.labels.set(`${key}:toCardinality`, loc(i + 1, col + 2))
290
- }
291
- break
292
- }
293
- })
294
- return map
295
- }
296
-
297
- function buildErSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
298
- const map = emptySourceMap()
299
- if (body.kind !== 'er') return map
300
- const b = body as ErBody
301
- const lines = canonicalSource.split(/\r?\n/)
302
- for (const e of b.entities) {
303
- for (let i = 0; i < lines.length; i++) {
304
- const line = lines[i]!
305
- if (new RegExp(`\\b${escapeSourceMapRegex(e.id)}\\b`).test(line)) { map.nodes.set(e.id, loc(i + 1, firstIndex(line, e.id))); break }
306
- }
307
- e.attributes.forEach((attr, index) => {
308
- for (let i = 0; i < lines.length; i++) {
309
- const col = lines[i]!.indexOf(attr.text)
310
- if (col >= 0) { map.labels.set(`er:${e.id}:attr#${index}`, loc(i + 1, col + 1)); break }
311
- }
312
- })
313
- }
314
- b.relations.forEach((r, index) => {
315
- for (let i = 0; i < lines.length; i++) {
316
- const line = lines[i]!
317
- if (!line.includes(r.from) || !line.includes(r.to)) continue
318
- const key = `rel#${index}:${r.from}->${r.to}`
319
- map.edges.set(key, loc(i + 1, firstIndex(line, r.from)))
320
- if (r.label) {
321
- const labelCol = line.lastIndexOf(r.label)
322
- if (labelCol >= 0) map.labels.set(key, loc(i + 1, labelCol + 1))
323
- }
324
- const between = line.slice(line.indexOf(r.from) + r.from.length, line.indexOf(r.to))
325
- const relStart = line.indexOf(between)
326
- const cardMatches = [...between.matchAll(/[|o}{]{2}/g)]
327
- if (cardMatches[0]) map.labels.set(`${key}:leftCardinality`, loc(i + 1, relStart + cardMatches[0].index! + 1))
328
- if (cardMatches[1]) map.labels.set(`${key}:rightCardinality`, loc(i + 1, relStart + cardMatches[1].index! + 1))
329
- break
330
- }
331
- })
332
- return map
333
- }
334
-
335
- function buildChartSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
336
- const map = emptySourceMap()
337
- const lines = canonicalSource.split(/\r?\n/)
338
- if (body.kind === 'xychart') {
339
- const b = body as XyChartBody
340
- b.series.forEach((series, si) => {
341
- const lineIndex = lines.findIndex(line => line.trim().startsWith(series.kind))
342
- if (lineIndex < 0) return
343
- const line = lines[lineIndex]!
344
- if (series.name) map.labels.set(`xychart:${series.id}:name`, loc(lineIndex + 1, firstIndex(line, series.name)))
345
- series.values.forEach((value, vi) => {
346
- const valueText = String(value)
347
- const col = line.indexOf(valueText)
348
- if (col >= 0) map.labels.set(`xychart:${series.id}:point#${vi}`, loc(lineIndex + 1, col + 1))
349
- })
350
- })
351
- } else if (body.kind === 'pie') {
352
- ;(body as PieBody).slices.forEach((slice, index) => {
353
- const lineIndex = lines.findIndex(line => line.includes(slice.label))
354
- if (lineIndex >= 0) map.labels.set(`pie:slice#${index}`, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, slice.label)))
355
- })
356
- } else if (body.kind === 'quadrant') {
357
- ;(body as QuadrantBody).points.forEach((point, index) => {
358
- const lineIndex = lines.findIndex(line => line.includes(point.label))
359
- if (lineIndex >= 0) map.labels.set(`quadrant:point#${index}`, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, point.label)))
360
- })
361
- }
362
- return map
363
- }
364
-
365
- function buildGanttSourceMap(body: DiagramBody, canonicalSource: string): SourceMap {
366
- const map = emptySourceMap()
367
- if (body.kind !== 'gantt') return map
368
- const b = body as GanttBody
369
- const lines = canonicalSource.split(/\r?\n/)
370
- for (const section of b.sections) {
371
- if (section.label) {
372
- const lineIndex = lines.findIndex(line => /^\s*section\s+/i.test(line) && line.includes(section.label!))
373
- if (lineIndex >= 0) { map.groups.set(section.id, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, section.label))); map.labels.set(`gantt:${section.id}:label`, loc(lineIndex + 1, firstIndex(lines[lineIndex]!, section.label))) }
374
- }
375
- for (const task of section.tasks) {
376
- const stableId = task.taskId ?? task.id
377
- const lineIndex = lines.findIndex(line => line.includes(task.label) && line.includes(task.end))
378
- if (lineIndex < 0) continue
379
- const line = lines[lineIndex]!
380
- map.nodes.set(stableId, loc(lineIndex + 1, firstIndex(line, task.label)))
381
- map.labels.set(`gantt:task:${stableId}`, loc(lineIndex + 1, firstIndex(line, task.label)))
382
- }
383
- }
384
- return map
385
- }
386
-
387
- function escapeSourceMapRegex(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') }
388
-
389
- function extractClassLabels(source: string): ExtractedLabel[] {
390
- const out: ExtractedLabel[] = []
391
- const lines = source.split(/\r?\n/)
392
- for (let i = 0; i < lines.length; i++) {
393
- const raw = lines[i]!.trim()
394
- if (!raw || raw.startsWith('%%')) continue
395
- let m
396
- if ((m = raw.match(/^class\s+\S+\s+as\s+"([^"]+)"/i))) {
397
- out.push({ text: m[1]!, target: `line${i + 1}` })
398
- } else if ((m = raw.match(/^\S+\s*:\s*(.+)$/))) {
399
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
400
- } else if ((m = raw.match(/^[+\-#~]\s*(.+)$/))) {
401
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
402
- } else if ((m = raw.match(/^note\s+(?:for\s+\S+\s+)?"([^"]+)"/i))) {
403
- out.push({ text: m[1]!, target: `line${i + 1}` })
404
- }
405
- }
406
- return out
407
- }
408
-
409
- registerFamily({
410
- id: 'class',
411
- detect: l => l.startsWith('classdiagram'),
412
- extractLabels: extractClassLabels,
413
- // Loop 8 A1: the structured class verifier IS the verify path — verifyMermaid
414
- // routes class diagrams through this plugin hook (Loop 9 M2 removed the
415
- // duplicate per-body branch). Single source of truth.
416
- verify: (body, opts) => body.kind === 'class' ? verifyClass(body, opts) : [],
417
- buildSourceMap: buildClassSourceMap,
418
- ...structuredFamilyHooks('class', { parseBody: parseClassBody, serialize: renderClass, mutate: mutateClass }),
419
- })
420
-
421
- // ---- ER -------------------------------------------------------------------
422
- // CUSTOMER ||--o{ ORDER : places, attributes inside braces.
423
- function extractErLabels(source: string): ExtractedLabel[] {
424
- const out: ExtractedLabel[] = []
425
- const lines = source.split(/\r?\n/)
426
- for (let i = 0; i < lines.length; i++) {
427
- const raw = lines[i]!.trim()
428
- if (!raw || raw.startsWith('%%')) continue
429
- let m
430
- if ((m = raw.match(/:\s*"?([^"]+?)"?$/))) {
431
- out.push({ text: m[1]!.trim(), target: `line${i + 1}` })
432
- }
433
- // Attribute lines inside `{ ... }` blocks
434
- if (raw.match(/^\s*\w+\s+\w+/) && !raw.match(/[<>|}]/)) {
435
- out.push({ text: raw, target: `line${i + 1}` })
436
- }
437
- }
438
- return out
439
- }
440
-
441
- registerFamily({
442
- id: 'er',
443
- detect: l => l.startsWith('erdiagram'),
444
- extractLabels: extractErLabels,
445
- // Loop 8 A1: same as class — this hook is the verify path for ER (Loop 9 M2
446
- // removed the duplicate per-body branch in verify.ts).
447
- verify: (body, opts) => body.kind === 'er' ? verifyErBody(body, opts) : [],
448
- buildSourceMap: buildErSourceMap,
449
- ...structuredFamilyHooks('er', { parseBody: parseErBody, serialize: renderEr, mutate: mutateEr }),
450
- })
451
-
452
- // ---- Journey --------------------------------------------------------------
453
- // title T, section S, task: 3: Me — label extraction rides the shared parse
454
- // core walker (scan mode: issues are skipped, labels still flow), so opaque
455
- // journey sources get overflow checks from the same grammar the parsers use.
456
- function extractJourneyLabels(source: string): ExtractedLabel[] {
457
- const out: ExtractedLabel[] = []
458
- const lines = source.split(/\r?\n/)
459
- const headerIndex = lines.findIndex(line => /^\s*journey\b/i.test(line))
460
- const push = (text: string, lineIndex: number): void => {
461
- for (const part of text.split('\n')) {
462
- if (part) out.push({ text: part, target: `line${lineIndex + 1}` })
463
- }
464
- }
465
- walkJourneyLines(lines, headerIndex + 1, {
466
- title: push,
467
- accTitle: push,
468
- accDescr: push,
469
- section: push,
470
- task: (text, _score, actors, lineIndex) => {
471
- push(text, lineIndex)
472
- for (const actor of actors) push(actor, lineIndex)
473
- },
474
- })
475
- return out
476
- }
477
-
478
- // Opaque-journey diagnostics re-derive the blocking issue from source with the
479
- // SAME shared grammar the parsers use (src/journey/parse-core.ts), so the
480
- // reported reason cannot drift from what the parser actually rejected — and
481
- // comments / accDescr block interiors are never mistaken for bad task lines.
482
- function verifyOpaqueJourney(body: DiagramBody): LayoutWarning[] {
483
- if (body.kind !== 'opaque' || body.family !== 'journey') return []
484
- const warnings: LayoutWarning[] = []
485
- const lines = body.source.split(/\r?\n/)
486
- // Skip the header line wherever it sits (leading blanks/comments preserved
487
- // in opaque source keep their positions, so line numbers stay truthful).
488
- const headerIndex = lines.findIndex(line => /^\s*journey\b/i.test(line))
489
- let blocking: JourneyParseIssue | undefined
490
- walkJourneyLines(lines, headerIndex + 1, {
491
- issue: issue => {
492
- if (issue.code === 'invalid_score') {
493
- warnings.push({
494
- code: 'UNSUPPORTED_SYNTAX',
495
- line: issue.lineIndex + 1,
496
- syntax: 'journey_invalid_score',
497
- message: `${issue.detail}.`,
498
- })
499
- return
500
- }
501
- blocking ??= issue
502
- },
503
- })
504
- if (blocking) {
505
- warnings.push({
506
- code: 'UNSUPPORTED_SYNTAX',
507
- line: blocking.lineIndex + 1,
508
- syntax: `journey_${blocking.code}`,
509
- message: `${blocking.detail}. The diagram is preserved verbatim as source; fix this line to unlock typed journey mutation.`,
510
- })
511
- }
512
- return warnings
513
- }
514
-
515
- registerFamily({
516
- id: 'journey',
517
- detect: l => l.startsWith('journey'),
518
- extractLabels: extractJourneyLabels,
519
- // BUILD-15: journey is structured-when-narrowed. The verify hook covers the
520
- // structured body; opaque fallbacks keep the universal label-extraction path.
521
- verify: (body, opts) => body.kind === 'journey' ? verifyJourney(body, opts) : verifyOpaqueJourney(body),
522
- ...structuredFamilyHooks('journey', {
523
- headerOk: h => /^journey\s*$/i.test(h),
524
- parseBody: lines => {
525
- const outcome = parseJourneyBody(lines)
526
- return outcome.ok ? outcome.body : null
527
- },
528
- serialize: renderJourney, mutate: mutateJourney,
529
- }),
530
- })
531
-
532
- // ---- XY chart -------------------------------------------------------------
533
- // title "T", x-axis [a,b,c], y-axis "label"
534
- function extractXyChartLabels(source: string): ExtractedLabel[] {
535
- const out: ExtractedLabel[] = []
536
- const lines = source.split(/\r?\n/)
537
- for (let i = 0; i < lines.length; i++) {
538
- const rawLine = lines[i]!.trim()
539
- if (!rawLine || rawLine.startsWith('%%')) continue
540
- const statements = splitXyLabelStatements(rawLine)
541
- for (const raw of statements) {
542
- const target = `line${i + 1}`
543
- let m
544
- if ((m = raw.match(/^accDescr\s*:?\s*\{\s*(.*)$/i))) {
545
- const first = m[1]!
546
- const end = first.indexOf('}')
547
- if (end >= 0) {
548
- const text = first.slice(0, end).trim()
549
- if (text) out.push({ text, target })
550
- } else {
551
- const text = first.trim()
552
- if (text) out.push({ text, target })
553
- for (i += 1; i < lines.length; i++) {
554
- const line = lines[i]!.trim()
555
- const close = line.indexOf('}')
556
- const text = (close >= 0 ? line.slice(0, close) : line).trim()
557
- if (text) out.push({ text, target: `line${i + 1}` })
558
- if (close >= 0) break
559
- }
560
- }
561
- continue
562
- }
563
- if ((m = raw.match(/^accTitle\s*:?\s*(.+)$/i))) out.push({ text: m[1]!.trim(), target })
564
- else if ((m = raw.match(/^accDescr\s*:?\s*(.+)$/i))) out.push({ text: m[1]!.trim(), target })
565
- // All quoted strings, including escaped quote/backslash pairs.
566
- for (const q of quotedLabelMatches(raw)) out.push({ text: q, target })
567
- const title = raw.match(/^title\s+(.+)$/i)
568
- if (title && !/^['"]/.test(title[1]!.trim())) out.push({ text: title[1]!.trim(), target })
569
- const axisTitleWithCategories = raw.match(/^[xy]-axis\s+(.+?)\s*\[[^\]]+\]\s*$/i)
570
- const axisTitleWithRange = raw.match(/^[xy]-axis\s+(\S+)\s+[+-]?(?:(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*-->/i)
571
- const axisTitle = axisTitleWithCategories ?? axisTitleWithRange ?? raw.match(/^[xy]-axis\s+([^\[\d.+-][^\[]*?)\s*(?:\[|[+-]?\d|$)/i)
572
- if (axisTitle && !/^['"]/.test(axisTitle[1]!.trim())) out.push({ text: axisTitle[1]!.trim(), target })
573
- const seriesLabel = raw.match(/^(?:bar|line)\s+(.+?)\s+\[[^\]]+\]\s*$/i)
574
- if (seriesLabel && !/^['"]/.test(seriesLabel[1]!.trim())) out.push({ text: seriesLabel[1]!.trim(), target })
575
- // x-axis [a, b, c] — extract individual entries
576
- const ax = raw.match(/^[xy]-axis\b.*\[([^\]]+)\]/i)
577
- if (ax) {
578
- for (const entry of ax[1]!.split(',')) {
579
- const t = entry.trim().replace(/^["']|["']$/g, '')
580
- if (t) out.push({ text: t, target })
581
- }
582
- }
583
- }
584
- }
585
- return out
586
- }
587
-
588
- function quotedLabelMatches(raw: string): string[] {
589
- const labels: string[] = []
590
- for (const quote of ['"', "'"] as const) {
591
- const pattern = quote === '"' ? /"((?:\\.|[^"\\])+)"/g : /'((?:\\.|[^'\\])*)'/g
592
- for (const m of raw.matchAll(pattern)) labels.push(m[1]!.replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\'))
593
- }
594
- return labels
595
- }
596
-
597
- function splitXyLabelStatements(line: string): string[] {
598
- const statements: string[] = []
599
- let current = ''
600
- let quote: '"' | "'" | null = null
601
- for (let i = 0; i < line.length; i++) {
602
- const char = line[i]!
603
- if (quote) {
604
- current += char
605
- if (char === '\\') { current += line[++i] ?? ''; continue }
606
- if (char === quote) quote = null
607
- continue
608
- }
609
- if (char === '"' || char === "'") { quote = char; current += char; continue }
610
- if (char === ';') {
611
- const trimmed = current.trim()
612
- if (trimmed) statements.push(trimmed)
613
- current = ''
614
- continue
615
- }
616
- current += char
617
- }
618
- const trimmed = current.trim()
619
- if (trimmed) statements.push(trimmed)
620
- return statements
621
- }
622
-
623
- registerFamily({
624
- id: 'xychart',
625
- detect: l => l.startsWith('xychart'),
626
- extractLabels: extractXyChartLabels,
627
- // BUILD-16: xychart is structured-when-narrowed. The verify hook covers the
628
- // structured body; opaque fallbacks (accTitle/accDescr, quoted text,
629
- // multi-statement `;` lines, unmodeled tokens like `curve basis`) keep the
630
- // universal label-extraction path. headerOk requires `xychart`/`xychart-beta`
631
- // with at most a `horizontal`/`vertical` orientation suffix — any other
632
- // trailing token (e.g. `EXTRA`) stays opaque so it round-trips verbatim.
633
- verify: (body, opts) => body.kind === 'xychart' ? verifyXyChart(body, opts) : [],
634
- buildSourceMap: buildChartSourceMap,
635
- // xychart needs the header to model the `horizontal` orientation suffix, so it
636
- // uses a tailored parse hook (not the shared structuredFamilyHooks) — but
637
- // serialize/mutate stay identical to every other structured family.
638
- parse: (lines, opaqueSource) => {
639
- const header = lines[0]?.trim() ?? ''
640
- const hm = header.match(/^xychart(?:-beta)?(?:\s+(horizontal|vertical))?\s*$/i)
641
- const body = hm ? parseXyChartBody(lines.slice(1)) : null
642
- if (body && hm?.[1]?.toLowerCase() === 'horizontal') body.horizontal = true
643
- return ok(body ?? { kind: 'opaque', family: 'xychart', source: opaqueSource })
644
- },
645
- serialize: body => {
646
- if (body.kind !== 'xychart') throw new Error(`xychart serializer received body kind ${body.kind}`)
647
- return renderXyChart(body)
648
- },
649
- mutate: (body, op) => {
650
- if (body.kind !== 'xychart') return err<MutationError>({ code: 'INVALID_OP', message: `xychart mutator received body kind ${body.kind}` })
651
- return mutateXyChart(body, op as never)
652
- },
653
- })
654
-
655
- // ---- Pie ------------------------------------------------------------------
656
- // pie [showData] [title T], optional `title T`, `"label" : number` entries.
657
- // Pie is structured-when-narrowed: the body parses to a PieBody (title,
658
- // showData, slices) or falls back to opaque when any line is unmodeled.
659
- // Labels are the quoted slice labels plus the optional title text.
660
- function extractPieLabels(source: string): ExtractedLabel[] {
661
- const out: ExtractedLabel[] = []
662
- const lines = source.split(/\r?\n/)
663
- for (let i = 0; i < lines.length; i++) {
664
- const raw = lines[i]!.trim()
665
- if (!raw || raw.startsWith('%%')) continue
666
- const target = `line${i + 1}`
667
- // Header may carry an inline title: `pie title Pets` / `pie showData title Pets`.
668
- let m
669
- if ((m = raw.match(/^pie\b\s*(?:showData\b\s*)?title\s+(.+)$/i))) {
670
- out.push({ text: m[1]!.trim(), target })
671
- continue
672
- }
673
- if (/^pie\b/i.test(raw)) continue
674
- if ((m = raw.match(/^title\s+(.+)$/i))) {
675
- out.push({ text: m[1]!.trim(), target })
676
- continue
677
- }
678
- // Entry line: `"label" : value` — extract the quoted label.
679
- if ((m = raw.match(/^"((?:[^"\\]|\\.)*)"\s*:/))) {
680
- const text = m[1]!.replace(/\\"/g, '"').replace(/\\\\/g, '\\').trim()
681
- if (text) out.push({ text, target })
682
- }
683
- }
684
- return out
685
- }
686
-
687
- // Parse the `pie [showData] [title <text>]` header tail. Returns null when the
688
- // tail carries unmodeled tokens, so the whole body falls back to opaque.
689
- function parsePieHeader(header: string): { showData: boolean; title?: string } | null {
690
- const m = header.match(/^pie\b(.*)$/i)
691
- if (!m) return null
692
- let tail = m[1]!.trim()
693
- let showData = false
694
- const sd = tail.match(/^showData\b\s*(.*)$/i)
695
- if (sd) { showData = true; tail = sd[1]!.trim() }
696
- const inlineTitle = tail.match(/^title\s+(.+)$/i)
697
- if (inlineTitle) return { showData, title: inlineTitle[1]!.trim() }
698
- if (tail.length > 0) return null // unexpected text after the header → opaque
699
- return { showData }
700
- }
701
-
702
- registerFamily({
703
- id: 'pie',
704
- detect: l => l.startsWith('pie'),
705
- extractLabels: extractPieLabels,
706
- // Pie is structured-when-narrowed. The verify hook covers the structured
707
- // body; opaque fallbacks keep the universal label-extraction path. The header
708
- // carries showData / inline title, so pie uses a tailored parse hook (like
709
- // xychart) — serialize/mutate stay identical to every other structured family.
710
- verify: (body, opts) => body.kind === 'pie' ? verifyPie(body, opts) : [],
711
- buildSourceMap: buildChartSourceMap,
712
- parse: (lines, opaqueSource) => {
713
- const header = parsePieHeader(lines[0]?.trim() ?? '')
714
- const body = header ? parsePieBody(lines.slice(1), header) : null
715
- return ok(body ?? { kind: 'opaque', family: 'pie', source: opaqueSource })
716
- },
717
- serialize: body => {
718
- if (body.kind !== 'pie') throw new Error(`pie serializer received body kind ${body.kind}`)
719
- return renderPie(body)
720
- },
721
- mutate: (body, op) => {
722
- if (body.kind !== 'pie') return err<MutationError>({ code: 'INVALID_OP', message: `pie mutator received body kind ${body.kind}` })
723
- return mutatePie(body, op as never)
724
- },
725
- })
726
-
727
- // ---- Quadrant -------------------------------------------------------------
728
- // quadrantChart header; `title T`; `x-axis a --> b`; `y-axis a --> b`;
729
- // `quadrant-1..4 label`; `Label: [x, y]`. Quadrant is structured-when-narrowed:
730
- // the body parses to a QuadrantBody (title, axes, quadrant labels, points) or
731
- // falls back to opaque when any line is unmodeled (styling, malformed coords,
732
- // duplicate point labels). Labels are the title, both axis label sides, the
733
- // four quadrant region labels, and the point labels.
734
- function extractQuadrantLabels(source: string): ExtractedLabel[] {
735
- const out: ExtractedLabel[] = []
736
- const lines = source.split(/\r?\n/)
737
- for (let i = 0; i < lines.length; i++) {
738
- const raw = lines[i]!.trim()
739
- if (!raw || raw.startsWith('%%')) continue
740
- const target = `line${i + 1}`
741
- if (/^quadrantchart\b/i.test(raw)) continue
742
- let m
743
- if ((m = raw.match(/^title\s+(.+)$/i))) {
744
- out.push({ text: m[1]!.trim(), target })
745
- continue
746
- }
747
- // x-axis / y-axis: `<near> [--> <far>]` — extract both sides.
748
- if ((m = raw.match(/^[xy]-axis\s+(.+)$/i))) {
749
- const tail = m[1]!.trim()
750
- const arrow = tail.indexOf('-->')
751
- if (arrow >= 0) {
752
- const near = tail.slice(0, arrow).trim()
753
- const far = tail.slice(arrow + 3).trim()
754
- if (near) out.push({ text: near, target })
755
- if (far) out.push({ text: far, target })
756
- } else if (tail) {
757
- out.push({ text: tail, target })
758
- }
759
- continue
760
- }
761
- if ((m = raw.match(/^quadrant-[1-4]\s+(.+)$/i))) {
762
- out.push({ text: m[1]!.trim(), target })
763
- continue
764
- }
765
- // Point line: `Label[:::class]: [x, y] [style metadata]` — extract the
766
- // display label, not the optional class/style adornments.
767
- if ((m = raw.match(/^(.+?)\s*:\s*\[[^\]]*\]\s*(?:.*)?$/))) {
768
- const text = m[1]!.replace(/\s*:::\s*[A-Za-z_][\w-]*\s*$/, '').trim()
769
- if (text) out.push({ text, target })
770
- }
771
- }
772
- return out
773
- }
774
-
775
- function verifyOpaqueQuadrant(body: DiagramBody): LayoutWarning[] {
776
- if (body.kind !== 'opaque' || body.family !== 'quadrant') return []
777
- const warnings: LayoutWarning[] = []
778
- // Unrenderable opaque sources are the universal render-parity gate's job
779
- // (Tier-1 RENDER_FAILED in verifyMermaid) — this hook's remaining value is
780
- // the style-metadata lint, which scans raw lines and needs no parse.
781
-
782
- let sawPointStyle = false
783
- let sawClassDef = false
784
- for (const rawLine of body.source.split(/\r?\n/)) {
785
- const raw = rawLine.trim()
786
- if (!raw || raw.startsWith('%%')) continue
787
- if (/^classDef\b/i.test(raw)) sawClassDef = true
788
- const point = raw.match(/^(.+?)\s*:\s*\[[^\]]*\]\s*(.*)$/)
789
- if (point && (point[1]!.includes(':::') || point[2]!.trim().length > 0)) sawPointStyle = true
790
- }
791
- if (sawPointStyle) {
792
- warnings.push({
793
- code: 'UNSUPPORTED_SYNTAX',
794
- syntax: 'quadrant_point_style_metadata',
795
- message: 'Quadrant point style/class metadata is preserved in source and accepted by the local renderer, but typed mutation/layout metadata does not model radius/color/class styling.',
796
- })
797
- }
798
- if (sawClassDef) {
799
- warnings.push({
800
- code: 'UNSUPPORTED_SYNTAX',
801
- syntax: 'quadrant_classDef_metadata',
802
- message: 'Quadrant classDef metadata is preserved in source and accepted by the local renderer, but typed mutation/layout metadata does not model class styling.',
803
- })
804
- }
805
- return warnings
806
- }
807
-
808
- registerFamily({
809
- id: 'quadrant',
810
- detect: l => l.startsWith('quadrantchart'),
811
- extractLabels: extractQuadrantLabels,
812
- // Quadrant is structured-when-narrowed. The verify hook covers the structured
813
- // body; opaque fallbacks keep the universal label-extraction path and warn
814
- // when official style metadata is preserved but not semantically modeled.
815
- verify: (body, opts) => body.kind === 'quadrant' ? verifyQuadrant(body, opts) : verifyOpaqueQuadrant(body),
816
- buildSourceMap: buildChartSourceMap,
817
- ...structuredFamilyHooks('quadrant', {
818
- headerOk: h => /^quadrantchart\s*$/i.test(h),
819
- parseBody: parseQuadrantBody, serialize: renderQuadrant, mutate: mutateQuadrant,
820
- }),
821
- })
822
-
823
- // ---- Gantt ------------------------------------------------------------------
824
- // title T, section S, task lines `Label : meta`, plus directive labels that
825
- // matter for LABEL_OVERFLOW on opaque bodies (accTitle/accDescr, todayMarker
826
- // excluded — they are styling/config, not display labels).
827
- function extractGanttLabels(source: string): ExtractedLabel[] {
828
- const out: ExtractedLabel[] = []
829
- const lines = source.split(/\r?\n/)
830
- for (let i = 0; i < lines.length; i++) {
831
- const raw = lines[i]!.trim()
832
- if (!raw || raw.startsWith('%%')) continue
833
- const target = `line${i + 1}`
834
- let m
835
- if (/^gantt\s*$/i.test(raw)) continue
836
- if ((m = raw.match(/^(?:title|section)\s+(.+)$/i))) {
837
- out.push({ text: m[1]!.trim(), target })
838
- continue
839
- }
840
- if ((m = raw.match(/^acc(?:Title|Descr)\s*:\s*(.+)$/i))) {
841
- out.push({ text: m[1]!.trim(), target })
842
- continue
843
- }
844
- // Directive lines carry config values, not labels.
845
- if (/^(dateFormat|axisFormat|tickInterval|inclusiveEndDates|topAxis|excludes|includes|todayMarker|weekday|weekend|click|accDescr)\b/i.test(raw)) continue
846
- // Task line: the label is everything before the first colon.
847
- const colon = raw.indexOf(':')
848
- if (colon > 0) {
849
- const text = raw.slice(0, colon).trim()
850
- if (text) out.push({ text, target })
851
- }
852
- }
853
- return out
854
- }
855
-
856
- // Gantt parse needs the RAW (indentation-preserving) body lines so opaque
857
- // segments (directives, click lines, comments) round-trip verbatim — the
858
- // same wiring as sequence, except the header is located rather than assumed
859
- // to be raw line 0 (leading blank lines must not duplicate the header).
860
- function ganttRawBodyLines(opaqueSource: string): string[] {
861
- const raw = opaqueSource.split(/\r?\n/)
862
- const headerAt = raw.findIndex(l => /^gantt\b/i.test(l.trim()))
863
- return headerAt >= 0 ? raw.slice(headerAt + 1) : raw.slice(1)
864
- }
865
-
866
- registerFamily({
867
- id: 'gantt',
868
- detect: l => l.startsWith('gantt'),
869
- extractLabels: extractGanttLabels,
870
- // Source-level structural checks (EMPTY/LABEL_OVERFLOW/EDGE_MISANCHORED on
871
- // after/until refs); see docs/design/families/gantt.md §Verification.
872
- verify: (body, opts) => body.kind === 'gantt' ? verifyGantt(body, opts) : [],
873
- buildSourceMap: buildGanttSourceMap,
874
- parse: (lines, opaqueSource) => {
875
- const headerOk = /^gantt\s*$/i.test(lines[0]?.trim() ?? '')
876
- const body = headerOk ? parseGanttBody(lines.slice(1), ganttRawBodyLines(opaqueSource)) : null
877
- return ok(body ?? { kind: 'opaque', family: 'gantt', source: opaqueSource })
878
- },
879
- serialize: body => {
880
- if (body.kind !== 'gantt') throw new Error(`gantt serializer received body kind ${body.kind}`)
881
- return renderGantt(body)
882
- },
883
- mutate: (body, op) => {
884
- if (body.kind !== 'gantt') return err<MutationError>({ code: 'INVALID_OP', message: `gantt mutator received body kind ${body.kind}` })
885
- return mutateGantt(body, op as never)
886
- },
887
- })
888
-
889
- // ---- Architecture ---------------------------------------------------------
890
- // group api(cloud)[API], service db(database)[DB] in api
891
- function extractArchitectureLabels(source: string): ExtractedLabel[] {
892
- const out: ExtractedLabel[] = []
893
- const lines = source.split(/\r?\n/)
894
- for (let i = 0; i < lines.length; i++) {
895
- const raw = lines[i]!.trim()
896
- if (!raw || raw.startsWith('%%')) continue
897
- for (const m of raw.matchAll(/\[([^\]]+)\]/g)) {
898
- out.push({ text: m[1]!, target: `line${i + 1}` })
899
- }
900
- }
901
- return out
902
- }
903
-
904
- registerFamily({
905
- id: 'architecture',
906
- detect: l => l.startsWith('architecture'),
907
- extractLabels: extractArchitectureLabels,
908
- // BUILD-17: architecture is structured-when-narrowed. The verify hook covers
909
- // the structured body; opaque fallbacks (accTitle/accDescr, {group} boundary
910
- // edges, unmodeled syntax) keep the universal label-extraction path.
911
- verify: (body, opts) => body.kind === 'architecture' ? verifyArchitecture(body, opts) : [],
912
- ...structuredFamilyHooks('architecture', {
913
- headerOk: h => /^architecture-beta\s*$/i.test(h),
914
- parseBody: parseArchitectureBody, serialize: renderArchitecture, mutate: mutateArchitecture,
915
- }),
916
- })
917
-
918
- // Re-export so importing this module is the only thing needed to populate
919
- // the registry.
920
- export { registerFamily, getFamily, knownFamilies, extractLabelsGeneric } from './families.ts'