@zyro-sec/merman 0.0.0-stage → 1.0.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 (92) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.test.ts +203 -0
  4. package/src/core/canvas.ts +228 -0
  5. package/src/core/color/style.test.ts +24 -0
  6. package/src/core/color/style.ts +56 -0
  7. package/src/core/drawing.test.ts +116 -0
  8. package/src/core/drawing.ts +301 -0
  9. package/src/core/geometry.test.ts +112 -0
  10. package/src/core/geometry.ts +347 -0
  11. package/src/core/mermaid.ts +38 -0
  12. package/src/core/render-grid.ts +51 -0
  13. package/src/core/spatial.test.ts +87 -0
  14. package/src/core/spatial.ts +243 -0
  15. package/src/core/text-lines.ts +32 -0
  16. package/src/core/text.test.ts +33 -0
  17. package/src/core/text.ts +44 -0
  18. package/src/detect.ts +17 -0
  19. package/src/diagnostics.ts +16 -0
  20. package/src/flowchart/drawing.ts +340 -0
  21. package/src/flowchart/flowchart.test.ts +2800 -0
  22. package/src/flowchart/labels.test.ts +127 -0
  23. package/src/flowchart/labels.ts +144 -0
  24. package/src/flowchart/layout.ts +1427 -0
  25. package/src/flowchart/options.ts +12 -0
  26. package/src/flowchart/parser.ts +467 -0
  27. package/src/flowchart/render.ts +10 -0
  28. package/src/flowchart/routing.test.ts +368 -0
  29. package/src/flowchart/routing.ts +1542 -0
  30. package/src/flowchart/style.ts +79 -0
  31. package/src/flowchart/types.ts +65 -0
  32. package/src/gantt/diagram.test.ts +124 -0
  33. package/src/gantt/diagram.ts +8 -0
  34. package/src/gantt/drawing.ts +191 -0
  35. package/src/gantt/parser.ts +161 -0
  36. package/src/gantt/render-grid.ts +17 -0
  37. package/src/gantt/style.ts +36 -0
  38. package/src/gantt/types.ts +44 -0
  39. package/src/gitgraph/diagram.test.ts +183 -0
  40. package/src/gitgraph/diagram.ts +8 -0
  41. package/src/gitgraph/drawing.ts +234 -0
  42. package/src/gitgraph/parser.ts +219 -0
  43. package/src/gitgraph/render-grid.ts +17 -0
  44. package/src/gitgraph/style.ts +37 -0
  45. package/src/gitgraph/types.ts +36 -0
  46. package/src/layout-audit.test.ts +92 -0
  47. package/src/markdown.ts +336 -0
  48. package/src/palette.test.ts +103 -0
  49. package/src/palette.ts +75 -0
  50. package/src/plugin.ts +15 -0
  51. package/src/sequence/diagram.test.ts +757 -0
  52. package/src/sequence/diagram.ts +8 -0
  53. package/src/sequence/drawing.ts +287 -0
  54. package/src/sequence/options.ts +8 -0
  55. package/src/sequence/parser.ts +282 -0
  56. package/src/sequence/placement.test.ts +219 -0
  57. package/src/sequence/placement.ts +684 -0
  58. package/src/sequence/render-grid.ts +22 -0
  59. package/src/sequence/style.ts +81 -0
  60. package/src/sequence/types.ts +74 -0
  61. package/src/state/diagram.test.ts +1386 -0
  62. package/src/state/diagram.ts +8 -0
  63. package/src/state/drawing.ts +360 -0
  64. package/src/state/endpoint.ts +15 -0
  65. package/src/state/layout.test.ts +314 -0
  66. package/src/state/layout.ts +1134 -0
  67. package/src/state/note.ts +59 -0
  68. package/src/state/options.ts +11 -0
  69. package/src/state/parser.ts +224 -0
  70. package/src/state/render-grid.ts +22 -0
  71. package/src/state/routing.test.ts +693 -0
  72. package/src/state/routing.ts +1522 -0
  73. package/src/state/search.ts +103 -0
  74. package/src/state/style.test.ts +113 -0
  75. package/src/state/style.ts +52 -0
  76. package/src/state/types.ts +63 -0
  77. package/src/state/visible-model.test.ts +84 -0
  78. package/src/state/visible-model.ts +77 -0
  79. package/src/test/diagnostics.test.ts +129 -0
  80. package/src/test/diagram.ts +32 -0
  81. package/src/test/layout-audit/fixtures.ts +538 -0
  82. package/src/test/layout-audit/harness.ts +522 -0
  83. package/src/test/markdown.test.ts +474 -0
  84. package/src/timeline/diagram.test.ts +188 -0
  85. package/src/timeline/diagram.ts +8 -0
  86. package/src/timeline/drawing.ts +109 -0
  87. package/src/timeline/parser.ts +119 -0
  88. package/src/timeline/render-grid.ts +17 -0
  89. package/src/timeline/style.ts +36 -0
  90. package/src/timeline/types.ts +31 -0
  91. package/tsconfig.json +10 -0
  92. package/README.md +0 -3
@@ -0,0 +1,2800 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { parseColor, TextAttributes } from "@opentui/core"
3
+ import stringWidth from "string-width"
4
+ import { diagramArrowHeadBetween } from "../core/drawing.js"
5
+ import { orthogonalPathPoints } from "../core/geometry.js"
6
+ import { expectDiagram } from "../test/diagram.js"
7
+ import { deploymentArchitectureSource } from "../test/layout-audit/fixtures.js"
8
+ import { drawFlowchartDiagramGrid as drawParsedFlowchartDiagramGrid } from "./drawing.js"
9
+ import {
10
+ DEFAULT_MIN_RANK_GAP,
11
+ DEFAULT_MIN_VERTICAL_RANK_GAP,
12
+ layoutFlowchartDiagram as layoutParsedFlowchartDiagram,
13
+ visualLength,
14
+ } from "./layout.js"
15
+ import { flowchartEdgeLabelLayout, flowchartRouteLabelLayout } from "./labels.js"
16
+ import { parseMermaidFlowchartDiagram } from "./parser.js"
17
+ import { renderFlowchartDiagram } from "./render.js"
18
+ import { flowchartSourceConnector } from "./routing.js"
19
+ import { renderGridStyledText, resolveFlowchartStyleColors } from "./style.js"
20
+
21
+ function drawFlowchartDiagramGrid(content: string, options?: Parameters<typeof drawParsedFlowchartDiagramGrid>[1]) {
22
+ return drawParsedFlowchartDiagramGrid(parseMermaidFlowchartDiagram(content), options)
23
+ }
24
+
25
+ function layoutFlowchartDiagram(content: string, options?: Parameters<typeof layoutParsedFlowchartDiagram>[1]) {
26
+ return layoutParsedFlowchartDiagram(parseMermaidFlowchartDiagram(content), options)
27
+ }
28
+
29
+ test("separates subgraph labels from their frame style", () => {
30
+ const grid = drawFlowchartDiagramGrid(`flowchart LR
31
+ subgraph Group
32
+ A[Node]
33
+ end`)
34
+ const styles = grid.rows.flatMap((row) => row.map((cell) => cell.style))
35
+
36
+ expect(styles).toContain("group")
37
+ expect(styles).toContain("groupLabel")
38
+ })
39
+
40
+ test("keeps every branch connected at a shared source junction", () => {
41
+ const source = `flowchart TB
42
+ A --> B
43
+ A --> C`
44
+ const layout = layoutFlowchartDiagram(source, { compact: true })
45
+ const grid = drawFlowchartDiagramGrid(source, { compact: true })
46
+ const sourcePoint = layout.routes[0]!.points[0]!
47
+
48
+ expect(layout.routes[1]!.points[0]).toEqual(sourcePoint)
49
+ expect(grid.getCell(sourcePoint.x, sourcePoint.y)?.char).toBe("┴")
50
+ })
51
+
52
+ function routeRunsAlongHorizontalBorder(
53
+ route: { points: readonly { x: number; y: number }[] },
54
+ bounds: { left: number; top: number; width: number; height: number },
55
+ ): boolean {
56
+ const borderYs = new Set([bounds.top, bounds.top + bounds.height - 1])
57
+ const left = bounds.left
58
+ const right = bounds.left + bounds.width - 1
59
+
60
+ for (let index = 1; index < route.points.length; index++) {
61
+ const from = route.points[index - 1]!
62
+ const to = route.points[index]!
63
+ if (from.y !== to.y || !borderYs.has(from.y)) continue
64
+ if (Math.min(Math.max(from.x, to.x), right) > Math.max(Math.min(from.x, to.x), left)) return true
65
+ }
66
+ return false
67
+ }
68
+
69
+ function routeRunsAlongVerticalBorder(
70
+ route: { points: readonly { x: number; y: number }[] },
71
+ bounds: { left: number; top: number; width: number; height: number },
72
+ ): boolean {
73
+ const borderXs = new Set([bounds.left, bounds.left + bounds.width - 1])
74
+ const top = bounds.top
75
+ const bottom = bounds.top + bounds.height - 1
76
+
77
+ for (let index = 1; index < route.points.length; index++) {
78
+ const from = route.points[index - 1]!
79
+ const to = route.points[index]!
80
+ if (from.x !== to.x || !borderXs.has(from.x)) continue
81
+ if (Math.min(Math.max(from.y, to.y), bottom) > Math.max(Math.min(from.y, to.y), top)) return true
82
+ }
83
+ return false
84
+ }
85
+
86
+ function routeIntersectsBounds(
87
+ route: { points: readonly { x: number; y: number }[] },
88
+ bounds: { left: number; top: number; width: number; height: number },
89
+ ): boolean {
90
+ const right = bounds.left + bounds.width - 1
91
+ const bottom = bounds.top + bounds.height - 1
92
+ for (let index = 1; index < route.points.length; index++) {
93
+ const from = route.points[index - 1]!
94
+ const to = route.points[index]!
95
+ if (from.x === to.x) {
96
+ if (
97
+ from.x >= bounds.left &&
98
+ from.x <= right &&
99
+ Math.max(from.y, to.y) >= bounds.top &&
100
+ Math.min(from.y, to.y) <= bottom
101
+ ) {
102
+ return true
103
+ }
104
+ } else if (
105
+ from.y >= bounds.top &&
106
+ from.y <= bottom &&
107
+ Math.max(from.x, to.x) >= bounds.left &&
108
+ Math.min(from.x, to.x) <= right
109
+ ) {
110
+ return true
111
+ }
112
+ }
113
+ return false
114
+ }
115
+
116
+ function terminalPointsTowardBounds(
117
+ route: { points: readonly { x: number; y: number }[] },
118
+ bounds: { left: number; top: number; width: number; height: number },
119
+ ): boolean {
120
+ const before = route.points.at(-2)!
121
+ const end = route.points.at(-1)!
122
+ const right = bounds.left + bounds.width - 1
123
+ const bottom = bounds.top + bounds.height - 1
124
+ if (end.x === bounds.left - 1 && end.y >= bounds.top && end.y <= bottom) return before.x < end.x && before.y === end.y
125
+ if (end.x === right + 1 && end.y >= bounds.top && end.y <= bottom) return before.x > end.x && before.y === end.y
126
+ if (end.y === bounds.top - 1 && end.x >= bounds.left && end.x <= right) return before.y < end.y && before.x === end.x
127
+ if (end.y === bottom + 1 && end.x >= bounds.left && end.x <= right) return before.y > end.y && before.x === end.x
128
+ return false
129
+ }
130
+
131
+ function boundsIntersect(
132
+ left: { left: number; top: number; width: number; height: number },
133
+ right: { left: number; top: number; width: number; height: number },
134
+ ): boolean {
135
+ return (
136
+ left.left <= right.left + right.width - 1 &&
137
+ left.left + left.width - 1 >= right.left &&
138
+ left.top <= right.top + right.height - 1 &&
139
+ left.top + left.height - 1 >= right.top
140
+ )
141
+ }
142
+
143
+ function boundsContains(
144
+ outer: { left: number; top: number; width: number; height: number },
145
+ inner: { left: number; top: number; width: number; height: number },
146
+ ): boolean {
147
+ return (
148
+ inner.left >= outer.left &&
149
+ inner.top >= outer.top &&
150
+ inner.left + inner.width <= outer.left + outer.width &&
151
+ inner.top + inner.height <= outer.top + outer.height
152
+ )
153
+ }
154
+
155
+ function routesIntersect(
156
+ left: { points: readonly { x: number; y: number }[] },
157
+ right: { points: readonly { x: number; y: number }[] },
158
+ ): boolean {
159
+ const occupied = new Set(orthogonalPathPoints(left.points).map((point) => `${point.x}:${point.y}`))
160
+ return orthogonalPathPoints(right.points).some((point) => occupied.has(`${point.x}:${point.y}`))
161
+ }
162
+
163
+ function renderedDimensions(output: string): { width: number; height: number } {
164
+ const lines = output.split("\n")
165
+ return { width: Math.max(...lines.map((line) => stringWidth(line))), height: lines.length }
166
+ }
167
+
168
+ function expectResponsiveFlowchartValid(content: string, layoutMaxWidth: number) {
169
+ const diagram = parseMermaidFlowchartDiagram(content)
170
+ const options = { compact: true, layoutMaxWidth }
171
+ const layout = layoutParsedFlowchartDiagram(diagram, options)
172
+ const grid = drawParsedFlowchartDiagramGrid(diagram, options)
173
+ const output = renderFlowchartDiagram(content, options)
174
+ const nodes = [...layout.bounds.values()]
175
+
176
+ expect(layout.diagram.direction).toBe("TD")
177
+ for (let left = 0; left < nodes.length; left++) {
178
+ for (let right = left + 1; right < nodes.length; right++) {
179
+ expect(boundsIntersect(nodes[left]!, nodes[right]!)).toBe(false)
180
+ }
181
+ }
182
+ for (const route of layout.routes) {
183
+ expect(route.points.length).toBeGreaterThanOrEqual(2)
184
+ for (let index = 1; index < route.points.length; index++) {
185
+ const from = route.points[index - 1]!
186
+ const to = route.points[index]!
187
+ expect(from.x === to.x || from.y === to.y).toBe(true)
188
+ }
189
+ expect(terminalPointsTowardBounds(route, layout.bounds.get(route.edge.to)!)).toBe(true)
190
+ const end = route.points.at(-1)!
191
+ expect(grid.getCell(end.x, end.y)?.char).toBe(diagramArrowHeadBetween(route.points.at(-2)!, end))
192
+ if (route.edge.label) expect(output).toContain(route.edge.label)
193
+ }
194
+ expectFlowchartRoutesAvoidUnrelatedNodes(layout)
195
+
196
+ for (const subgraph of diagram.subgraphs ?? []) {
197
+ const frame = layout.subgraphBounds.get(subgraph.id)!
198
+ for (const nodeId of subgraph.nodeIds) expect(boundsContains(frame, layout.bounds.get(nodeId)!)).toBe(true)
199
+ expect(output).toContain(subgraph.label)
200
+ }
201
+ for (const node of layout.bounds.values()) {
202
+ for (const line of node.lines) expect(output).toContain(line)
203
+ }
204
+
205
+ const widestContent = Math.max(
206
+ ...nodes.map((node) => node.width),
207
+ ...layout.routes.flatMap((route) =>
208
+ route.edge.label ? [flowchartRouteLabelLayout(route, visualLength).width] : [],
209
+ ),
210
+ )
211
+ const dimensions = renderedDimensions(output)
212
+ expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThanOrEqual(
213
+ layoutMaxWidth + widestContent + 4,
214
+ )
215
+ return { dimensions, layout, output }
216
+ }
217
+
218
+ function generatedWideRankFlowchart(count: number): string {
219
+ const labels = [
220
+ "地域 gateway Ω",
221
+ "界面 worker λ",
222
+ "Long-running synchronization service",
223
+ "Cache café 🚀",
224
+ "Audit and observability pipeline",
225
+ "Provider μ endpoint",
226
+ "Fallback Ж service",
227
+ "Archive 数据 lake",
228
+ "Terminal résumé queue",
229
+ ]
230
+ const branches = labels
231
+ .slice(0, count)
232
+ .flatMap((label, index) => [
233
+ ` Hub ${index === 0 ? "-->|dispatch across regions and providers|" : "-->"} N${index}[${label}]`,
234
+ ` N${index} --> Join`,
235
+ ])
236
+ return [
237
+ "flowchart LR",
238
+ " Start[Client α] --> Hub",
239
+ " subgraph Services [地域 services Ω]",
240
+ " Hub[Dispatch hub]",
241
+ ...branches,
242
+ " Join[Join results]",
243
+ " end",
244
+ " Join --> Done[Complete ✓]",
245
+ ].join("\n")
246
+ }
247
+
248
+ function expectFlowchartRoutesAvoidUnrelatedNodes(layout: ReturnType<typeof layoutFlowchartDiagram>): void {
249
+ for (const route of layout.routes) {
250
+ for (const [id, bounds] of layout.bounds) {
251
+ if (id === route.edge.from || id === route.edge.to) continue
252
+ expect(routeIntersectsBounds(route, bounds)).toBe(false)
253
+ }
254
+ }
255
+ }
256
+
257
+ function expectFinalFlowchartLabelLayoutUnobstructed(layout: ReturnType<typeof layoutFlowchartDiagram>) {
258
+ const labels = layout.routes.map((route) => {
259
+ const label = flowchartRouteLabelLayout(route, visualLength)
260
+ return {
261
+ route,
262
+ label,
263
+ bounds: { left: label.point.x, top: label.point.y, width: label.width, height: label.height },
264
+ }
265
+ })
266
+
267
+ for (const [index, label] of labels.entries()) {
268
+ for (const bounds of layout.bounds.values()) expect(boundsIntersect(label.bounds, bounds)).toBe(false)
269
+ for (const [otherIndex, other] of labels.entries()) {
270
+ if (otherIndex !== index) expect(boundsIntersect(label.bounds, other.bounds)).toBe(false)
271
+ }
272
+ const textBounds = { ...label.bounds, left: label.bounds.left + 1, width: label.bounds.width - 2 }
273
+ for (const other of layout.routes) {
274
+ if (other === label.route) continue
275
+ expect(routeIntersectsBounds(other, textBounds)).toBe(false)
276
+ const source = layout.bounds.get(other.edge.from)
277
+ const sourcePoint = other.points[0]
278
+ if (!source || !sourcePoint) continue
279
+ const connector = flowchartSourceConnector(source, sourcePoint)
280
+ expect(boundsIntersect(label.bounds, { left: connector.x, top: connector.y, width: 1, height: 1 })).toBe(false)
281
+ expect(boundsIntersect(label.bounds, { left: sourcePoint.x, top: sourcePoint.y, width: 1, height: 1 })).toBe(
282
+ false,
283
+ )
284
+ }
285
+ }
286
+ return labels
287
+ }
288
+
289
+ function expectFlowchartLabelsUnobstructed(content: string): ReturnType<typeof layoutFlowchartDiagram> {
290
+ const output = renderFlowchartDiagram(content)
291
+ const layout = layoutFlowchartDiagram(content)
292
+ const labels = expectFinalFlowchartLabelLayoutUnobstructed(layout)
293
+ const grid = drawFlowchartDiagramGrid(content)
294
+
295
+ for (const label of labels) {
296
+ const escaped = label.route.edge.label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
297
+ expect(output.match(new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, "gu")) ?? []).toHaveLength(1)
298
+ for (const [lineIndex, line] of label.label.lines.entries()) {
299
+ for (let offset = 0; offset < visualLength(line); offset++) {
300
+ expect(grid.getCell(label.label.point.x + offset, label.label.point.y + lineIndex)?.style).toBe("label")
301
+ }
302
+ }
303
+ }
304
+ expectFlowchartRoutesAvoidUnrelatedNodes(layout)
305
+ return layout
306
+ }
307
+
308
+ describe("FlowchartDiagram", () => {
309
+ test("renders compact horizontal flowcharts with shorter routes", () => {
310
+ const output = renderFlowchartDiagram(
311
+ `flowchart LR
312
+ A[Idea] --> B[Parse]
313
+ B --> C[Render]
314
+ C --> D[Terminal]`,
315
+ { compact: true },
316
+ )
317
+
318
+ expectDiagram(output).toEqualDiagram(`
319
+ ╭──────╮ ╭───────╮ ╭────────╮ ╭──────────╮
320
+ │ Idea ├───▶│ Parse ├───▶│ Render ├───▶│ Terminal │
321
+ ╰──────╯ ╰───────╯ ╰────────╯ ╰──────────╯
322
+ `)
323
+ })
324
+
325
+ test("renders compact vertical flowcharts with a readable arrow stem", () => {
326
+ const output = renderFlowchartDiagram(
327
+ `flowchart TD
328
+ A[Start] --> B[Done]`,
329
+ { compact: true },
330
+ )
331
+
332
+ expectDiagram(output).toEqualDiagram(`
333
+ ╭───────╮
334
+ │ Start │
335
+ ╰───┬───╯
336
+ │
337
+ ▼
338
+ ╭──────╮
339
+ │ Done │
340
+ ╰──────╯
341
+ `)
342
+ })
343
+
344
+ test("routes compact vertical sibling subtrees from their true parents", () => {
345
+ const output = renderFlowchartDiagram(
346
+ `flowchart TD
347
+ D[DEPLOYMENT - Anomaly] --> CA[ClientApps: google, github]
348
+ D --> O[ORG acme = guild/workspace]
349
+ O --> OG[org grant: google, authed as bot@acme.com]
350
+ O --> M[MEMBER juliana]
351
+ M --> UG[user grant: google, personal]`,
352
+ { compact: true },
353
+ )
354
+
355
+ expectDiagram(output).toEqualDiagram(`
356
+ ╭──────────────────────╮
357
+ │ DEPLOYMENT - Anomaly │
358
+ ╰───────────┬──────────╯
359
+ ╭────────────────────┴────────────────────╮
360
+ ▼ ▼
361
+ ╭────────────────────────────╮ ╭────────────────────────────╮
362
+ │ ClientApps: google, github │ │ ORG acme = guild/workspace │
363
+ ╰────────────────────────────╯ ╰──────────────┬─────────────╯
364
+ ╭───────────────────────────────────┴───────╮
365
+ ▼ ▼
366
+ ╭───────────────────────────────────────────╮ ╭────────────────╮
367
+ │ org grant: google, authed as bot@acme.com │ │ MEMBER juliana │
368
+ ╰───────────────────────────────────────────╯ ╰────────┬───────╯
369
+ ╭────────────────────────────╯
370
+ ▼
371
+ ╭──────────────────────────────╮
372
+ │ user grant: google, personal │
373
+ ╰──────────────────────────────╯
374
+ `)
375
+ })
376
+
377
+ test("routes vertical sibling subtrees from their true parents", () => {
378
+ const output = renderFlowchartDiagram(`flowchart TD
379
+ D[DEPLOYMENT - Anomaly] --> CA[ClientApps: google, github]
380
+ D --> O[ORG acme = guild/workspace]
381
+ O --> OG[org grant: google, authed as bot@acme.com]
382
+ O --> M[MEMBER juliana]
383
+ M --> UG[user grant: google, personal]`)
384
+
385
+ expectDiagram(output).toEqualDiagram(`
386
+ ╭──────────────────────╮
387
+ │ DEPLOYMENT - Anomaly │
388
+ ╰───────────┬──────────╯
389
+ │
390
+ ╭────────────────────┴────────────────────╮
391
+ │ │
392
+ ▼ ▼
393
+ ╭────────────────────────────╮ ╭────────────────────────────╮
394
+ │ ClientApps: google, github │ │ ORG acme = guild/workspace │
395
+ ╰────────────────────────────╯ ╰──────────────┬─────────────╯
396
+ │
397
+ ╭───────────────────────────────────┴───────╮
398
+ │ │
399
+ ▼ ▼
400
+ ╭───────────────────────────────────────────╮ ╭────────────────╮
401
+ │ org grant: google, authed as bot@acme.com │ │ MEMBER juliana │
402
+ ╰───────────────────────────────────────────╯ ╰────────┬───────╯
403
+ │
404
+ ╭────────────────────────────╯
405
+ │
406
+ ▼
407
+ ╭──────────────────────────────╮
408
+ │ user grant: google, personal │
409
+ ╰──────────────────────────────╯
410
+ `)
411
+ })
412
+
413
+ test("keeps Unicode node labels inside their measured frame", () => {
414
+ const output = renderFlowchartDiagram(`flowchart LR
415
+ A[界]`)
416
+ const widths = output.split("\n").map((line) => stringWidth(line))
417
+
418
+ expect(new Set(widths).size).toBe(1)
419
+ expect(output).toContain("界")
420
+ })
421
+
422
+ test("does not mutate a parsed diagram when laying out with a direction override", () => {
423
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
424
+ A --> B`)
425
+
426
+ layoutParsedFlowchartDiagram(diagram, { direction: "RL" })
427
+
428
+ expect(diagram.direction).toBe("LR")
429
+ })
430
+
431
+ test("does not draw reverse-flow arrowheads on a target's opposite side", () => {
432
+ const content = `flowchart RL
433
+ Parser[Parser] --> Output[Rendered]`
434
+ const output = renderFlowchartDiagram(content)
435
+ const layout = layoutFlowchartDiagram(content)
436
+ const outputBounds = layout.bounds.get("Output")!
437
+ const renderedRow = output.split("\n").find((line) => line.includes("Rendered"))!
438
+
439
+ const horizontalRoute = layout.routes.find((route) => route.edge.from === "Parser" && route.edge.to === "Output")!
440
+ expect(horizontalRoute.points.at(-1)?.x).toBe(outputBounds.left + outputBounds.width)
441
+ expect(renderedRow).toContain("│ Rendered │◀")
442
+ expect(renderedRow.trimStart().startsWith("◀")).toBe(false)
443
+ })
444
+
445
+ test("preserves arrowheads for horizontal cycles", () => {
446
+ const output = renderFlowchartDiagram(`flowchart LR
447
+ A[A] --> B[B]
448
+ B --> A`)
449
+
450
+ expectDiagram(output).toEqualDiagram(`
451
+ ╭───────────╮
452
+ │ │
453
+ │ │
454
+ ▼ │
455
+ ╭───╮ ╭─┴─╮
456
+ │ A ├──────▶│ B │
457
+ ╰───╯ ╰───╯
458
+ `)
459
+ })
460
+
461
+ test.each(
462
+ (["LR", "RL", "TD", "TB", "BT"] as const).flatMap((direction) =>
463
+ [false, true].map((compact) => ({ direction, compact })),
464
+ ),
465
+ )(
466
+ "preserves every target arrowhead after painting $direction routes with compact=$compact",
467
+ ({ direction, compact }) => {
468
+ const content = `flowchart ${direction}
469
+ A[A]
470
+ B[B]
471
+ C[C]
472
+ D[D]
473
+ A --> A
474
+ A --> C
475
+ C --> B`
476
+ const diagram = parseMermaidFlowchartDiagram(content)
477
+ const layout = layoutParsedFlowchartDiagram(diagram, { compact })
478
+ const grid = drawParsedFlowchartDiagramGrid(diagram, { compact })
479
+
480
+ for (const route of layout.routes) {
481
+ const end = route.points.at(-1)!
482
+ expect(grid.getCell(end.x, end.y)?.char).toBe(diagramArrowHeadBetween(route.points.at(-2)!, end))
483
+ }
484
+ },
485
+ )
486
+
487
+ test.each(
488
+ (["LR", "RL", "TD", "TB", "BT"] as const).flatMap((direction) =>
489
+ [false, true].map((compact) => ({ direction, compact })),
490
+ ),
491
+ )("keeps crossed endpoint-disjoint $direction routes separate with compact=$compact", ({ direction, compact }) => {
492
+ const layout = layoutFlowchartDiagram(
493
+ `flowchart ${direction}
494
+ A[A]
495
+ B[B]
496
+ C[C]
497
+ D[D]
498
+ A --> C
499
+ D --> B`,
500
+ { compact },
501
+ )
502
+
503
+ expect(layout.routes).toHaveLength(2)
504
+ expect(routesIntersect(layout.routes[0]!, layout.routes[1]!)).toBe(false)
505
+ })
506
+
507
+ test("keeps vertical feedback labels clear of unrelated nodes", () => {
508
+ const content = `flowchart TD
509
+ S[Source] --> A[Alpha]
510
+ S --> B{Beta?}
511
+ S --> C[(Store)]
512
+ A --> J[[Join]]
513
+ B --> J
514
+ C --> J
515
+ J -->|cycle back| S`
516
+ const layout = layoutFlowchartDiagram(content)
517
+ const feedback = layout.routes.find((route) => route.edge.from === "J" && route.edge.to === "S")!
518
+ const label = flowchartEdgeLabelLayout(feedback.points, feedback.edge.label, stringWidth)
519
+ const labelBounds = { left: label.point.x, top: label.point.y, width: label.width, height: label.height }
520
+
521
+ for (const id of ["A", "B", "C"]) expect(boundsIntersect(labelBounds, layout.bounds.get(id)!)).toBe(false)
522
+ expect(renderFlowchartDiagram(content)).toContain("cycle back")
523
+ })
524
+
525
+ test("routes horizontal feedback edges around sibling nodes", () => {
526
+ for (const direction of ["LR", "RL"] as const) {
527
+ const layout = layoutFlowchartDiagram(`flowchart ${direction}
528
+ S[Start] --> D{Ready?}
529
+ D --> O[Output]
530
+ D --> R[Retry]
531
+ R --> S`)
532
+ const feedback = layout.routes.find((route) => route.edge.from === "R" && route.edge.to === "S")!
533
+
534
+ expect(routeIntersectsBounds(feedback, layout.bounds.get("O")!)).toBe(false)
535
+ }
536
+ })
537
+
538
+ test("keeps compact vertical fan-in arrowheads pointed at the target", () => {
539
+ const content = `flowchart TD
540
+ A[Left] -->|left| C[Merge]
541
+ B[Right] -->|right| C`
542
+ const layout = layoutFlowchartDiagram(content, { compact: true })
543
+
544
+ for (const route of layout.routes) {
545
+ const beforeTarget = route.points.at(-2)!
546
+ const target = route.points.at(-1)!
547
+ expect(beforeTarget.x).toBe(target.x)
548
+ expect(beforeTarget.y).toBeLessThan(target.y)
549
+ }
550
+ expect(renderFlowchartDiagram(content, { compact: true })).toContain("▼")
551
+ })
552
+
553
+ test("routes same-rank vertical-flow edges into the target side", () => {
554
+ const layout = layoutFlowchartDiagram(`flowchart TD
555
+ B[Start] --> D{Choose}
556
+ D --> E[[Primary]]
557
+ D --> F[Fallback]
558
+ E --> B
559
+ F --> E`)
560
+ const route = layout.routes.find((candidate) => candidate.edge.from === "F" && candidate.edge.to === "E")!
561
+ const beforeTarget = route.points.at(-2)!
562
+ const target = route.points.at(-1)!
563
+
564
+ expect(beforeTarget.y).toBe(target.y)
565
+ expect(beforeTarget.x).toBeGreaterThan(target.x)
566
+ })
567
+
568
+ test("renders parallel same-endpoint edges without losing labels", () => {
569
+ const content = `flowchart LR
570
+ A[Source] -->|first| B[Target]
571
+ A -->|second| B`
572
+ const output = renderFlowchartDiagram(content)
573
+ const parallel = layoutFlowchartDiagram(content).routes
574
+
575
+ expect(output).toContain("first")
576
+ expect(output).toContain("second")
577
+ expect(output).toMatch(/[▲▼◀▶]/)
578
+ expect(new Set(parallel.map((route) => JSON.stringify(route.points))).size).toBe(2)
579
+ })
580
+
581
+ test("keeps reciprocal edge labels disjoint from nodes, labels, and other routes", () => {
582
+ const content = `flowchart TD
583
+ A[A] -->|forward_label| B[B]
584
+ B -->|backward_label| A`
585
+
586
+ expectFlowchartLabelsUnobstructed(content)
587
+ })
588
+
589
+ test("keeps labeled parallel BT edges on distinct unobstructed routes", () => {
590
+ const content = `flowchart BT
591
+ F3_1[Node F3_1]
592
+ F3_4[Node F3_4]
593
+ F3_3[Node F3_3]
594
+ F3_2[Node F3_2]
595
+ F3_3 -->|flow_edge_3_0| F3_4
596
+ F3_2 -->|flow_edge_3_1| F3_3
597
+ F3_1 -->|flow_edge_3_5| F3_4
598
+ F3_1 -->|flow_edge_3_6| F3_4
599
+ F3_2 -->|flow_edge_3_7| F3_1
600
+ F3_1 -->|flow_edge_3_8| F3_4`
601
+ const layout = expectFlowchartLabelsUnobstructed(content)
602
+ const parallel = layout.routes.filter((route) => route.edge.from === "F3_1" && route.edge.to === "F3_4")
603
+
604
+ expect(parallel).toHaveLength(3)
605
+ expect(new Set(parallel.map((route) => JSON.stringify(route.points))).size).toBe(3)
606
+ })
607
+
608
+ test("keeps every label in the cyclic parallel BT fuzz fixture", () => {
609
+ const content = `flowchart BT
610
+ F3_0[Node F3_0]
611
+ F3_1[Node F3_1]
612
+ F3_2[Node F3_2]
613
+ F3_3[Node F3_3]
614
+ F3_4[Node F3_4]
615
+ F3_0 -->|flow_edge_3_0| F3_1
616
+ F3_1 -->|flow_edge_3_1| F3_2
617
+ F3_2 -->|flow_edge_3_2| F3_3
618
+ F3_3 -->|flow_edge_3_3| F3_4
619
+ F3_0 -->|flow_edge_3_4| F3_4
620
+ F3_0 -->|flow_edge_3_5| F3_0
621
+ F3_1 -->|flow_edge_3_6| F3_4
622
+ F3_3 -->|flow_edge_3_7| F3_0
623
+ F3_1 -->|flow_edge_3_8| F3_4
624
+ F3_3 -->|flow_edge_3_9| F3_0`
625
+
626
+ expectFlowchartLabelsUnobstructed(content)
627
+ })
628
+
629
+ test("keeps every label in the cyclic parallel TB fuzz fixture", () => {
630
+ const content = `flowchart TB
631
+ F9_0[Node F9_0]
632
+ F9_1[Node F9_1]
633
+ F9_2[Node F9_2]
634
+ F9_3[Node F9_3]
635
+ F9_4[Node F9_4]
636
+ F9_5[Node F9_5]
637
+ F9_6[Node F9_6]
638
+ F9_0 -->|flow_edge_9_0| F9_1
639
+ F9_1 -->|flow_edge_9_1| F9_2
640
+ F9_2 -->|flow_edge_9_2| F9_3
641
+ F9_3 -->|flow_edge_9_3| F9_4
642
+ F9_4 -->|flow_edge_9_4| F9_5
643
+ F9_5 -->|flow_edge_9_5| F9_6
644
+ F9_2 -->|flow_edge_9_6| F9_3
645
+ F9_1 -->|flow_edge_9_7| F9_0
646
+ F9_5 -->|flow_edge_9_8| F9_6
647
+ F9_6 -->|flow_edge_9_9| F9_3
648
+ F9_0 -->|flow_edge_9_10| F9_1
649
+ F9_1 -->|flow_edge_9_11| F9_5`
650
+
651
+ expectFlowchartLabelsUnobstructed(content)
652
+ })
653
+
654
+ test("keeps routes outside unrelated nodes in the cyclic TB fuzz fixture", () => {
655
+ const content = `flowchart TB
656
+ F7_0[Node F7_0]
657
+ F7_1[Node F7_1]
658
+ F7_2[Node F7_2]
659
+ F7_3[Node F7_3]
660
+ F7_4[Node F7_4]
661
+ F7_5[Node F7_5]
662
+ F7_6[Node F7_6]
663
+ F7_7[Node F7_7]
664
+ F7_0 -->|flow_edge_7_0| F7_1
665
+ F7_1 -->|flow_edge_7_1| F7_2
666
+ F7_2 -->|flow_edge_7_2| F7_3
667
+ F7_3 -->|flow_edge_7_3| F7_4
668
+ F7_4 -->|flow_edge_7_4| F7_5
669
+ F7_5 -->|flow_edge_7_5| F7_6
670
+ F7_6 -->|flow_edge_7_6| F7_7
671
+ F7_7 -->|flow_edge_7_7| F7_2
672
+ F7_3 -->|flow_edge_7_8| F7_3
673
+ F7_0 -->|flow_edge_7_9| F7_4
674
+ F7_5 -->|flow_edge_7_10| F7_6
675
+ F7_4 -->|flow_edge_7_11| F7_2`
676
+
677
+ expectFlowchartLabelsUnobstructed(content)
678
+ })
679
+
680
+ test("keeps every label clear in the cyclic BT fuzz fixture", () => {
681
+ const content = `flowchart BT
682
+ F130_0[Node F130_0]
683
+ F130_1[Node F130_1]
684
+ F130_2[Node F130_2]
685
+ F130_3[Node F130_3]
686
+ F130_4[Node F130_4]
687
+ F130_5[Node F130_5]
688
+ F130_0 -->|flow_edge_130_0| F130_1
689
+ F130_1 -->|flow_edge_130_1| F130_2
690
+ F130_2 -->|flow_edge_130_2| F130_3
691
+ F130_3 -->|flow_edge_130_3| F130_4
692
+ F130_4 -->|flow_edge_130_4| F130_5
693
+ F130_2 -->|flow_edge_130_5| F130_1
694
+ F130_4 -->|flow_edge_130_6| F130_3
695
+ F130_3 -->|flow_edge_130_7| F130_1
696
+ F130_5 -->|flow_edge_130_8| F130_5
697
+ F130_2 -->|flow_edge_130_9| F130_0
698
+ F130_4 -->|flow_edge_130_10| F130_0
699
+ F130_4 -->|flow_edge_130_11| F130_0`
700
+
701
+ expectFlowchartLabelsUnobstructed(content)
702
+ })
703
+
704
+ test("keeps translated top feedback labels distinct in the cyclic BT fuzz fixture", () => {
705
+ const content = `flowchart BT
706
+ F141_0[Node F141_0]
707
+ F141_1[Node F141_1]
708
+ F141_2[Node F141_2]
709
+ F141_3[Node F141_3]
710
+ F141_4[Node F141_4]
711
+ F141_5[Node F141_5]
712
+ F141_6[Node F141_6]
713
+ F141_7[Node F141_7]
714
+ F141_0 -->|flow_edge_141_0| F141_1
715
+ F141_1 -->|flow_edge_141_1| F141_2
716
+ F141_2 -->|flow_edge_141_2| F141_3
717
+ F141_3 -->|flow_edge_141_3| F141_4
718
+ F141_4 -->|flow_edge_141_4| F141_5
719
+ F141_5 -->|flow_edge_141_5| F141_6
720
+ F141_6 -->|flow_edge_141_6| F141_7
721
+ F141_7 -->|flow_edge_141_7| F141_1
722
+ F141_4 -->|flow_edge_141_8| F141_4
723
+ F141_3 -->|flow_edge_141_9| F141_0
724
+ F141_3 -->|flow_edge_141_10| F141_2
725
+ F141_7 -->|flow_edge_141_11| F141_6
726
+ F141_7 -->|flow_edge_141_12| F141_2
727
+ F141_7 -->|flow_edge_141_13| F141_5`
728
+
729
+ expectFlowchartLabelsUnobstructed(content)
730
+ })
731
+
732
+ test("keeps feedback labels outside their endpoint nodes in the cyclic BT fuzz fixture", () => {
733
+ const content = `flowchart BT
734
+ F223_0[Node F223_0]
735
+ F223_1[Node F223_1]
736
+ F223_2[Node F223_2]
737
+ F223_3[Node F223_3]
738
+ F223_4[Node F223_4]
739
+ F223_5[Node F223_5]
740
+ F223_6[Node F223_6]
741
+ F223_0 -->|flow_edge_223_0| F223_1
742
+ F223_1 -->|flow_edge_223_1| F223_2
743
+ F223_2 -->|flow_edge_223_2| F223_3
744
+ F223_3 -->|flow_edge_223_3| F223_4
745
+ F223_4 -->|flow_edge_223_4| F223_5
746
+ F223_5 -->|flow_edge_223_5| F223_6
747
+ F223_5 -->|flow_edge_223_6| F223_2
748
+ F223_2 -->|flow_edge_223_7| F223_6
749
+ F223_3 -->|flow_edge_223_8| F223_6`
750
+
751
+ expectFlowchartLabelsUnobstructed(content)
752
+ })
753
+
754
+ test("keeps self-loop labels outside their node in the cyclic TB fuzz fixture", () => {
755
+ const content = `flowchart TB
756
+ F238_0[Node F238_0]
757
+ F238_1[Node F238_1]
758
+ F238_2[Node F238_2]
759
+ F238_3[Node F238_3]
760
+ F238_4[Node F238_4]
761
+ F238_5[Node F238_5]
762
+ F238_0 -->|flow_edge_238_0| F238_1
763
+ F238_1 -->|flow_edge_238_1| F238_2
764
+ F238_2 -->|flow_edge_238_2| F238_3
765
+ F238_3 -->|flow_edge_238_3| F238_4
766
+ F238_4 -->|flow_edge_238_4| F238_5
767
+ F238_1 -->|flow_edge_238_5| F238_2
768
+ F238_3 -->|flow_edge_238_6| F238_3
769
+ F238_2 -->|flow_edge_238_7| F238_0
770
+ F238_1 -->|flow_edge_238_8| F238_5
771
+ F238_1 -->|flow_edge_238_9| F238_1
772
+ F238_4 -->|flow_edge_238_10| F238_4
773
+ F238_4 -->|flow_edge_238_11| F238_0
774
+ F238_2 -->|flow_edge_238_12| F238_2`
775
+
776
+ expectFlowchartLabelsUnobstructed(content)
777
+ })
778
+
779
+ test.each(["LR", "RL", "TD", "TB", "BT"] as const)(
780
+ "keeps multiple %s self-loop labels clear amid surrounding cycles",
781
+ (direction) => {
782
+ const content = `flowchart ${direction}
783
+ A[Alpha] -->|entry_${direction}| B[Beta]
784
+ B -->|loop_${direction}_0| B
785
+ B -->|loop_${direction}_1| B
786
+ B -->|loop_${direction}_2| B
787
+ B -->|exit_${direction}| C[Gamma]
788
+ C -->|cycle_${direction}| A`
789
+ const layout = expectFlowchartLabelsUnobstructed(content)
790
+ const loops = layout.routes.filter((route) => route.edge.from === "B" && route.edge.to === "B")
791
+
792
+ expect(loops).toHaveLength(3)
793
+ expect(new Set(loops.map((route) => JSON.stringify(route.points))).size).toBe(3)
794
+ },
795
+ )
796
+
797
+ test.each(
798
+ (["LR", "RL", "TD", "TB", "BT"] as const).flatMap((direction) =>
799
+ ([2, 3, 4] as const).map((count) => ({ direction, count })),
800
+ ),
801
+ )("keeps $count parallel $direction labels clear amid surrounding cycles", ({ direction, count }) => {
802
+ const parallel = Array.from({ length: count }, (_, index) => ` A -->|parallel_${direction}_${count}_${index}| B`)
803
+ const content = [
804
+ `flowchart ${direction}`,
805
+ " S[Source] -->|entry| A[Alpha]",
806
+ ...parallel,
807
+ " B[Beta] -->|exit| T[Target]",
808
+ " B -->|reciprocal| A",
809
+ " T -->|cycle| S",
810
+ ].join("\n")
811
+ const layout = expectFlowchartLabelsUnobstructed(content)
812
+ const parallelRoutes = layout.routes.filter((route) => route.edge.from === "A" && route.edge.to === "B")
813
+
814
+ expect(parallelRoutes).toHaveLength(count)
815
+ expect(new Set(parallelRoutes.map((route) => JSON.stringify(route.points))).size).toBe(count)
816
+ })
817
+
818
+ test("keeps three parallel multiline edges legible in both orientations", () => {
819
+ const horizontal = renderFlowchartDiagram(`flowchart LR
820
+ A[Source] -->|first 1<br/>first 2<br/>first 3<br/>first 4| B[Target]
821
+ A -->|second 1<br/>second 2<br/>second 3<br/>second 4| B
822
+ A -->|third 1<br/>third 2<br/>third 3<br/>third 4| B`)
823
+ const vertical = renderFlowchartDiagram(`flowchart TD
824
+ A[Source] -->|first lane<br/>first two| B[Target]
825
+ A -->|second lane<br/>second two| B
826
+ A -->|third lane<br/>third two| B`)
827
+
828
+ for (const label of ["second 1", "second 2", "second 3", "second 4", "third 1", "third 2"]) {
829
+ expect(horizontal).toContain(label)
830
+ }
831
+ for (const label of ["first lane", "first two", "second lane", "second two", "third lane", "third two"]) {
832
+ expect(vertical).toContain(label)
833
+ }
834
+ })
835
+
836
+ test("keeps five parallel multiline edge labels distinct", () => {
837
+ const output = renderFlowchartDiagram(`flowchart TD
838
+ A[Source] -->|one alpha<br/>one beta| B[Target]
839
+ A -->|two alpha<br/>two beta| B
840
+ A -->|three alpha<br/>three beta| B
841
+ A -->|four alpha<br/>four beta| B
842
+ A -->|five alpha<br/>five beta| B`)
843
+
844
+ for (const number of ["one", "two", "three", "four", "five"]) {
845
+ expect(output.match(new RegExp(`${number} alpha`, "g"))).toHaveLength(1)
846
+ expect(output.match(new RegExp(`${number} beta`, "g"))).toHaveLength(1)
847
+ }
848
+ })
849
+
850
+ test("does not reserve label gaps for unlabeled fan-out", () => {
851
+ const output = renderFlowchartDiagram(`flowchart TD
852
+ S[The Boss] --> A[A]
853
+ S --> B[B]
854
+ S --> C[C]
855
+ S --> D[D]
856
+ S --> E[E]
857
+ S --> F[F]
858
+ S --> G[G]
859
+ S --> H[H]
860
+ S --> I[I]
861
+ S --> J[J]`)
862
+
863
+ expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThanOrEqual(100)
864
+ })
865
+
866
+ test("keeps transitive targets below intermediate vertical stages", () => {
867
+ const content = `flowchart TD
868
+ A[Start] --> B[Validate]
869
+ B --> C[Publish]
870
+ A --> C`
871
+ const layout = layoutFlowchartDiagram(content)
872
+ const output = renderFlowchartDiagram(content)
873
+
874
+ expect(layout.bounds.get("C")!.top).toBeGreaterThan(layout.bounds.get("B")!.top)
875
+ expect(output.match(/[▼◀]/g)).toHaveLength(3)
876
+ })
877
+
878
+ test("orders rank nodes to remove crossings between branches", () => {
879
+ const content = `flowchart TD
880
+ A{Question} -->|Path one| B[Step one]
881
+ A -->|Path two| C[Step two]
882
+ B --> D{Check one}
883
+ D -->|No| E{Retry one}
884
+ E -->|No| B
885
+ C --> F{Check two}
886
+ F -->|No| G{Retry two}
887
+ G -->|No| C
888
+ E -->|Yes| H[Rethink]
889
+ G -->|Yes| H
890
+ H --> A
891
+ D -->|Yes| I([Done])
892
+ F -->|Yes| I`
893
+ const layout = layoutFlowchartDiagram(content, { compact: true, layoutMaxWidth: 120 })
894
+ const left = (id: string) => layout.bounds.get(id)!.left
895
+
896
+ expect(left("E")).toBeLessThan(left("I"))
897
+ expect(left("I")).toBeLessThan(left("G"))
898
+ expectDiagram(renderFlowchartDiagram(content, { compact: true, layoutMaxWidth: 120 })).toEqualDiagram(`
899
+ ╭─────────╮
900
+ ╭─╯ ╰─╮
901
+ │ Question │◀──────────────────────────╮
902
+ ╰─╮ ╭─╯ │
903
+ ╰────┬────╯ │
904
+ ╭─ Path one ──┴── Path two ───╮ │
905
+ │ │ │
906
+ ▼ ▼ │
907
+ ╭──────────╮ ╭──────────╮ │
908
+ ╭──── No ─────▶│ Step one │ │ Step two │◀──── No ────┤
909
+ │ ╰─────┬────╯ ╰─────┬────╯ │
910
+ │ │ │ │
911
+ │ │ ╭─╯ │
912
+ │ ▼ ▼ │
913
+ │ ╭─────────╮ ╭─────────╮ │
914
+ │ ╭─╯ ╰─╮ ╭─╯ ╰─╮ │
915
+ │ │ Check one │ │ Check two │ │
916
+ │ ╰─╮ ╭─╯ ╰─╮ ╭─╯ │
917
+ │ ╰────┬────╯ ╰────┬────╯ │
918
+ │ ╭── No ───┴──── Yes ─────┬─── Yes ────┴─── No ───╮ │
919
+ │ │ │ │ │
920
+ │ ▼ │ ▼ │
921
+ │ ╭─────────╮ ▼ ╭─────────╮ │
922
+ │ ╭─╯ ╰─╮ ╭──────╮ ╭─╯ ╰─╮ │
923
+ ╰───┤ Retry one │ │ Done │ │ Retry two ├──┤
924
+ ╰─╮ ╭─╯ ╰──────╯ ╰─╮ ╭─╯ │
925
+ ╰────┬────╯ ╰────┬────╯ │
926
+ │ │ │
927
+ ╰───────── Yes ─────────┬───────── Yes ──────────╯ │
928
+ ▼ │
929
+ ╭─────────╮ │
930
+ │ Rethink ├─────────────────────────────╯
931
+ ╰─────────╯
932
+ `)
933
+ })
934
+
935
+ test("routes transitive horizontal shortcuts around intermediate stages", () => {
936
+ const content = `flowchart LR
937
+ A[Start] --> B[Validate]
938
+ B --> C[Publish]
939
+ A --> C`
940
+ const layout = layoutFlowchartDiagram(content)
941
+ const output = renderFlowchartDiagram(content)
942
+
943
+ expect(layout.bounds.get("C")!.left).toBeGreaterThan(layout.bounds.get("B")!.left)
944
+ expect(output.match(/[▶▼]/g)).toHaveLength(3)
945
+ })
946
+
947
+ test("folds oversized horizontal activity pipelines into a readable vertical layout", () => {
948
+ const output = renderFlowchartDiagram(
949
+ `flowchart LR
950
+ C[ReceiveInput] --> P[Persist ActivityRequested]
951
+ P --> S[Self RunPendingActivity]
952
+ S --> O[OpenCode async task]
953
+ O --> M[Self OutputObserved]
954
+ M --> E[Persist OutputObserved]`,
955
+ { layoutMaxWidth: 120 },
956
+ )
957
+
958
+ expectDiagram(output).toEqualDiagram(`
959
+ ╭──────────────╮
960
+ │ ReceiveInput │
961
+ ╰───────┬──────╯
962
+ │
963
+ │
964
+ │
965
+ ▼
966
+ ╭───────────────────────────╮
967
+ │ Persist ActivityRequested │
968
+ ╰─────────────┬─────────────╯
969
+ │
970
+ │
971
+ │
972
+ ▼
973
+ ╭─────────────────────────╮
974
+ │ Self RunPendingActivity │
975
+ ╰────────────┬────────────╯
976
+ │
977
+ │
978
+ │
979
+ ▼
980
+ ╭─────────────────────╮
981
+ │ OpenCode async task │
982
+ ╰──────────┬──────────╯
983
+ │
984
+ │
985
+ │
986
+ ▼
987
+ ╭─────────────────────╮
988
+ │ Self OutputObserved │
989
+ ╰──────────┬──────────╯
990
+ │
991
+ │
992
+ │
993
+ ▼
994
+ ╭────────────────────────╮
995
+ │ Persist OutputObserved │
996
+ ╰────────────────────────╯
997
+ `)
998
+ })
999
+
1000
+ test("folds oversized horizontal feedback pipelines without losing labeled routes", () => {
1001
+ const output = renderFlowchartDiagram(
1002
+ `flowchart LR
1003
+ C[Commands] --> A[AgentThread activation]
1004
+ A -->|persist facts| J[(AgentThread journal)]
1005
+ A -->|resume / steer / abort| O[OpenCode session]
1006
+ O -->|observed output| A
1007
+ J -->|visible output requested| R[Reactor]
1008
+ R --> D[Discord]`,
1009
+ { layoutMaxWidth: 120 },
1010
+ )
1011
+
1012
+ expectDiagram(output).toEqualDiagram(`
1013
+ ╭──────────╮
1014
+ │ Commands │
1015
+ ╰─────┬────╯
1016
+ │
1017
+ │
1018
+ │
1019
+ ▼
1020
+ ╭────────────────────────╮
1021
+ │ AgentThread activation │◀───── observed output ─────╮
1022
+ ╰────────────┬───────────╯ │
1023
+ │ │
1024
+ ╭───── persist facts ──────┴── resume / steer / abort ──╮ │
1025
+ │ │ │
1026
+ ▼ │ │
1027
+ ╭─────────────────────╮ ▼ │
1028
+ ├─────────────────────┤ ╭──────────────────╮ │
1029
+ │ AgentThread journal │ │ OpenCode session ├──╯
1030
+ ├─────────────────────┤ ╰──────────────────╯
1031
+ ╰──────────┬──────────╯
1032
+ │
1033
+ ╰ visible output requested ╮
1034
+ │
1035
+ ▼
1036
+ ╭─────────╮
1037
+ │ Reactor │
1038
+ ╰────┬────╯
1039
+ │
1040
+ │
1041
+ │
1042
+ ▼
1043
+ ╭─────────╮
1044
+ │ Discord │
1045
+ ╰─────────╯
1046
+ `)
1047
+ })
1048
+
1049
+ test("wraps the real deployment chart responsively without losing content or geometry", () => {
1050
+ const expected = new Map([
1051
+ [60, { width: 82, height: 108 }],
1052
+ [80, { width: 97, height: 85 }],
1053
+ [120, { width: 143, height: 77 }],
1054
+ [160, { width: 163, height: 69 }],
1055
+ ])
1056
+ const results = [...expected].map(([budget, dimensions]) => {
1057
+ const result = expectResponsiveFlowchartValid(deploymentArchitectureSource, budget)
1058
+ expect(result.dimensions).toEqual(dimensions)
1059
+ for (const frame of result.layout.subgraphBounds.values()) {
1060
+ for (const other of result.layout.subgraphBounds.values()) {
1061
+ if (frame !== other) expect(boundsIntersect(frame, other)).toBe(false)
1062
+ }
1063
+ }
1064
+ return result.dimensions
1065
+ })
1066
+
1067
+ for (let index = 1; index < results.length; index++) {
1068
+ expect(results[index - 1]!.width).toBeLessThan(results[index]!.width)
1069
+ }
1070
+ })
1071
+
1072
+ test.each([7, 9])("wraps generated %s-node Unicode subgraph ranks across width targets", (count) => {
1073
+ const results = [60, 80, 120].map(
1074
+ (budget) => expectResponsiveFlowchartValid(generatedWideRankFlowchart(count), budget).dimensions,
1075
+ )
1076
+
1077
+ for (let index = 1; index < results.length; index++) {
1078
+ expect(results[index - 1]!.width).toBeLessThan(results[index]!.width)
1079
+ expect(results[index - 1]!.height).toBeGreaterThanOrEqual(results[index]!.height)
1080
+ }
1081
+ })
1082
+
1083
+ test("keeps responsive local-direction subgraphs clear of sibling nodes", () => {
1084
+ const layout = layoutFlowchartDiagram(
1085
+ `flowchart BT
1086
+ N0[Outside zero]
1087
+ subgraph Outer
1088
+ N2[Two]
1089
+ subgraph Inner
1090
+ direction LR
1091
+ N3[Three]
1092
+ N4[Four]
1093
+ end
1094
+ N5[X]
1095
+ end
1096
+ N7[Outside seven]
1097
+ N7 --> N2
1098
+ N2 -->|label 6| N5
1099
+ N5 --> N4
1100
+ N0 --> N7`,
1101
+ { compact: true, layoutMaxWidth: 35 },
1102
+ )
1103
+ const nodes = [...layout.bounds.values()]
1104
+
1105
+ for (let left = 0; left < nodes.length; left++) {
1106
+ for (let right = left + 1; right < nodes.length; right++) {
1107
+ expect(boundsIntersect(nodes[left]!, nodes[right]!)).toBe(false)
1108
+ }
1109
+ }
1110
+ })
1111
+
1112
+ test("keeps external nodes outside local-direction subgraph frames", () => {
1113
+ const layout = layoutFlowchartDiagram(
1114
+ `flowchart LR
1115
+ Input([Input]) --> Parse
1116
+ subgraph Outer[Outer orchestration]
1117
+ direction RL
1118
+ subgraph Inner[Inner pipeline]
1119
+ direction TD
1120
+ Parse[Parse request] --> Validate{Valid?}
1121
+ Validate -->|yes| Cache[(Cache)]
1122
+ Cache -->|stale| Validate
1123
+ end
1124
+ Validate --> Dispatch[[Dispatch work]]
1125
+ Dispatch -->|requeue| Parse
1126
+ end
1127
+ Dispatch -. result .-> Output([Output])
1128
+ Output -->|audit| Cache`,
1129
+ { compact: true, layoutMaxWidth: 120 },
1130
+ )
1131
+ const outer = layout.subgraphBounds.get("Outer")!
1132
+
1133
+ expect(boundsIntersect(outer, layout.bounds.get("Input")!)).toBe(false)
1134
+ expect(boundsIntersect(outer, layout.bounds.get("Output")!)).toBe(false)
1135
+ })
1136
+
1137
+ test("keeps responsive sibling subgraph frames and long titles disjoint", () => {
1138
+ const layout = layoutFlowchartDiagram(
1139
+ `flowchart TD
1140
+ subgraph Parent
1141
+ direction LR
1142
+ subgraph Left [A deliberately long left group title]
1143
+ direction LR
1144
+ A1[One] --> A2[Two]
1145
+ end
1146
+ subgraph Right [A deliberately long right group title]
1147
+ direction LR
1148
+ B1[Three] --> B2[Four]
1149
+ end
1150
+ A2 --> B1
1151
+ end`,
1152
+ { compact: true, layoutMaxWidth: 35 },
1153
+ )
1154
+
1155
+ expect(boundsIntersect(layout.subgraphBounds.get("Left")!, layout.subgraphBounds.get("Right")!)).toBe(false)
1156
+ })
1157
+
1158
+ test.each([80, 144])("keeps nested deployment groups compact and dependency-ordered at width %s", (width) => {
1159
+ const layout = layoutFlowchartDiagram(
1160
+ `flowchart LR
1161
+ Browser([Browser]) --> Gateway[Gateway]
1162
+ subgraph Cloud[Cloud platform]
1163
+ direction TB
1164
+ subgraph Compute[Compute]
1165
+ API[API service] --> Worker[Background worker]
1166
+ end
1167
+ subgraph Storage[Storage]
1168
+ Database[(Database)]
1169
+ Cache[(Cache)]
1170
+ end
1171
+ API --> Database
1172
+ Worker --> Cache
1173
+ end
1174
+ Gateway --> API
1175
+ Worker --> Result([Result])`,
1176
+ { compact: true, layoutMaxWidth: width },
1177
+ )
1178
+ const cloud = layout.subgraphBounds.get("Cloud")!
1179
+ const compute = layout.subgraphBounds.get("Compute")!
1180
+ const storage = layout.subgraphBounds.get("Storage")!
1181
+ const result = layout.bounds.get("Result")!
1182
+
1183
+ expect(layout.bounds.get("Worker")!.top).toBeGreaterThan(layout.bounds.get("API")!.top)
1184
+ expect(layout.bounds.get("Database")!.centerY).toBe(layout.bounds.get("Cache")!.centerY)
1185
+ expect(storage.top).toBeGreaterThan(compute.top + compute.height - 1)
1186
+ expect(cloud.width).toBeLessThanOrEqual(50)
1187
+ expect([...layout.subgraphBounds.values()].every((frame) => frame.labelSide === "top")).toBe(true)
1188
+ expect(boundsContains(cloud, compute)).toBe(true)
1189
+ expect(boundsContains(cloud, storage)).toBe(true)
1190
+ expect(boundsIntersect(cloud, result)).toBe(false)
1191
+ if (layout.diagram.direction === "TD") expect(result.top).toBeGreaterThan(cloud.top + cloud.height - 1)
1192
+ if (layout.diagram.direction === "LR") expect(result.left).toBeGreaterThan(cloud.left + cloud.width - 1)
1193
+
1194
+ for (const route of layout.routes.filter(
1195
+ (route) =>
1196
+ (route.edge.from === "API" && route.edge.to === "Database") ||
1197
+ (route.edge.from === "Worker" && route.edge.to === "Cache"),
1198
+ )) {
1199
+ for (const point of route.points) {
1200
+ expect(point.x).toBeGreaterThan(cloud.left)
1201
+ expect(point.x).toBeLessThan(cloud.left + cloud.width - 1)
1202
+ expect(point.y).toBeGreaterThan(cloud.top)
1203
+ expect(point.y).toBeLessThan(cloud.top + cloud.height - 1)
1204
+ }
1205
+ }
1206
+ })
1207
+
1208
+ test("keeps responsive labeled fan-out on one rank with a shared source junction", () => {
1209
+ const content = `flowchart LR
1210
+ Request([Request]) --> Gateway[API gateway]
1211
+ Gateway -->|authenticate| Auth[Authentication]
1212
+ Gateway -->|rate limit| Limit[Rate limiter]
1213
+ Gateway -->|cache lookup| Cache[(Response cache)]
1214
+ Auth --> Worker[Request worker]
1215
+ Limit --> Worker
1216
+ Cache --> Worker
1217
+ Worker --> Response([Response])`
1218
+ const layout = layoutFlowchartDiagram(content, { compact: true, layoutMaxWidth: 80 })
1219
+ const branches = layout.routes.filter((route) => route.edge.from === "Gateway")
1220
+ const gateway = layout.bounds.get("Gateway")!
1221
+
1222
+ expect(new Set(["Auth", "Limit", "Cache"].map((id) => layout.bounds.get(id)!.centerY)).size).toBe(1)
1223
+ expect(new Set(branches.map((route) => JSON.stringify(route.points[0]))).size).toBe(1)
1224
+ expect(branches.flatMap((route) => route.points).every((point) => point.y > gateway.top)).toBe(true)
1225
+ for (const label of ["authenticate", "rate limit", "cache lookup"]) {
1226
+ expect(renderFlowchartDiagram(content, { compact: true, layoutMaxWidth: 80 })).toContain(label)
1227
+ }
1228
+ })
1229
+
1230
+ test("does not change parallel routes for a non-binding width target", () => {
1231
+ const diagram = parseMermaidFlowchartDiagram(`flowchart TD
1232
+ A[A] -->|one| B[B]
1233
+ A -->|two| B`)
1234
+ const unconstrained = layoutParsedFlowchartDiagram(diagram, { compact: true })
1235
+ const nonBinding = layoutParsedFlowchartDiagram(diagram, { compact: true, layoutMaxWidth: 1_000 })
1236
+
1237
+ expect(nonBinding.routes.map((route) => route.points)).toEqual(unconstrained.routes.map((route) => route.points))
1238
+ })
1239
+
1240
+ test("keeps responsive fan-out labels inside the width target", () => {
1241
+ const content = `flowchart TD
1242
+ subgraph Group
1243
+ S[Source]
1244
+ S -->|route 0 detail| N0[Node 0]
1245
+ S -->|route 1 detail| N1[Node 1]
1246
+ S -->|route 2 detail| N2[Node 2]
1247
+ S -->|route 3 detail| N3[Node 3]
1248
+ end`
1249
+ const layout = layoutFlowchartDiagram(content, { compact: true, layoutMaxWidth: 30 })
1250
+ const output = renderFlowchartDiagram(content, { compact: true, layoutMaxWidth: 30 })
1251
+
1252
+ for (const route of layout.routes) {
1253
+ const label = flowchartRouteLabelLayout(route, visualLength)
1254
+ expect(label.point.x + label.width).toBeLessThanOrEqual(30)
1255
+ }
1256
+ expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThanOrEqual(34)
1257
+ })
1258
+
1259
+ test("parses Mermaid flowchart nodes and standard arrows", () => {
1260
+ const diagram = parseMermaidFlowchartDiagram(`
1261
+ flowchart TD
1262
+ Start([Start]):::focus --> Form[Collect Details]
1263
+ Form -->|valid| Store[(Orders DB)]:::store
1264
+ Form -- invalid --> Review(Manual Review)
1265
+ Review --> Decision{Approved?}
1266
+ `)
1267
+
1268
+ expect(diagram.direction).toBe("TD")
1269
+ expect(diagram.nodes).toEqual([
1270
+ { id: "Start", label: "Start", shape: "rounded" },
1271
+ { id: "Form", label: "Collect Details", shape: "box" },
1272
+ { id: "Store", label: "Orders DB", shape: "database" },
1273
+ { id: "Review", label: "Manual Review", shape: "rounded" },
1274
+ { id: "Decision", label: "Approved?", shape: "decision" },
1275
+ ])
1276
+ expect(diagram.edges).toEqual([
1277
+ { from: "Start", to: "Form", label: "" },
1278
+ { from: "Form", to: "Store", label: "valid" },
1279
+ { from: "Form", to: "Review", label: "invalid" },
1280
+ { from: "Review", to: "Decision", label: "" },
1281
+ ])
1282
+ })
1283
+
1284
+ test("decodes HTML entities in node and edge labels", () => {
1285
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1286
+ A[HMAC verify &lt;3s &amp; continue] -->|result &#x2265; 1| B[Done]`)
1287
+
1288
+ expect(diagram.nodes.find((node) => node.id === "A")?.label).toBe("HMAC verify <3s & continue")
1289
+ expect(diagram.edges[0]?.label).toBe("result ≥ 1")
1290
+ })
1291
+
1292
+ test("preserves quoted multiline edge labels", () => {
1293
+ const diagram = parseMermaidFlowchartDiagram(`flowchart TD
1294
+ A -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>A --> B"| B`)
1295
+
1296
+ expect(diagram.edges).toEqual([
1297
+ {
1298
+ from: "A",
1299
+ to: "B",
1300
+ label: "fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>A --> B",
1301
+ },
1302
+ ])
1303
+ })
1304
+
1305
+ test("parses and renders each edge in a chained flowchart statement", () => {
1306
+ const content = `flowchart LR
1307
+ API --> Worker --> DB[(Database)]`
1308
+ const diagram = parseMermaidFlowchartDiagram(content)
1309
+ const output = renderFlowchartDiagram(content, { compact: true })
1310
+
1311
+ expect(diagram.nodes).toEqual([
1312
+ { id: "API", label: "API", shape: "box" },
1313
+ { id: "Worker", label: "Worker", shape: "box" },
1314
+ { id: "DB", label: "Database", shape: "database" },
1315
+ ])
1316
+ expect(diagram.edges).toEqual([
1317
+ { from: "API", to: "Worker", label: "" },
1318
+ { from: "Worker", to: "DB", label: "" },
1319
+ ])
1320
+ expectDiagram(output).toEqualDiagram(`
1321
+ ╭──────────╮
1322
+ ╭─────╮ ╭────────╮ ├──────────┤
1323
+ │ API ├───▶│ Worker ├───▶│ Database │
1324
+ ╰─────╯ ╰────────╯ ├──────────┤
1325
+ ╰──────────╯
1326
+ `)
1327
+ })
1328
+
1329
+ test("preserves labels and styles on every edge in a chain", () => {
1330
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1331
+ A -->|plain| B -.->|retry| C ==>|done| D`)
1332
+
1333
+ expect(diagram.edges).toEqual([
1334
+ { from: "A", to: "B", label: "plain" },
1335
+ { from: "B", to: "C", label: "retry", style: "dashed" },
1336
+ { from: "C", to: "D", label: "done", style: "thick" },
1337
+ ])
1338
+ })
1339
+
1340
+ test("expands & node groups into fan-in and fan-out edges", () => {
1341
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1342
+ N[Native] & M[Mapped] & O --> LM["LanguageModel"]
1343
+ LM -->|prepare| REQ & LOG`)
1344
+
1345
+ expect(diagram.nodes).toEqual([
1346
+ { id: "N", label: "Native", shape: "box" },
1347
+ { id: "M", label: "Mapped", shape: "box" },
1348
+ { id: "O", label: "O", shape: "box" },
1349
+ { id: "LM", label: "LanguageModel", shape: "box" },
1350
+ { id: "REQ", label: "REQ", shape: "box" },
1351
+ { id: "LOG", label: "LOG", shape: "box" },
1352
+ ])
1353
+ expect(diagram.edges).toEqual([
1354
+ { from: "N", to: "LM", label: "" },
1355
+ { from: "M", to: "LM", label: "" },
1356
+ { from: "O", to: "LM", label: "" },
1357
+ { from: "LM", to: "REQ", label: "prepare" },
1358
+ { from: "LM", to: "LOG", label: "prepare" },
1359
+ ])
1360
+ })
1361
+
1362
+ test("expands & groups on both sides of an edge and through a chain", () => {
1363
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1364
+ A & B --> C & D --> E`)
1365
+
1366
+ expect(diagram.edges).toEqual([
1367
+ { from: "A", to: "C", label: "" },
1368
+ { from: "A", to: "D", label: "" },
1369
+ { from: "B", to: "C", label: "" },
1370
+ { from: "B", to: "D", label: "" },
1371
+ { from: "C", to: "E", label: "" },
1372
+ { from: "D", to: "E", label: "" },
1373
+ ])
1374
+ })
1375
+
1376
+ test("declares every node of a bare & group inside the current subgraph", () => {
1377
+ const diagram = parseMermaidFlowchartDiagram(`flowchart TD
1378
+ subgraph Runtime
1379
+ A[Alpha] & B[Beta]:::focus
1380
+ end
1381
+ A --> B`)
1382
+
1383
+ expect(diagram.nodes).toEqual([
1384
+ { id: "A", label: "Alpha", shape: "box" },
1385
+ { id: "B", label: "Beta", shape: "box" },
1386
+ ])
1387
+ expect(diagram.subgraphs?.[0]?.nodeIds).toEqual(["A", "B"])
1388
+ })
1389
+
1390
+ test("keeps & inside quoted or bracketed labels as label text", () => {
1391
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1392
+ A["Fetch & parse"] & B[R&D] --> C[Done &amp; dusted]`)
1393
+
1394
+ expect(diagram.nodes).toEqual([
1395
+ { id: "A", label: "Fetch & parse", shape: "box" },
1396
+ { id: "B", label: "R&D", shape: "box" },
1397
+ { id: "C", label: "Done & dusted", shape: "box" },
1398
+ ])
1399
+ expect(diagram.edges).toEqual([
1400
+ { from: "A", to: "C", label: "" },
1401
+ { from: "B", to: "C", label: "" },
1402
+ ])
1403
+ })
1404
+
1405
+ test("keeps & inside edge labels as label text", () => {
1406
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1407
+ X[a & b] -->|x & y| Y`)
1408
+
1409
+ expect(diagram.nodes.find((node) => node.id === "X")?.label).toBe("a & b")
1410
+ expect(diagram.edges).toEqual([{ from: "X", to: "Y", label: "x & y" }])
1411
+ })
1412
+
1413
+ test("treats apostrophes in labels as text rather than string delimiters", () => {
1414
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1415
+ CS[Console's own schema copy] -. validates .-> CFG
1416
+ A[Bob's] & B[Al's] --> C[it's done; ship]`)
1417
+
1418
+ expect(diagram.nodes).toEqual([
1419
+ { id: "CS", label: "Console's own schema copy", shape: "box" },
1420
+ { id: "CFG", label: "CFG", shape: "box" },
1421
+ { id: "A", label: "Bob's", shape: "box" },
1422
+ { id: "B", label: "Al's", shape: "box" },
1423
+ { id: "C", label: "it's done; ship", shape: "box" },
1424
+ ])
1425
+ expect(diagram.edges).toEqual([
1426
+ { from: "CS", to: "CFG", label: "validates", style: "dashed" },
1427
+ { from: "A", to: "C", label: "" },
1428
+ { from: "B", to: "C", label: "" },
1429
+ ])
1430
+ })
1431
+
1432
+ test("rejects empty & group members", () => {
1433
+ for (const statement of ["A & --> B", "& A --> B", "A --> B &", "A &"]) {
1434
+ expect(() => parseMermaidFlowchartDiagram(`flowchart LR\n ${statement}`)).toThrow(
1435
+ `Unsupported syntax in flowchart diagram at line 2: "${statement}"`,
1436
+ )
1437
+ }
1438
+ })
1439
+
1440
+ test("renders a fan-in expressed with & the same as separate edge statements", () => {
1441
+ const grouped = renderFlowchartDiagram(`flowchart LR
1442
+ N & M & O --> LM[LanguageModel] --> REQ[LLMRequest]`)
1443
+ const separate = renderFlowchartDiagram(`flowchart LR
1444
+ N --> LM[LanguageModel]
1445
+ M --> LM
1446
+ O --> LM
1447
+ LM --> REQ[LLMRequest]`)
1448
+
1449
+ expect(grouped).toBe(separate)
1450
+ expect(grouped).toContain("LanguageModel")
1451
+ })
1452
+
1453
+ test("parses chained undirected solid edges", () => {
1454
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1455
+ A --- B --- C`)
1456
+
1457
+ expect(diagram.edges).toEqual([
1458
+ { from: "A", to: "B", label: "", arrowhead: false },
1459
+ { from: "B", to: "C", label: "", arrowhead: false },
1460
+ ])
1461
+ })
1462
+
1463
+ test("parses labeled undirected dashed and bidirectional edges", () => {
1464
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1465
+ DB[(Durable Object SQLite)]
1466
+ API[Slack API]
1467
+ DB -. no shared transaction .- API
1468
+ API <--> DB`)
1469
+
1470
+ expect(diagram.edges).toEqual([
1471
+ { from: "DB", to: "API", label: "no shared transaction", style: "dashed", arrowhead: false },
1472
+ { from: "API", to: "DB", label: "", sourceArrowhead: true },
1473
+ ])
1474
+ const dashedOutput = renderFlowchartDiagram(`flowchart LR
1475
+ DB[(Durable Object SQLite)] -. no shared transaction .- API[Slack API]`)
1476
+ const bidirectionalOutput = renderFlowchartDiagram(`flowchart LR
1477
+ DB[(Durable Object SQLite)] <--> API[Slack API]`)
1478
+ expect(dashedOutput).toContain("no shared transaction")
1479
+ expect(bidirectionalOutput.match(/[◀▶▲▼]/g)?.length).toBeGreaterThanOrEqual(2)
1480
+ })
1481
+
1482
+ test("renders the volume persistence diagram with an undirected solid edge", () => {
1483
+ const content = `flowchart LR
1484
+ subgraph durable [Durable — survives everything]
1485
+ V[(Volume ws-wor_abc<br/>mounted at /workspace)]
1486
+ R[our row: id, provider]
1487
+ end
1488
+ subgraph ephemeral [Ephemeral — dies freely]
1489
+ S1[Sandbox #1] -. mounts .-> V
1490
+ S2[Sandbox #2<br/>Tuesday] -. mounts same .-> V
1491
+ X[apt-get installs,<br/>~/.cache, /tmp]
1492
+ end
1493
+ S1 --- X
1494
+ style X stroke-dasharray: 5 5`
1495
+ const diagram = parseMermaidFlowchartDiagram(content)
1496
+ const layout = layoutParsedFlowchartDiagram(diagram, { compact: true })
1497
+ const grid = drawParsedFlowchartDiagramGrid(diagram, { compact: true })
1498
+ const output = renderFlowchartDiagram(content, { compact: true })
1499
+ const route = layout.routes.find((route) => route.edge.from === "S1" && route.edge.to === "X")!
1500
+ const end = route.points.at(-1)!
1501
+
1502
+ expect(diagram.edges.at(-1)).toEqual({ from: "S1", to: "X", label: "", arrowhead: false })
1503
+ expect(route.points.length).toBeGreaterThan(1)
1504
+ expect(grid.getCell(end.x, end.y)?.char).not.toMatch(/[▶▼◀▲]/)
1505
+ expectDiagram(output).toContainInOrder("Sandbox #1", "apt-get installs,", "~/.cache, /tmp")
1506
+ })
1507
+
1508
+ test.each(["LR", "RL", "TD", "BT"] as const)(
1509
+ "keeps undirected %s routes continuous up to the target",
1510
+ (direction) => {
1511
+ const content = `flowchart ${direction}\n A[Alpha] --- B[(Store)]`
1512
+ const diagram = parseMermaidFlowchartDiagram(content)
1513
+ const layout = layoutParsedFlowchartDiagram(diagram)
1514
+ const grid = drawParsedFlowchartDiagramGrid(diagram)
1515
+ const route = layout.routes[0]!
1516
+
1517
+ expect(terminalPointsTowardBounds(route, layout.bounds.get("B")!)).toBe(true)
1518
+ for (let index = 1; index < route.points.length; index++) {
1519
+ const from = route.points[index - 1]!
1520
+ const to = route.points[index]!
1521
+ const length = Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
1522
+ for (let offset = 0; offset <= length; offset++) {
1523
+ const x = from.x + Math.sign(to.x - from.x) * offset
1524
+ const y = from.y + Math.sign(to.y - from.y) * offset
1525
+ expect(grid.getCell(x, y)?.char).not.toBe(" ")
1526
+ }
1527
+ }
1528
+ expect(grid.getCell(route.points.at(-1)!.x, route.points.at(-1)!.y)?.char).toMatch(/[─│]/)
1529
+ },
1530
+ )
1531
+
1532
+ test("keeps independent horizontal fan-out groups on distinct routes", () => {
1533
+ const content = `flowchart LR
1534
+ A[A] -->|A to X| X[X]
1535
+ A -->|A to Y| Y[Y]
1536
+ B[B] -->|B to Y| Y
1537
+ B -->|B to Z| Z[Z]`
1538
+ const output = renderFlowchartDiagram(content)
1539
+ const routes = layoutFlowchartDiagram(content).routes
1540
+ const routeByLabel = new Map(routes.map((route) => [route.edge.label, route]))
1541
+
1542
+ for (const label of ["A to X", "A to Y", "B to Y", "B to Z"]) {
1543
+ expect(output.match(new RegExp(label, "g"))).toHaveLength(1)
1544
+ }
1545
+ expect(routeByLabel.get("A to X")!.points[1]!.x).toBe(routeByLabel.get("A to Y")!.points[1]!.x)
1546
+ expect(routeByLabel.get("B to Y")!.points[1]!.x).toBe(routeByLabel.get("B to Z")!.points[1]!.x)
1547
+ expect(routeByLabel.get("A to Y")!.points[1]!.x).not.toBe(routeByLabel.get("B to Y")!.points[1]!.x)
1548
+ expect(routeByLabel.get("A to Y")!.points.at(-1)).not.toEqual(routeByLabel.get("B to Y")!.points.at(-1))
1549
+ })
1550
+
1551
+ test("parses and renders inline dashed edge labels", () => {
1552
+ const content = `flowchart TD
1553
+ CS[conformance suite<br/>same test cases pin every driver] -.verifies.-> LS
1554
+ CS -.verifies.-> MS
1555
+ CS -.verifies.-> MEM[memory driver]`
1556
+ const diagram = parseMermaidFlowchartDiagram(content)
1557
+ const output = renderFlowchartDiagram(content, { compact: true })
1558
+
1559
+ expect(diagram.edges).toEqual([
1560
+ { from: "CS", to: "LS", label: "verifies", style: "dashed" },
1561
+ { from: "CS", to: "MS", label: "verifies", style: "dashed" },
1562
+ { from: "CS", to: "MEM", label: "verifies", style: "dashed" },
1563
+ ])
1564
+ expect(output.match(/verifies/g)).toHaveLength(3)
1565
+ expect(output).not.toContain("─ ─")
1566
+ })
1567
+
1568
+ test("uses invisible subgraph links for ordering without rendering them", () => {
1569
+ const content = `flowchart LR
1570
+ subgraph before [Before]
1571
+ T1[read/edit/write/patch<br/>shell/grep/glob] --> F1[FSUtil / node:fs / AppProcess<br/>+ hosted branching in every tool]
1572
+ end
1573
+ subgraph after [After — merged this week]
1574
+ T2[same 8 tools] --> E[Environment<br/>files + spawner]
1575
+ E --> D{driver}
1576
+ D --> L[local<br/>node:fs]
1577
+ D --> M[Modal<br/>sandbox.exec]
1578
+ D --> Mem[memory<br/>tests]
1579
+ end
1580
+ before ~~~ after`
1581
+ const diagram = parseMermaidFlowchartDiagram(content)
1582
+ const layout = layoutParsedFlowchartDiagram(diagram, { compact: true })
1583
+ const output = renderFlowchartDiagram(content, { compact: true })
1584
+
1585
+ expect(diagram.edges.at(-1)).toEqual({ from: "before", to: "after", label: "", orderOnly: true })
1586
+ expect(diagram.nodes.some((node) => node.id === "before" || node.id === "after")).toBe(false)
1587
+ expect(layout.routes).toHaveLength(diagram.edges.length - 1)
1588
+ expect(layout.routes.some((route) => route.edge.orderOnly)).toBe(false)
1589
+ expect(layout.subgraphBounds.get("before")!.left).toBeLessThan(layout.subgraphBounds.get("after")!.left)
1590
+ const chain = ["T2", "E", "D"].map((id) => layout.bounds.get(id)!)
1591
+ expect(chain.map((bounds) => bounds.centerY)).toEqual([chain[0]!.centerY, chain[0]!.centerY, chain[0]!.centerY])
1592
+ for (const route of layout.routes.filter((route) => route.edge.from === "T2" || route.edge.from === "E")) {
1593
+ expect(new Set(route.points.map((point) => point.y)).size).toBe(1)
1594
+ }
1595
+ expect(output).toContain("Before")
1596
+ expect(output).toContain("After — merged this week")
1597
+ })
1598
+
1599
+ test("routes visible subgraph-to-subgraph chains without creating phantom nodes", () => {
1600
+ const content = `flowchart TD
1601
+ subgraph S1["1. provider.transform (seed)"]
1602
+ A1["Catalog model → copy catalog variants"]
1603
+ A2["Custom model → apply package/modelID/limit + seed default variants"]
1604
+ end
1605
+ subgraph S2["2. plugin model.transform"]
1606
+ B["Plugin can replace variants, clear to [], or ignore"]
1607
+ end
1608
+ subgraph S3["3. config model.transform (post)"]
1609
+ C1{"Config sets reasoning or variants?"}
1610
+ C1 -- yes --> C2["Apply explicit config"]
1611
+ C1 -- no --> C3{"Config changed package (or recreated removed model)?"}
1612
+ C3 -- yes --> C4["Respell / reseed variants"]
1613
+ C3 -- no --> C5["Keep current variants"]
1614
+ end
1615
+ S1 --> S2 --> S3`
1616
+ const diagram = parseMermaidFlowchartDiagram(content)
1617
+ expect(diagram.nodes.some((node) => node.id === "S1" || node.id === "S2" || node.id === "S3")).toBe(false)
1618
+
1619
+ for (const layoutMaxWidth of [60, 80, 120]) {
1620
+ const layout = layoutParsedFlowchartDiagram(diagram, { compact: true, layoutMaxWidth })
1621
+ const grid = drawParsedFlowchartDiagramGrid(diagram, { compact: true, layoutMaxWidth })
1622
+ const s1 = layout.subgraphBounds.get("S1")!
1623
+ const s2 = layout.subgraphBounds.get("S2")!
1624
+ const s3 = layout.subgraphBounds.get("S3")!
1625
+
1626
+ expect(s1.top + s1.height).toBeLessThan(s2.top)
1627
+ expect(s2.top + s2.height).toBeLessThan(s3.top)
1628
+
1629
+ for (const [fromId, toId, fromFrame, toFrame] of [
1630
+ ["S1", "S2", s1, s2],
1631
+ ["S2", "S3", s2, s3],
1632
+ ] as const) {
1633
+ const route = layout.routes.find((candidate) => candidate.edge.from === fromId && candidate.edge.to === toId)!
1634
+ const start = route.points[0]!
1635
+ const end = route.points.at(-1)!
1636
+ expect(start.y).toBe(fromFrame.top + fromFrame.height)
1637
+ expect(end.y).toBe(toFrame.top - 1)
1638
+ expect(grid.getCell(start.x, fromFrame.top + fromFrame.height - 1)?.char).toBe("┬")
1639
+ expect(grid.getCell(end.x, end.y)?.char).toBe("▼")
1640
+ }
1641
+ }
1642
+ })
1643
+
1644
+ test("resolves forward, nested, labeled, and upward subgraph endpoints while keeping explicit same-id nodes", () => {
1645
+ const forward = parseMermaidFlowchartDiagram(`flowchart TD
1646
+ Start[Start] --> S1
1647
+ S1 -->|done| Done[Done]
1648
+ subgraph S1["Stage"]
1649
+ W1[Step 1] --> W2[Step 2]
1650
+ end`)
1651
+ expect(forward.nodes.map((node) => node.id)).toEqual(["Start", "Done", "W1", "W2"])
1652
+ const forwardOutput = renderFlowchartDiagram(`flowchart TD
1653
+ Start[Start] --> S1
1654
+ S1 -->|done| Done[Done]
1655
+ subgraph S1["Stage"]
1656
+ W1[Step 1] --> W2[Step 2]
1657
+ end`)
1658
+ expect(forwardOutput).toContain("done")
1659
+
1660
+ const btGrid = drawParsedFlowchartDiagramGrid(
1661
+ parseMermaidFlowchartDiagram(`flowchart BT
1662
+ subgraph S1["First group title"]
1663
+ A1[Alpha]
1664
+ end
1665
+ subgraph S2["Second group title"]
1666
+ B1[Beta]
1667
+ end
1668
+ S1 --> S2`),
1669
+ { compact: true },
1670
+ )
1671
+ const btText = btGrid.toString({ trimTop: true, trimBottom: true })
1672
+ expect(btText).toContain("First group title")
1673
+ expect(btText).toContain("┴")
1674
+ expect(btText).toContain("▲")
1675
+
1676
+ const nestedLayout = layoutFlowchartDiagram(`flowchart TD
1677
+ subgraph Outer["Outer"]
1678
+ Entry[Entry] --> Inner
1679
+ subgraph Inner["Inner"]
1680
+ A[One] --> B[Two]
1681
+ end
1682
+ end`)
1683
+ const outer = nestedLayout.subgraphBounds.get("Outer")!
1684
+ const entryRoute = nestedLayout.routes.find((route) => route.edge.from === "Entry" && route.edge.to === "Inner")!
1685
+ expect(
1686
+ entryRoute.points.every(
1687
+ (point) =>
1688
+ point.x > outer.left &&
1689
+ point.x < outer.left + outer.width - 1 &&
1690
+ point.y > outer.top &&
1691
+ point.y < outer.top + outer.height - 1,
1692
+ ),
1693
+ ).toBe(true)
1694
+
1695
+ const sameId = parseMermaidFlowchartDiagram(`flowchart LR
1696
+ subgraph API
1697
+ API[API Gateway] --> DB[(Postgres)]
1698
+ end`)
1699
+ expect(sameId.nodes.map((node) => node.id)).toEqual(["API", "DB"])
1700
+ const sameIdLayout = layoutParsedFlowchartDiagram(sameId, { compact: true })
1701
+ const apiNode = sameIdLayout.bounds.get("API")!
1702
+ const apiRoute = sameIdLayout.routes[0]!
1703
+ expect(apiRoute.points[0]!.x).toBe(apiNode.left + apiNode.width)
1704
+ })
1705
+
1706
+ test("keeps every node and edge in a long chain distinct and in its subgraph", () => {
1707
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1708
+ subgraph Pipeline
1709
+ A --> B --> C --> D --> E --> F --> G --> H --> I --> J --> K --> L
1710
+ end`)
1711
+
1712
+ expect(diagram.nodes.map((node) => node.id)).toEqual(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"])
1713
+ expect(diagram.edges.map((edge) => `${edge.from}->${edge.to}`)).toEqual([
1714
+ "A->B",
1715
+ "B->C",
1716
+ "C->D",
1717
+ "D->E",
1718
+ "E->F",
1719
+ "F->G",
1720
+ "G->H",
1721
+ "H->I",
1722
+ "I->J",
1723
+ "J->K",
1724
+ "K->L",
1725
+ ])
1726
+ expect(diagram.subgraphs?.[0]?.nodeIds).toEqual(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"])
1727
+ })
1728
+
1729
+ test("parses bare subgraph nodes before a chained edge", () => {
1730
+ const diagram = parseMermaidFlowchartDiagram(`flowchart LR
1731
+ subgraph Services
1732
+ API
1733
+ Worker
1734
+ end
1735
+ API --> Worker --> DB[(Database)]`)
1736
+
1737
+ expect(diagram.nodes.map((node) => node.id)).toEqual(["API", "Worker", "DB"])
1738
+ expect(diagram.edges.map((edge) => [edge.from, edge.to])).toEqual([
1739
+ ["API", "Worker"],
1740
+ ["Worker", "DB"],
1741
+ ])
1742
+ expect(diagram.subgraphs?.[0]?.nodeIds).toEqual(["API", "Worker"])
1743
+ })
1744
+
1745
+ test("parses Mermaid subgraph groups", () => {
1746
+ const diagram = parseMermaidFlowchartDiagram(`
1747
+ flowchart LR
1748
+ subgraph Web [Web App]
1749
+ UI[UI] --> API[API]
1750
+ end
1751
+ subgraph Platform
1752
+ API --> DB[(Database)]
1753
+ end
1754
+ `)
1755
+
1756
+ expect(diagram.subgraphs).toEqual([
1757
+ { id: "Web", label: "Web App", nodeIds: ["UI", "API"], parentId: undefined },
1758
+ { id: "Platform", label: "Platform", nodeIds: ["API", "DB"], parentId: undefined },
1759
+ ])
1760
+ })
1761
+
1762
+ test("parses Mermaid subgraph-local directions", () => {
1763
+ const diagram = parseMermaidFlowchartDiagram(`
1764
+ flowchart TD
1765
+ subgraph Verse
1766
+ direction LR
1767
+ A[A] --> B[B]
1768
+ end
1769
+ `)
1770
+
1771
+ expect(diagram.subgraphs).toEqual([
1772
+ { id: "Verse", label: "Verse", nodeIds: ["A", "B"], parentId: undefined, direction: "LR" },
1773
+ ])
1774
+ })
1775
+
1776
+ test("parses and renders Mermaid subroutine nodes", () => {
1777
+ const content = `
1778
+ flowchart LR
1779
+ Parse[[Parse]] --> Layout[Layout]
1780
+ `
1781
+ const diagram = parseMermaidFlowchartDiagram(content)
1782
+ const output = renderFlowchartDiagram(content)
1783
+
1784
+ expect(diagram.nodes[0]).toEqual({ id: "Parse", label: "Parse", shape: "subroutine" })
1785
+ expectDiagram(output).toContainInOrder("╭─┬─────┬─╮", "│ │Parse│ ├", "╰─┴─────┴─╯")
1786
+ })
1787
+
1788
+ test("parses and renders Mermaid thick edges", () => {
1789
+ const content = `
1790
+ flowchart LR
1791
+ Build[Build] ==> Ship[Ship]
1792
+ `
1793
+ const diagram = parseMermaidFlowchartDiagram(content)
1794
+ const output = renderFlowchartDiagram(content)
1795
+
1796
+ expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "thick" }])
1797
+ expect(output).toContain("━━━━━━▶")
1798
+ })
1799
+
1800
+ test("parses and renders Mermaid dashed edges", () => {
1801
+ const content = `
1802
+ flowchart LR
1803
+ Build[Build] -.-> Ship[Ship]
1804
+ `
1805
+ const diagram = parseMermaidFlowchartDiagram(content)
1806
+ const output = renderFlowchartDiagram(content)
1807
+
1808
+ expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "dashed" }])
1809
+ expect(output).toContain("──────▶")
1810
+ })
1811
+
1812
+ test("paints horizontal and vertical dashed routes with solid terminal cells", () => {
1813
+ for (const direction of ["LR", "TD"] as const) {
1814
+ const content = `flowchart ${direction}\n A -.-> B`
1815
+ const diagram = parseMermaidFlowchartDiagram(content)
1816
+ const layout = layoutParsedFlowchartDiagram(diagram)
1817
+ const grid = drawParsedFlowchartDiagramGrid(diagram)
1818
+ const route = layout.routes[0]!
1819
+
1820
+ expect(route.edge.style).toBe("dashed")
1821
+ for (let index = 1; index < route.points.length; index++) {
1822
+ const from = route.points[index - 1]!
1823
+ const to = route.points[index]!
1824
+ const length = Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
1825
+ for (let offset = 0; offset <= length; offset++) {
1826
+ const x = from.x + Math.sign(to.x - from.x) * offset
1827
+ const y = from.y + Math.sign(to.y - from.y) * offset
1828
+ expect(grid.getCell(x, y)?.char).not.toBe(" ")
1829
+ }
1830
+ }
1831
+ }
1832
+ })
1833
+
1834
+ test("leaves shared fan-out junctions neutral", () => {
1835
+ const content = `flowchart LR
1836
+ D{driver} --> L[local]
1837
+ D --> M[Modal]
1838
+ D --> Mem[memory]`
1839
+ const diagram = parseMermaidFlowchartDiagram(content)
1840
+ const layout = layoutParsedFlowchartDiagram(diagram, { compact: true })
1841
+ const grid = drawParsedFlowchartDiagramGrid(diagram, { compact: true })
1842
+ const junction = layout.routes[0]!.points[1]!
1843
+
1844
+ expect(grid.getCell(junction.x, junction.y)?.style).toBe("edge")
1845
+ })
1846
+
1847
+ test("distributes short source fades before the first corner", () => {
1848
+ const content = `flowchart TD
1849
+ C[Files contract<br/>read / write / stat<br/>errors: Failed] -->|implemented by| ED[exec-defaults<br/>fused scripts<br/>one process]`
1850
+ const layout = layoutFlowchartDiagram(content)
1851
+ const grid = drawFlowchartDiagramGrid(content)
1852
+ const firstCorner = layout.routes[0]!.points[1]!
1853
+ const fadeStyles = new Set(
1854
+ grid.rows.flatMap((row) => row.map((cell) => cell.style)).filter((style) => style?.startsWith("nodeEdgeFade")),
1855
+ )
1856
+
1857
+ expect(fadeStyles.has("nodeEdgeFade1")).toBe(false)
1858
+ expect(fadeStyles.has("nodeEdgeFade5")).toBe(true)
1859
+ expect(grid.getCell(firstCorner.x, firstCorner.y)?.style).toBe("edge")
1860
+ })
1861
+
1862
+ test("tracks nested Mermaid subgraphs", () => {
1863
+ const diagram = parseMermaidFlowchartDiagram(`
1864
+ flowchart LR
1865
+ subgraph Outer
1866
+ subgraph Inner [Inner Work]
1867
+ A[A] --> B[B]
1868
+ end
1869
+ B --> C[C]
1870
+ end
1871
+ `)
1872
+
1873
+ expect(diagram.subgraphs).toEqual([
1874
+ { id: "Outer", label: "Outer", nodeIds: ["B", "C"], parentId: undefined },
1875
+ { id: "Inner", label: "Inner Work", nodeIds: ["A", "B"], parentId: "Outer" },
1876
+ ])
1877
+ })
1878
+
1879
+ test("detects graph headers and renders a terminal flowchart", () => {
1880
+ const output = renderFlowchartDiagram(`
1881
+ graph LR
1882
+ Client([Client]) --> API[API]
1883
+ API --> Cache[(Cache)]
1884
+ `)
1885
+
1886
+ expectDiagram(output).toEqualDiagram(`
1887
+ ╭───────╮
1888
+ ╭────────╮ ╭─────╮ ├───────┤
1889
+ │ Client ├──────▶│ API ├──────▶│ Cache │
1890
+ ╰────────╯ ╰─────╯ ├───────┤
1891
+ ╰───────╯
1892
+ `)
1893
+ })
1894
+
1895
+ test("renders Mermaid decision diamond nodes", () => {
1896
+ const output = renderFlowchartDiagram(`
1897
+ flowchart LR
1898
+ Build[Build] --> Gate{Ready?}
1899
+ Gate -->|yes| Ship([Ship])
1900
+ Gate -->|no| Fix[Fix]
1901
+ `)
1902
+
1903
+ expect(output).toContain("Ready?")
1904
+ expect(output).toContain("╭─╯")
1905
+ expect(output).toContain("╰─╮")
1906
+ expect(output).toContain("yes")
1907
+ expect(output).toContain("no")
1908
+ expect(output).not.toMatch(/[╱╲\\/]/)
1909
+ })
1910
+
1911
+ test("pads edge labels away from corners and arrowheads", () => {
1912
+ const output = renderFlowchartDiagram(`
1913
+ flowchart LR
1914
+ Gate{Ready?} -->|pass| Stage[(Stage)]
1915
+ Gate -->|notes| Notes([Notes])
1916
+ `)
1917
+
1918
+ expect(output).toContain(" pass ")
1919
+ expect(output).toContain(" notes ")
1920
+ expect(output).not.toContain("┌pass")
1921
+ expect(output).not.toContain("└notes")
1922
+ expect(output).not.toContain("pass─▶")
1923
+ expect(output).not.toContain("notes▶")
1924
+ })
1925
+
1926
+ test("renders br-delimited edge labels on separate rows", () => {
1927
+ const output = renderFlowchartDiagram(`flowchart LR
1928
+ A[Start] -->|first<br/>second line| B[Finish]`)
1929
+
1930
+ expect(output).toContain("first")
1931
+ expect(output).toContain("second line")
1932
+ expect(output.indexOf("first")).toBeLessThan(output.indexOf("second line"))
1933
+ expect(output).not.toContain("<br")
1934
+ })
1935
+
1936
+ test("renders edge labels with an independent background", () => {
1937
+ const background = parseColor("#334455")
1938
+ const styled = renderGridStyledText(
1939
+ drawFlowchartDiagramGrid(`flowchart LR
1940
+ A[Start] -->|route label| B[Finish]`),
1941
+ resolveFlowchartStyleColors(),
1942
+ { label: background },
1943
+ )
1944
+
1945
+ expect(styled.chunks.some((chunk) => chunk.text.includes("route label") && chunk.bg === background)).toBe(true)
1946
+ expect(styled.chunks.some((chunk) => chunk.text.includes("Start") && chunk.bg !== undefined)).toBe(false)
1947
+ })
1948
+
1949
+ test("keeps quoted multiline labels compact and renders italic node text", () => {
1950
+ const source = `flowchart TB
1951
+ DO["ServerWorkerd.create({ storage, config })"]
1952
+ DO --> SO["serverOptions()<br/><i>option flags</i>"]
1953
+ DO --> RP["replacements()<br/><i>layer overrides</i>"]
1954
+ SO -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>config as string"| SF["ServerFetch.make(options, { overrides })"]
1955
+ RP -->|"Database → DO-SQLite<br/>Shell/FS/Pty → typed-unavailable<br/>Snapshot/Vcs → no-op<br/>plugins → precompiled only"| SF
1956
+ SF --> GRAPH["LayerNode graph<br/>(core builds normally,<br/>swapped nodes substituted)"]`
1957
+ const grid = drawFlowchartDiagramGrid(source)
1958
+ const output = grid.toString({ trimTop: true, trimBottom: true })
1959
+ const styled = renderGridStyledText(grid, resolveFlowchartStyleColors())
1960
+
1961
+ expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThan(140)
1962
+ expect(output).not.toMatch(/<\/?i>|<br|events persist|mcp stdio|^[^\n]*"fs:/)
1963
+ expect(
1964
+ styled.chunks.some((chunk) => chunk.text.includes("option flags") && chunk.attributes === TextAttributes.ITALIC),
1965
+ ).toBe(true)
1966
+ })
1967
+
1968
+ test("keeps quoted architecture labels from distorting subgraph routes", () => {
1969
+ const source = `flowchart TB
1970
+ subgraph consumer["Durable Object"]
1971
+ DO["ServerWorkerd.create({ storage, config })"]
1972
+ end
1973
+
1974
+ DO --> SO["serverOptions()<br/><i>option flags</i>"]
1975
+ DO --> RP["replacements()<br/><i>layer overrides</i>"]
1976
+
1977
+ SO -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>config as string"| SF["ServerFetch.make(options, { overrides })"]
1978
+ RP -->|"Database → DO-SQLite<br/>Shell/FS/Pty → typed-unavailable<br/>Snapshot/Vcs → no-op<br/>plugins → precompiled only"| SF
1979
+
1980
+ SF --> GRAPH["LayerNode graph<br/>(core builds normally,<br/>swapped nodes substituted)"]
1981
+
1982
+ subgraph bundle["3rd mechanism: bundle conditions (build time)"]
1983
+ COND["--conditions=workerd<br/>pty / fff / photon / shell-parser<br/>native modules → inert stubs<br/>#global-roots → workerd path rooting"]
1984
+ end
1985
+ COND -.->|import resolution| GRAPH`
1986
+ const output = renderFlowchartDiagram(source)
1987
+
1988
+ expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThan(130)
1989
+ expect(output).not.toMatch(/<\/?i>|<br|^[^\n]*"(?:fs:|Database)/)
1990
+ for (const label of [
1991
+ "fs: watcher/fff off",
1992
+ "events.persist: true",
1993
+ "mcp.stdio: false",
1994
+ "config as string",
1995
+ "Database → DO-SQLite",
1996
+ "Shell/FS/Pty → typed-unavailable",
1997
+ "Snapshot/Vcs → no-op",
1998
+ "plugins → precompiled only",
1999
+ ]) {
2000
+ expect(output).toContain(label)
2001
+ }
2002
+ })
2003
+
2004
+ test("keeps tall multiline branch labels out of sibling nodes", () => {
2005
+ const output = renderFlowchartDiagram(`flowchart LR
2006
+ A[Start] -->|one<br/>two<br/>three<br/>four<br/>five| B[Upper]
2007
+ A --> C[Lower]`)
2008
+ const lines = output.split("\n")
2009
+ const labelRows = ["one", "two", "three", "four", "five"].map((line) =>
2010
+ lines.findIndex((row) => row.includes(line)),
2011
+ )
2012
+ const lowerRow = lines.findIndex((line) => line.includes("Lower"))
2013
+
2014
+ expect(labelRows).toEqual([...labelRows].sort((left, right) => left - right))
2015
+ expect(lowerRow).toBeGreaterThan(labelRows.at(-1)!)
2016
+ })
2017
+
2018
+ test("keeps multiline vertical edge labels above their target node", () => {
2019
+ const output = renderFlowchartDiagram(`flowchart TD
2020
+ A[Start] -->|first<br/>second<br/>third<br/>fourth| B[Finish]`)
2021
+ const lines = output.split("\n")
2022
+ const fourthRow = lines.findIndex((line) => line.includes("fourth"))
2023
+ const finishRow = lines.findIndex((line) => line.includes("Finish"))
2024
+
2025
+ expect(fourthRow).toBeGreaterThanOrEqual(0)
2026
+ expect(finishRow).toBeGreaterThan(fourthRow)
2027
+ expect(output).not.toContain("<br")
2028
+ })
2029
+
2030
+ test.each(
2031
+ (["TD", "BT"] as const).flatMap((direction) =>
2032
+ [false, true].flatMap((compact) => [2, 4].map((lines) => ({ direction, compact, lines }))),
2033
+ ),
2034
+ )(
2035
+ "keeps $lines-line $direction labels off both terminal rows with compact=$compact",
2036
+ ({ direction, compact, lines }) => {
2037
+ const label = Array.from({ length: lines }, (_, index) => `line ${index + 1}`).join("<br/>")
2038
+ const route = layoutFlowchartDiagram(`flowchart ${direction}\n A[A] -->|${label}| B[B]`, { compact }).routes[0]!
2039
+ const layout = flowchartRouteLabelLayout(route, visualLength)
2040
+ const terminals = new Set([route.points[0]!.y, route.points.at(-1)!.y])
2041
+
2042
+ for (let y = layout.point.y; y < layout.point.y + layout.height; y++) expect(terminals.has(y)).toBe(false)
2043
+ },
2044
+ )
2045
+
2046
+ test("expands canvas for multiline back-edge labels", () => {
2047
+ const output = renderFlowchartDiagram(`flowchart TD
2048
+ A --> B
2049
+ B -->|try<br/>again| A`)
2050
+
2051
+ expect(output).toContain("try")
2052
+ expect(output).toContain("again")
2053
+ expect(output).not.toContain("<br")
2054
+ })
2055
+
2056
+ test("only expands horizontal rank gaps for labeled edges", () => {
2057
+ const { bounds } = layoutFlowchartDiagram(`
2058
+ flowchart LR
2059
+ Spec[Spec] --> Plan[Plan]
2060
+ Plan --> Build[Build]
2061
+ Build --> Gate{Ready?}
2062
+ Gate -->|pass| Stage[(Stage)]
2063
+ `)
2064
+ const gapBetween = (fromId: string, toId: string): number => {
2065
+ const from = bounds.get(fromId)!
2066
+ const to = bounds.get(toId)!
2067
+ return to.left - (from.left + from.width)
2068
+ }
2069
+
2070
+ expect(gapBetween("Spec", "Plan")).toBe(DEFAULT_MIN_RANK_GAP)
2071
+ expect(gapBetween("Plan", "Build")).toBe(DEFAULT_MIN_RANK_GAP)
2072
+ expect(gapBetween("Build", "Gate")).toBe(DEFAULT_MIN_RANK_GAP)
2073
+ expect(gapBetween("Gate", "Stage")).toBeGreaterThan(DEFAULT_MIN_RANK_GAP)
2074
+ })
2075
+
2076
+ test("renders Mermaid subgraph frames", () => {
2077
+ const output = renderFlowchartDiagram(`
2078
+ graph LR
2079
+ subgraph Web [Web App]
2080
+ UI[UI] --> API[API]
2081
+ end
2082
+ API --> DB[(DB)]
2083
+ `)
2084
+
2085
+ expect(output).toContain("Web App")
2086
+ expect(output).toContain("UI")
2087
+ expect(output).toContain("API")
2088
+ expect(output).toContain("DB")
2089
+ expect(output).toContain("╭─ Web App ")
2090
+ expect(output.split("\n").find((line) => line.includes("API") && line.includes("DB"))).not.toContain("┼")
2091
+ })
2092
+
2093
+ test("breaks vertical subgraph borders where horizontal routes pass through", () => {
2094
+ const content = `flowchart LR
2095
+ Outside[Outside] --> Inside
2096
+ subgraph Group
2097
+ Inside[Inside]
2098
+ end`
2099
+ const diagram = parseMermaidFlowchartDiagram(content)
2100
+ const layout = layoutParsedFlowchartDiagram(diagram)
2101
+ const grid = drawParsedFlowchartDiagramGrid(diagram)
2102
+ const group = layout.subgraphBounds.get("Group")!
2103
+ const crossing = { x: group.left, y: layout.routes[0]!.points.at(-1)!.y }
2104
+
2105
+ expect(grid.getCell(crossing.x, crossing.y)?.char).toBe("─")
2106
+ expect(grid.getCell(crossing.x, crossing.y)?.style).not.toBe("group")
2107
+ expect(grid.getCell(crossing.x - 1, crossing.y)?.char).toBe("─")
2108
+ expect(grid.getCell(crossing.x, crossing.y - 1)?.char).toBe("│")
2109
+ expect(grid.getCell(crossing.x, crossing.y + 1)?.char).toBe("│")
2110
+ })
2111
+
2112
+ test("breaks horizontal subgraph borders where vertical routes pass through", () => {
2113
+ const content = `flowchart TD
2114
+ Outside[Outside] --> Inside
2115
+ subgraph Outer [O]
2116
+ subgraph Inner
2117
+ Inside[Inside]
2118
+ end
2119
+ end`
2120
+ const diagram = parseMermaidFlowchartDiagram(content)
2121
+ const layout = layoutParsedFlowchartDiagram(diagram)
2122
+ const grid = drawParsedFlowchartDiagramGrid(diagram)
2123
+ const outer = layout.subgraphBounds.get("Outer")!
2124
+ const crossing = { x: layout.routes[0]!.points[0]!.x, y: outer.top }
2125
+
2126
+ expect(grid.getCell(crossing.x, crossing.y)?.char).toBe("│")
2127
+ expect(grid.getCell(crossing.x, crossing.y)?.style).not.toBe("group")
2128
+ expect(grid.getCell(crossing.x - 1, crossing.y)?.char).toBe("─")
2129
+ expect(grid.getCell(crossing.x + 1, crossing.y)?.char).toBe("─")
2130
+ expect(grid.getCell(crossing.x, crossing.y - 1)?.char).toBe("│")
2131
+ })
2132
+
2133
+ test("reserves frame rows for br-delimited subgraph labels", () => {
2134
+ const output = renderFlowchartDiagram(`flowchart LR
2135
+ subgraph Web [API<br/>Services]
2136
+ A[Worker]
2137
+ end`)
2138
+ const lines = output.split("\n")
2139
+ const apiRow = lines.findIndex((line) => line.includes("API"))
2140
+ const servicesRow = lines.findIndex((line) => line.includes("Services"))
2141
+ const workerRow = lines.findIndex((line) => line.includes("Worker"))
2142
+
2143
+ expect(apiRow).toBeGreaterThanOrEqual(0)
2144
+ expect(servicesRow).toBe(apiRow + 1)
2145
+ expect(workerRow).toBeGreaterThan(servicesRow)
2146
+ expect(output).not.toContain("<br")
2147
+ })
2148
+
2149
+ test("moves multiline subgraph labels away from entering routes", () => {
2150
+ const output = renderFlowchartDiagram(`flowchart TD
2151
+ Input --> A
2152
+ subgraph Group [Line one<br/>Line two]
2153
+ A[A] --> B[B]
2154
+ end`)
2155
+ const lines = output.split("\n")
2156
+ const lineOne = lines.findIndex((line) => line.includes("Line one"))
2157
+ const lineTwo = lines.findIndex((line) => line.includes("Line two"))
2158
+ const b = lines.findIndex((line) => line.includes("│ B │"))
2159
+
2160
+ expect(lineOne).toBeGreaterThan(b)
2161
+ expect(lineTwo).toBe(lineOne + 1)
2162
+ expect(output).not.toContain("<br")
2163
+ })
2164
+
2165
+ test("keeps long Unicode subgraph titles from replacing entering arrowheads", () => {
2166
+ const content = `flowchart TD
2167
+ U[Up] --> A
2168
+ subgraph G [界界界界界界]
2169
+ A[A]
2170
+ end
2171
+ A --> D[Down]`
2172
+ const diagram = parseMermaidFlowchartDiagram(content)
2173
+ const layout = layoutParsedFlowchartDiagram(diagram, { compact: true })
2174
+ const grid = drawParsedFlowchartDiagramGrid(diagram, { compact: true })
2175
+ const entry = layout.routes.find((route) => route.edge.from === "U")!
2176
+ const end = entry.points.at(-1)!
2177
+
2178
+ expect(grid.getCell(end.x, end.y)?.char).toBe(diagramArrowHeadBetween(entry.points.at(-2)!, end))
2179
+ })
2180
+
2181
+ test("lays out subgraph-local directions independently from the outer flow", () => {
2182
+ const layout = layoutFlowchartDiagram(`
2183
+ flowchart TD
2184
+ Start[Start] --> A[A]
2185
+ subgraph Steps
2186
+ direction LR
2187
+ A --> B[B]
2188
+ B --> C[C]
2189
+ end
2190
+ C --> Done[Done]
2191
+ `)
2192
+ const a = layout.bounds.get("A")!
2193
+ const b = layout.bounds.get("B")!
2194
+ const c = layout.bounds.get("C")!
2195
+ const done = layout.bounds.get("Done")!
2196
+ const route = layout.routes.find((candidate) => candidate.edge.from === "A" && candidate.edge.to === "B")!
2197
+
2198
+ expect(a.centerY).toBe(b.centerY)
2199
+ expect(b.left).toBeGreaterThan(a.left)
2200
+ expect(c.left).toBeGreaterThan(b.left)
2201
+ expect(done.top).toBeGreaterThan(c.top)
2202
+ expect(route.points[0]!.y).toBe(route.points[route.points.length - 1]!.y)
2203
+ })
2204
+
2205
+ test("routes cross-subgraph edges around local-direction siblings", () => {
2206
+ const layout = layoutFlowchartDiagram(`flowchart TD
2207
+ subgraph Workers
2208
+ direction TD
2209
+ A[Worker one] --> B[Worker two]
2210
+ end
2211
+ subgraph Peer
2212
+ direction RL
2213
+ C[Store] --> D[Transform]
2214
+ end
2215
+ B --> D`)
2216
+ const route = layout.routes.find((candidate) => candidate.edge.from === "B" && candidate.edge.to === "D")!
2217
+
2218
+ expect(routeIntersectsBounds(route, layout.bounds.get("C")!)).toBe(false)
2219
+ })
2220
+
2221
+ test.each([
2222
+ ["BT", { compact: true }],
2223
+ ["LR", { compact: true }],
2224
+ ["RL", { compact: true }],
2225
+ ] as const)("keeps labeled cross-group routes clear of sibling nodes in %s layouts", (direction, options) => {
2226
+ const content = `flowchart ${direction}
2227
+ subgraph Left
2228
+ direction RL
2229
+ A[API] --> B[Queue]
2230
+ end
2231
+ subgraph Right
2232
+ direction TB
2233
+ C[Transform] --> D[Accept]
2234
+ end
2235
+ B -->|cross group| C
2236
+ D -->|retry group| A`
2237
+ const layout = layoutFlowchartDiagram(content, options)
2238
+ const crossGroup = layout.routes.find((route) => route.edge.from === "B" && route.edge.to === "C")!
2239
+
2240
+ if (direction !== "LR") expect(routeIntersectsBounds(crossGroup, layout.bounds.get("A")!)).toBe(false)
2241
+ expect(renderFlowchartDiagram(content, options)).toContain("cross group")
2242
+ expect(renderFlowchartDiagram(content, options)).toContain("retry group")
2243
+ })
2244
+
2245
+ test.each(["LR", "RL"] as const)(
2246
+ "keeps nested result labels and target-facing entry routes in %s layouts",
2247
+ (direction) => {
2248
+ const content = `flowchart ${direction}
2249
+ I[Input] --> A
2250
+ subgraph Outer
2251
+ direction LR
2252
+ subgraph Inner
2253
+ direction BT
2254
+ A[Parse] --> B[Valid]
2255
+ B --> C[Cache]
2256
+ C --> B
2257
+ end
2258
+ B --> D[Dispatch]
2259
+ end
2260
+ D -->|result path| O[Output]`
2261
+ const layout = layoutFlowchartDiagram(content)
2262
+ const entry = layout.routes.find((route) => route.edge.from === "I" && route.edge.to === "A")!
2263
+
2264
+ expect(renderFlowchartDiagram(content)).toContain("result path")
2265
+ expect(terminalPointsTowardBounds(entry, layout.bounds.get("A")!)).toBe(true)
2266
+ },
2267
+ )
2268
+
2269
+ test("keeps labels on nested routes that pass translated outer siblings", () => {
2270
+ const output = renderFlowchartDiagram(`flowchart TD
2271
+ Input --> Parse
2272
+ subgraph Outer
2273
+ direction LR
2274
+ subgraph Inner
2275
+ direction BT
2276
+ Parse[Parse] --> Validate{Valid?}
2277
+ Validate -->|yes| Cache[(Cache)]
2278
+ Cache --> Validate
2279
+ end
2280
+ Validate --> Dispatch[Dispatch]
2281
+ end`)
2282
+
2283
+ expect(output).toContain("yes")
2284
+ })
2285
+
2286
+ test("routes nested RL local edges around outer siblings", () => {
2287
+ const layout = layoutFlowchartDiagram(
2288
+ `flowchart RL
2289
+ I([Input λ]) --> A
2290
+ subgraph Outer [Outer group 長い]
2291
+ direction LR
2292
+ subgraph Inner [Inner<br/>工程]
2293
+ direction BT
2294
+ A[Parse request] -->|inner edge| B{Valid?}
2295
+ B --> C[(Cache Ω)]
2296
+ C --> B
2297
+ end
2298
+ B --> D[[Dispatch work]]
2299
+ end
2300
+ D -.->|result path| O([Output μ])`,
2301
+ { compact: true },
2302
+ )
2303
+
2304
+ for (const route of layout.routes.filter((route) => ["A", "B", "C"].includes(route.edge.from))) {
2305
+ if (route.edge.to === "D") continue
2306
+ expect(routeIntersectsBounds(route, layout.bounds.get("D")!)).toBe(false)
2307
+ }
2308
+ })
2309
+
2310
+ test("keeps nested local-direction layouts rigid across direction and compact matrices", () => {
2311
+ const directions = ["LR", "RL", "TD", "BT"] as const
2312
+ for (const global of directions) {
2313
+ for (const outer of directions) {
2314
+ for (const inner of directions) {
2315
+ for (const compact of [false, true]) {
2316
+ const layout = layoutFlowchartDiagram(
2317
+ `flowchart ${global}
2318
+ X[X] --> A
2319
+ subgraph Outer [Outer]
2320
+ direction ${outer}
2321
+ subgraph Inner [Inner]
2322
+ direction ${inner}
2323
+ A[A] --> B[B]
2324
+ end
2325
+ B --> C[C]
2326
+ end
2327
+ C --> Y[Y]`,
2328
+ { compact },
2329
+ )
2330
+ const nodes = [...layout.bounds.values()]
2331
+ const innerFrame = layout.subgraphBounds.get("Inner")!
2332
+ const outerFrame = layout.subgraphBounds.get("Outer")!
2333
+ const a = layout.bounds.get("A")!
2334
+ const b = layout.bounds.get("B")!
2335
+ const c = layout.bounds.get("C")!
2336
+
2337
+ for (let left = 0; left < nodes.length; left++) {
2338
+ for (let right = left + 1; right < nodes.length; right++) {
2339
+ expect(boundsIntersect(nodes[left]!, nodes[right]!)).toBe(false)
2340
+ }
2341
+ }
2342
+ expect(boundsContains(innerFrame, a)).toBe(true)
2343
+ expect(boundsContains(innerFrame, b)).toBe(true)
2344
+ expect(boundsContains(outerFrame, innerFrame)).toBe(true)
2345
+ expect(boundsContains(outerFrame, c)).toBe(true)
2346
+ expect(layout.routes.every((route) => route.points.length >= 2)).toBe(true)
2347
+ expectFlowchartRoutesAvoidUnrelatedNodes(layout)
2348
+ for (const frame of layout.subgraphBounds.values()) {
2349
+ for (const route of layout.routes) {
2350
+ expect(routeRunsAlongHorizontalBorder(route, frame)).toBe(false)
2351
+ expect(routeRunsAlongVerticalBorder(route, frame)).toBe(false)
2352
+ }
2353
+ }
2354
+
2355
+ if (inner === "LR") expect(b.left).toBeGreaterThan(a.left)
2356
+ if (inner === "RL") expect(b.left).toBeLessThan(a.left)
2357
+ if (inner === "TD") expect(b.top).toBeGreaterThan(a.top)
2358
+ if (inner === "BT") expect(b.top).toBeLessThan(a.top)
2359
+ if (outer === "LR") expect(c.centerX).toBeGreaterThan(b.centerX)
2360
+ if (outer === "RL") expect(c.centerX).toBeLessThan(b.centerX)
2361
+ if (outer === "TD") expect(c.centerY).toBeGreaterThan(b.centerY)
2362
+ if (outer === "BT") expect(c.centerY).toBeLessThan(b.centerY)
2363
+ }
2364
+ }
2365
+ }
2366
+ }
2367
+ })
2368
+
2369
+ test("compacts stacked subgraph-local direction rows", () => {
2370
+ const layout = layoutFlowchartDiagram(`
2371
+ flowchart TD
2372
+ Start[Start] --> A
2373
+ subgraph First [first row]
2374
+ direction LR
2375
+ A[A] --> B[B]
2376
+ end
2377
+ B --> C
2378
+ subgraph Second [second row]
2379
+ direction LR
2380
+ C[C] --> D[D]
2381
+ end
2382
+ D --> Done[Done]
2383
+ `)
2384
+ const first = layout.subgraphBounds.get("First")!
2385
+ const second = layout.subgraphBounds.get("Second")!
2386
+ const betweenRows = layout.routes.find((route) => route.edge.from === "B" && route.edge.to === "C")!
2387
+
2388
+ expect(second.top).toBeGreaterThan(first.top)
2389
+ expect(second.top - (first.top + first.height)).toBeLessThanOrEqual(DEFAULT_MIN_VERTICAL_RANK_GAP)
2390
+ expect(routeRunsAlongHorizontalBorder(betweenRows, first)).toBe(false)
2391
+ expect(routeRunsAlongHorizontalBorder(betweenRows, second)).toBe(false)
2392
+ })
2393
+
2394
+ test("keeps subgraph labels readable when routes enter through the frame", () => {
2395
+ const output = renderFlowchartDiagram(`
2396
+ flowchart TD
2397
+ Start[Start] --> Remember
2398
+ subgraph Remembering [remember to]
2399
+ direction LR
2400
+ Remember[remember to] --> Heart[Heart]
2401
+ end
2402
+ `)
2403
+
2404
+ expect(output).toContain(" remember to ")
2405
+ expect(output).not.toContain("rememb▼r")
2406
+ })
2407
+
2408
+ test("keeps local LR branch joins compact when they feed a vertical stage", () => {
2409
+ const content = `
2410
+ flowchart TD
2411
+ Start[Start] --> A
2412
+ subgraph Verse [verse]
2413
+ direction LR
2414
+ A[A]
2415
+ B[B]
2416
+ C[C]
2417
+ D[D]
2418
+ E[E]
2419
+ F[F]
2420
+ G[G]
2421
+ A --> B
2422
+ B --> C
2423
+ A --> D
2424
+ D --> E
2425
+ A --> F
2426
+ F --> G
2427
+ end
2428
+ C --> Join
2429
+ E --> Join
2430
+ G --> Join
2431
+ `
2432
+ const layout = layoutFlowchartDiagram(content)
2433
+ const b = layout.bounds.get("B")!
2434
+ const c = layout.bounds.get("C")!
2435
+ const d = layout.bounds.get("D")!
2436
+ const e = layout.bounds.get("E")!
2437
+ const verse = layout.subgraphBounds.get("Verse")!
2438
+ const joinRoutes = layout.routes.filter((route) => route.edge.to === "Join")
2439
+ const output = renderFlowchartDiagram(content)
2440
+
2441
+ expect(c.left).toBeGreaterThan(b.left)
2442
+ expect(e.left).toBeGreaterThan(d.left)
2443
+ expect(new Set(joinRoutes.map((route) => route.points[1]!.x)).size).toBe(1)
2444
+ expect(Math.max(...joinRoutes.flatMap((route) => route.points.map((point) => point.x)))).toBeGreaterThan(
2445
+ verse.left + verse.width,
2446
+ )
2447
+ expect(output).not.toContain("││")
2448
+ })
2449
+
2450
+ test("routes transitions between local LR subgraphs outside their frames", () => {
2451
+ const layout = layoutFlowchartDiagram(`
2452
+ flowchart TD
2453
+ subgraph First [first]
2454
+ direction LR
2455
+ A[A]
2456
+ B[B]
2457
+ C[C]
2458
+ A --> B
2459
+ A --> C
2460
+ end
2461
+ B --> D
2462
+ C --> D
2463
+ subgraph Second [second]
2464
+ direction LR
2465
+ D[D] --> E[E]
2466
+ end
2467
+ `)
2468
+ const first = layout.subgraphBounds.get("First")!
2469
+ const second = layout.subgraphBounds.get("Second")!
2470
+ const routes = layout.routes.filter((route) => route.edge.to === "D")
2471
+
2472
+ expect(routes.length).toBe(2)
2473
+ for (const route of routes) {
2474
+ expect(routeRunsAlongHorizontalBorder(route, first)).toBe(false)
2475
+ expect(routeRunsAlongVerticalBorder(route, first)).toBe(false)
2476
+ expect(routeRunsAlongHorizontalBorder(route, second)).toBe(false)
2477
+ expect(routeRunsAlongVerticalBorder(route, second)).toBe(false)
2478
+ }
2479
+ })
2480
+
2481
+ test("keeps grouped fan routes orthogonal after subgraph translation", () => {
2482
+ const layout = layoutFlowchartDiagram(`
2483
+ flowchart LR
2484
+ Brief([Sketch Brief]) --> Parse[Parse Mermaid]
2485
+ subgraph Plan [Diagram Plan]
2486
+ Parse --> Layout[Rank Layout]
2487
+ Parse --> Cache[(Diagram Cache)]
2488
+ end
2489
+ Layout --> Preview([Terminal Preview])
2490
+ Cache --> Preview
2491
+ `)
2492
+
2493
+ for (const route of layout.routes) {
2494
+ for (let index = 1; index < route.points.length; index++) {
2495
+ const from = route.points[index - 1]!
2496
+ const to = route.points[index]!
2497
+ expect(from.x === to.x || from.y === to.y).toBe(true)
2498
+ }
2499
+ }
2500
+ })
2501
+
2502
+ test("separates cross-dependent top-level subgraphs", () => {
2503
+ const content = `flowchart TD
2504
+ subgraph plugins["Plugins — one verb: attach"]
2505
+ chip["pr-indicator<br/>attach(prompt.footer, { after: 'directory' })"]
2506
+ theme["fancy-footer<br/>attach(prompt.footer, { replace: 'right' })"]
2507
+ end
2508
+
2509
+ subgraph host["Host anatomy tree — published, stable part IDs"]
2510
+ footer["prompt.footer"]
2511
+ left["left"]
2512
+ right["right<br/>(container)"]
2513
+ dir["directory"]
2514
+ model["model"]
2515
+ tokens["tokens"]
2516
+ footer --> left
2517
+ footer --> right
2518
+ right --> dir
2519
+ right --> model
2520
+ right --> tokens
2521
+ end
2522
+
2523
+ chip -- "insert after" --> dir
2524
+ theme == "takeover" ==> right
2525
+ theme -. "suppresses guests<br/>in subtree" .-> chip`
2526
+ const layout = layoutFlowchartDiagram(content)
2527
+ const plugins = layout.subgraphBounds.get("plugins")!
2528
+ const host = layout.subgraphBounds.get("host")!
2529
+ const output = renderFlowchartDiagram(content)
2530
+ const lines = output.split("\n")
2531
+
2532
+ expect(host.top).toBeGreaterThanOrEqual(plugins.top + plugins.height)
2533
+ expect(lines.filter((line) => line.includes("Plugins — one verb: attach"))).toHaveLength(1)
2534
+ expect(lines.filter((line) => line.includes("Host anatomy tree — published, stable part IDs"))).toHaveLength(1)
2535
+ expect(lines.findIndex((line) => line.includes("Host anatomy tree"))).toBeGreaterThan(
2536
+ lines.findIndex((line) => line.includes("Plugins — one verb")),
2537
+ )
2538
+ for (const route of layout.routes) {
2539
+ for (let index = 1; index < route.points.length; index++) {
2540
+ const from = route.points[index - 1]!
2541
+ const to = route.points[index]!
2542
+ expect(from.x === to.x || from.y === to.y).toBe(true)
2543
+ }
2544
+ }
2545
+ })
2546
+
2547
+ test.each(["TD", "BT", "LR", "RL"] as const)(
2548
+ "keeps parallel top-level subgraphs in the same rank for %s diagrams",
2549
+ (direction) => {
2550
+ const layout = layoutFlowchartDiagram(`flowchart ${direction}
2551
+ subgraph source [Source]
2552
+ A[A]
2553
+ end
2554
+ subgraph left [Left]
2555
+ B[B]
2556
+ end
2557
+ subgraph right [Right]
2558
+ C[C]
2559
+ end
2560
+ A --> B
2561
+ A --> C`)
2562
+ const source = layout.subgraphBounds.get("source")!
2563
+ const left = layout.subgraphBounds.get("left")!
2564
+ const right = layout.subgraphBounds.get("right")!
2565
+ const leftNode = layout.bounds.get("B")!
2566
+ const rightNode = layout.bounds.get("C")!
2567
+ const horizontal = direction === "LR" || direction === "RL"
2568
+ const reversed = direction === "BT" || direction === "RL"
2569
+ const start = (bound: typeof source) => {
2570
+ const value = horizontal ? bound.left : bound.top
2571
+ const size = horizontal ? bound.width : bound.height
2572
+ return reversed ? -(value + size) : value
2573
+ }
2574
+ const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
2575
+
2576
+ expect(horizontal ? leftNode.centerX : leftNode.centerY).toBe(horizontal ? rightNode.centerX : rightNode.centerY)
2577
+ expect(Math.min(start(left), start(right))).toBeGreaterThanOrEqual(start(source) + size(source))
2578
+ },
2579
+ )
2580
+
2581
+ test.each(["TD", "BT", "LR", "RL"] as const)(
2582
+ "separates oversized parallel subgraph labels across %s diagrams",
2583
+ (direction) => {
2584
+ const horizontal = direction === "LR" || direction === "RL"
2585
+ const label = horizontal
2586
+ ? "one<br/>two<br/>three<br/>four<br/>five"
2587
+ : "A very very wide downstream subgraph title"
2588
+ const layout = layoutFlowchartDiagram(`flowchart ${direction}
2589
+ subgraph source [Source]
2590
+ A[A]
2591
+ end
2592
+ subgraph left [${label}]
2593
+ B[B]
2594
+ end
2595
+ subgraph right [Right]
2596
+ C[C]
2597
+ end
2598
+ A --> B
2599
+ A --> C`)
2600
+ const left = layout.subgraphBounds.get("left")!
2601
+ const right = layout.subgraphBounds.get("right")!
2602
+ const overlap =
2603
+ left.left < right.left + right.width &&
2604
+ left.left + left.width > right.left &&
2605
+ left.top < right.top + right.height &&
2606
+ left.top + left.height > right.top
2607
+
2608
+ expect(overlap).toBe(false)
2609
+ },
2610
+ )
2611
+
2612
+ test.each(["TD", "BT", "LR", "RL"] as const)(
2613
+ "ranks nested order-only subgraph dependencies for %s diagrams",
2614
+ (direction) => {
2615
+ const layout = layoutFlowchartDiagram(`flowchart ${direction}
2616
+ subgraph first [First]
2617
+ subgraph firstInner [First inner]
2618
+ A[A]
2619
+ end
2620
+ end
2621
+ subgraph second [Second]
2622
+ subgraph secondInner [Second inner]
2623
+ B[B]
2624
+ end
2625
+ end
2626
+ firstInner ~~~ secondInner`)
2627
+ const first = layout.subgraphBounds.get("first")!
2628
+ const second = layout.subgraphBounds.get("second")!
2629
+ const horizontal = direction === "LR" || direction === "RL"
2630
+ const reversed = direction === "BT" || direction === "RL"
2631
+ const start = (bound: typeof first) => {
2632
+ const value = horizontal ? bound.left : bound.top
2633
+ const size = horizontal ? bound.width : bound.height
2634
+ return reversed ? -(value + size) : value
2635
+ }
2636
+ const size = horizontal ? first.width : first.height
2637
+
2638
+ expect(start(second)).toBeGreaterThanOrEqual(start(first) + size)
2639
+ },
2640
+ )
2641
+
2642
+ test.each(["TD", "BT", "LR", "RL"] as const)(
2643
+ "ranks cyclic top-level subgraphs as one downstream component for %s diagrams",
2644
+ (direction) => {
2645
+ const layout = layoutFlowchartDiagram(`flowchart ${direction}
2646
+ subgraph source [Source]
2647
+ A[A]
2648
+ end
2649
+ subgraph first [First]
2650
+ B[B]
2651
+ end
2652
+ subgraph second [Second]
2653
+ C[C]
2654
+ end
2655
+ A --> B
2656
+ B --> C
2657
+ C --> B`)
2658
+ const source = layout.subgraphBounds.get("source")!
2659
+ const first = layout.subgraphBounds.get("first")!
2660
+ const second = layout.subgraphBounds.get("second")!
2661
+ const horizontal = direction === "LR" || direction === "RL"
2662
+ const reversed = direction === "BT" || direction === "RL"
2663
+ const start = (bound: typeof source) => {
2664
+ const value = horizontal ? bound.left : bound.top
2665
+ const size = horizontal ? bound.width : bound.height
2666
+ return reversed ? -(value + size) : value
2667
+ }
2668
+ const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
2669
+
2670
+ expect(Math.min(start(first), start(second))).toBeGreaterThanOrEqual(start(source) + size(source))
2671
+ },
2672
+ )
2673
+
2674
+ test("moves subgraph labels away from crossing routes", () => {
2675
+ const output = renderFlowchartDiagram(`
2676
+ flowchart TD
2677
+ Payment -->|approved| Orders[(Orders DB)]
2678
+ Payment -->|declined| Retry([Retry])
2679
+ Orders --> Receipt([Receipt])
2680
+ subgraph Fulfill [Fulfillment]
2681
+ Orders[(Orders DB)]
2682
+ Receipt([Receipt])
2683
+ end
2684
+ `)
2685
+ const lines = output.split("\n")
2686
+ const titleLineIndex = lines.findIndex((line) => line.includes("Fulfillment"))
2687
+ const ordersLineIndex = lines.findIndex((line) => line.includes("Orders DB"))
2688
+
2689
+ expect(titleLineIndex).toBeGreaterThan(ordersLineIndex)
2690
+ expect(lines[titleLineIndex]).not.toContain("approved")
2691
+ })
2692
+
2693
+ test("renders labeled vertical branches", () => {
2694
+ const output = renderFlowchartDiagram(`
2695
+ flowchart TD
2696
+ Input([Input]) --> Router[Route]
2697
+ Router -->|hit| Cache[(Cache)]
2698
+ Router -->|miss| Worker[Worker]
2699
+ `)
2700
+
2701
+ expect(output).toContain("Input")
2702
+ expect(output).toContain("Route")
2703
+ expect(output).toContain("Cache")
2704
+ expect(output).toContain("Worker")
2705
+ expect(output).toContain("hit")
2706
+ expect(output).toContain("miss")
2707
+ expect(output).toContain("▼")
2708
+ })
2709
+
2710
+ test("routes branch edges without diagonal glyphs", () => {
2711
+ const output = renderFlowchartDiagram(`
2712
+ graph LR
2713
+ Ticket([Ticket]) --> Triage[Auto Triage]
2714
+ Triage -->|billing| Billing[Billing Queue]
2715
+ Triage -->|bug| Bugs[(Bug Tracker)]
2716
+ Triage -->|question| Docs[Docs Reply]
2717
+ Billing --> Done([Closed])
2718
+ Bugs --> Done
2719
+ Docs --> Done
2720
+ `)
2721
+
2722
+ expect(output).toContain("Billing Queue")
2723
+ expect(output).toContain("Bug Tracker")
2724
+ expect(output).toContain("Docs Reply")
2725
+ expect(output).toContain("┼")
2726
+ expect(output).not.toMatch(/[▲▼]│/)
2727
+ expect(output).not.toMatch(/[╱╲\\/]/)
2728
+ })
2729
+
2730
+ test("keeps vertical branch labels separated from return edges", () => {
2731
+ const output = renderFlowchartDiagram(`
2732
+ flowchart TD
2733
+ Cart([Cart]) --> Address[Address]
2734
+ Address --> Payment[Payment]
2735
+ Payment -->|approved| Orders[(Orders DB)]
2736
+ Payment -->|declined| Retry([Retry])
2737
+ Retry --> Payment
2738
+ Orders --> Receipt([Receipt])
2739
+ `)
2740
+
2741
+ expect(output).toContain("approved")
2742
+ expect(output).toContain("declined")
2743
+ expect(output).not.toContain("approveddeclined")
2744
+ expect(output).not.toContain("declinedapproved")
2745
+ })
2746
+
2747
+ test("expands canvas to include back-edge labels", () => {
2748
+ const output = renderFlowchartDiagram(`
2749
+ flowchart TD
2750
+ A --> B
2751
+ B -->|again| A
2752
+ `)
2753
+
2754
+ expect(output).toContain("again")
2755
+ })
2756
+
2757
+ test("keeps vertical flowcharts compact with attached source connectors", () => {
2758
+ const output = renderFlowchartDiagram(`
2759
+ flowchart TD
2760
+ Cart([Cart]) --> Address[Address]
2761
+ Address --> Payment[Payment]
2762
+ Payment -->|approved| Orders[(Orders DB)]
2763
+ Payment -->|declined| Retry([Retry])
2764
+ Retry --> Payment
2765
+ Orders --> Receipt([Receipt])
2766
+ `)
2767
+ const lines = output.split("\n")
2768
+ const cartConnectorLineIndex = lines.findIndex((line) => line.includes("┬"))
2769
+ const connectorColumn = [...lines[cartConnectorLineIndex]!].indexOf("┬")
2770
+
2771
+ expect(lines.length).toBeLessThanOrEqual(34)
2772
+ expect([...lines[cartConnectorLineIndex + 1]!][connectorColumn]).toBe("│")
2773
+ })
2774
+
2775
+ test("keeps short back-edge labels out of source nodes", () => {
2776
+ const output = renderFlowchartDiagram(`
2777
+ flowchart LR
2778
+ Build[Build Services] --> Test[Integration Tests]
2779
+ Test -->|pass| Canary[Canary]
2780
+ Test -->|fail| Fix[Fix Forward]
2781
+ Fix --> Build
2782
+ Canary -->|rollback| Fix
2783
+ `)
2784
+ const rollbackLine = output.split("\n").find((line) => line.includes("rollback"))
2785
+
2786
+ expect(rollbackLine).toBeDefined()
2787
+ expect(rollbackLine).not.toContain("Canary")
2788
+ expect(rollbackLine).not.toContain("Fix Forward")
2789
+ })
2790
+
2791
+ test("applies the global flowchart StyledText theme", () => {
2792
+ const grid = drawFlowchartDiagramGrid("flowchart LR\n A[Alpha] --> B[Beta]")
2793
+ const node = parseColor("#ff0000")
2794
+ const nodeBorder = parseColor("#0000ff")
2795
+ const styled = renderGridStyledText(grid, resolveFlowchartStyleColors({ node, nodeBorder }))
2796
+
2797
+ expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && chunk.fg?.equals(node))).toBe(true)
2798
+ expect(styled.chunks.some((chunk) => chunk.text.includes("╭") && chunk.fg?.equals(nodeBorder))).toBe(true)
2799
+ })
2800
+ })