@zyro-sec/merman 1.0.2 → 1.0.3

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 (91) hide show
  1. package/package.json +2 -2
  2. package/script/layout-audit.ts +98 -98
  3. package/src/core/canvas.ts +228 -228
  4. package/src/core/color/style.ts +56 -56
  5. package/src/core/drawing.ts +301 -301
  6. package/src/core/geometry.ts +347 -347
  7. package/src/core/mermaid.ts +38 -38
  8. package/src/core/render-grid.ts +51 -51
  9. package/src/core/spatial.ts +243 -243
  10. package/src/core/text-lines.ts +32 -32
  11. package/src/core/text.ts +44 -44
  12. package/src/detect.ts +17 -17
  13. package/src/diagnostics.ts +16 -16
  14. package/src/flowchart/drawing.ts +340 -340
  15. package/src/flowchart/labels.ts +144 -144
  16. package/src/flowchart/layout.ts +1427 -1427
  17. package/src/flowchart/options.ts +12 -12
  18. package/src/flowchart/parser.ts +467 -467
  19. package/src/flowchart/render.ts +10 -10
  20. package/src/flowchart/routing.ts +1542 -1542
  21. package/src/flowchart/style.ts +79 -79
  22. package/src/flowchart/types.ts +65 -65
  23. package/src/gantt/diagram.ts +8 -8
  24. package/src/gantt/drawing.ts +191 -191
  25. package/src/gantt/parser.ts +161 -161
  26. package/src/gantt/render-grid.ts +17 -17
  27. package/src/gantt/style.ts +36 -36
  28. package/src/gantt/types.ts +44 -44
  29. package/src/gitgraph/diagram.ts +8 -8
  30. package/src/gitgraph/drawing.ts +234 -234
  31. package/src/gitgraph/parser.ts +219 -219
  32. package/src/gitgraph/render-grid.ts +17 -17
  33. package/src/gitgraph/style.ts +37 -37
  34. package/src/gitgraph/types.ts +36 -36
  35. package/src/markdown.ts +336 -336
  36. package/src/palette.ts +75 -75
  37. package/src/plugin.ts +15 -15
  38. package/src/sequence/diagram.ts +8 -8
  39. package/src/sequence/drawing.ts +287 -287
  40. package/src/sequence/options.ts +8 -8
  41. package/src/sequence/parser.ts +282 -282
  42. package/src/sequence/placement.ts +684 -684
  43. package/src/sequence/render-grid.ts +22 -22
  44. package/src/sequence/style.ts +81 -81
  45. package/src/sequence/types.ts +74 -74
  46. package/src/state/diagram.ts +8 -8
  47. package/src/state/drawing.ts +360 -360
  48. package/src/state/endpoint.ts +15 -15
  49. package/src/state/layout.ts +1134 -1134
  50. package/src/state/note.ts +59 -59
  51. package/src/state/options.ts +11 -11
  52. package/src/state/parser.ts +224 -224
  53. package/src/state/render-grid.ts +22 -22
  54. package/src/state/routing.ts +1522 -1522
  55. package/src/state/search.ts +103 -103
  56. package/src/state/style.ts +52 -52
  57. package/src/state/types.ts +63 -63
  58. package/src/state/visible-model.ts +77 -77
  59. package/src/test/diagram.ts +32 -32
  60. package/src/test/layout-audit/fixtures.ts +538 -538
  61. package/src/test/layout-audit/harness.ts +522 -522
  62. package/src/timeline/diagram.ts +8 -8
  63. package/src/timeline/drawing.ts +109 -109
  64. package/src/timeline/parser.ts +119 -119
  65. package/src/timeline/render-grid.ts +17 -17
  66. package/src/timeline/style.ts +36 -36
  67. package/src/timeline/types.ts +31 -31
  68. package/tsconfig.json +10 -10
  69. package/src/core/canvas.test.ts +0 -203
  70. package/src/core/color/style.test.ts +0 -24
  71. package/src/core/drawing.test.ts +0 -116
  72. package/src/core/geometry.test.ts +0 -112
  73. package/src/core/spatial.test.ts +0 -87
  74. package/src/core/text.test.ts +0 -33
  75. package/src/flowchart/flowchart.test.ts +0 -2800
  76. package/src/flowchart/labels.test.ts +0 -127
  77. package/src/flowchart/routing.test.ts +0 -368
  78. package/src/gantt/diagram.test.ts +0 -124
  79. package/src/gitgraph/diagram.test.ts +0 -183
  80. package/src/layout-audit.test.ts +0 -92
  81. package/src/palette.test.ts +0 -103
  82. package/src/sequence/diagram.test.ts +0 -757
  83. package/src/sequence/placement.test.ts +0 -219
  84. package/src/state/diagram.test.ts +0 -1386
  85. package/src/state/layout.test.ts +0 -314
  86. package/src/state/routing.test.ts +0 -693
  87. package/src/state/style.test.ts +0 -113
  88. package/src/state/visible-model.test.ts +0 -84
  89. package/src/test/diagnostics.test.ts +0 -129
  90. package/src/test/markdown.test.ts +0 -474
  91. package/src/timeline/diagram.test.ts +0 -188
@@ -1,522 +1,522 @@
1
- import { orthogonalPathPoints, segmentBetween, type DiagramPoint } from "../../core/geometry.js"
2
- import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "../../core/spatial.js"
3
- import { diagramTextWidth } from "../../core/text.js"
4
- import { splitDiagramLines } from "../../core/text-lines.js"
5
- import { drawFlowchartDiagramGrid } from "../../flowchart/drawing.js"
6
- import { layoutFlowchartDiagram } from "../../flowchart/layout.js"
7
- import { flowchartRouteLabelLayout } from "../../flowchart/labels.js"
8
- import { parseMermaidFlowchartDiagram } from "../../flowchart/parser.js"
9
- import { createStateDiagramDrawing } from "../../state/drawing.js"
10
- import type { StateDiagramBoxBounds } from "../../state/layout.js"
11
- import { stateDiagramNoteConnector } from "../../state/note.js"
12
- import { parseMermaidStateDiagram } from "../../state/parser.js"
13
- import type { StateTransitionRenderPlan } from "../../state/routing.js"
14
- import { isHiddenCompositeMarker } from "../../state/visible-model.js"
15
- import { layoutFixtures, type LayoutFixture } from "./fixtures.js"
16
-
17
- export const auditViewports = [60, 80, 120] as const
18
-
19
- export type LayoutMetrics = {
20
- width: number
21
- height: number
22
- area: number
23
- routeLength: number
24
- bends: number
25
- crossings: number
26
- sharedRouteCells: number
27
- overflow: number
28
- }
29
-
30
- export type LayoutAudit = {
31
- fixture: LayoutFixture
32
- viewport: (typeof auditViewports)[number]
33
- output: string
34
- metrics: LayoutMetrics
35
- violations: string[]
36
- }
37
-
38
- type Bounds = Pick<StateDiagramBoxBounds, "left" | "top" | "width" | "height">
39
- type AuditedRoute = {
40
- from: string
41
- to: string
42
- points: readonly DiagramPoint[]
43
- }
44
-
45
- function finiteBounds(bounds: Bounds): boolean {
46
- return (
47
- [bounds.left, bounds.top, bounds.width, bounds.height].every(Number.isFinite) &&
48
- bounds.width > 0 &&
49
- bounds.height > 0
50
- )
51
- }
52
-
53
- function boundsOverlap(left: Bounds, right: Bounds): boolean {
54
- return (
55
- left.left < right.left + right.width &&
56
- left.left + left.width > right.left &&
57
- left.top < right.top + right.height &&
58
- left.top + left.height > right.top
59
- )
60
- }
61
-
62
- function boundsContain(outer: Bounds, inner: Bounds): boolean {
63
- return (
64
- inner.left >= outer.left &&
65
- inner.top >= outer.top &&
66
- inner.left + inner.width <= outer.left + outer.width &&
67
- inner.top + inner.height <= outer.top + outer.height
68
- )
69
- }
70
-
71
- function pointInBounds(point: DiagramPoint, bounds: Bounds): boolean {
72
- return (
73
- point.x >= bounds.left &&
74
- point.x < bounds.left + bounds.width &&
75
- point.y >= bounds.top &&
76
- point.y < bounds.top + bounds.height
77
- )
78
- }
79
-
80
- function pointTouchesBounds(point: DiagramPoint, bounds: Bounds): boolean {
81
- if (pointInBounds(point, bounds)) return true
82
- return (
83
- ((point.x === bounds.left - 1 || point.x === bounds.left + bounds.width) &&
84
- point.y >= bounds.top &&
85
- point.y < bounds.top + bounds.height) ||
86
- ((point.y === bounds.top - 1 || point.y === bounds.top + bounds.height) &&
87
- point.x >= bounds.left &&
88
- point.x < bounds.left + bounds.width)
89
- )
90
- }
91
-
92
- function isOrthogonal(points: readonly DiagramPoint[]): boolean {
93
- return points.every((point, index) => {
94
- if (
95
- !Number.isFinite(point.x) ||
96
- !Number.isFinite(point.y) ||
97
- !Number.isInteger(point.x) ||
98
- !Number.isInteger(point.y)
99
- )
100
- return false
101
- const previous = points[index - 1]
102
- return !previous || previous.x === point.x || previous.y === point.y
103
- })
104
- }
105
-
106
- function expandedPath(points: readonly DiagramPoint[]): DiagramPoint[] {
107
- if (!isOrthogonal(points)) return []
108
- return orthogonalPathPoints(points)
109
- }
110
-
111
- function routeLength(points: readonly DiagramPoint[]): number {
112
- return routeSegments(points).reduce((total, segment) => total + segment.length, 0)
113
- }
114
-
115
- function routeBends(points: readonly DiagramPoint[]): number {
116
- const directions = points.slice(1).flatMap((point, index) => {
117
- const previous = points[index]
118
- if (point.x === previous.x && point.y !== previous.y) return ["y"]
119
- if (point.y === previous.y && point.x !== previous.x) return ["x"]
120
- return []
121
- })
122
- return directions.slice(1).filter((axis, index) => axis !== directions[index]).length
123
- }
124
-
125
- function routeSegments(points: readonly DiagramPoint[]) {
126
- return points.slice(1).flatMap((point, index) => segmentBetween(points[index]!, point) ?? [])
127
- }
128
-
129
- function crossingCount(routes: readonly AuditedRoute[]): number {
130
- let count = 0
131
- for (const [index, route] of routes.entries()) {
132
- for (const other of routes.slice(index + 1)) {
133
- for (const segment of routeSegments(route.points)) {
134
- for (const otherSegment of routeSegments(other.points)) {
135
- if (segment.axis === otherSegment.axis) continue
136
- const horizontal = segment.axis === "x" ? segment : otherSegment
137
- const vertical = segment.axis === "y" ? segment : otherSegment
138
- const x = vertical.from.x
139
- const y = horizontal.from.y
140
- const horizontalMin = Math.min(horizontal.from.x, horizontal.to.x)
141
- const horizontalMax = Math.max(horizontal.from.x, horizontal.to.x)
142
- const verticalMin = Math.min(vertical.from.y, vertical.to.y)
143
- const verticalMax = Math.max(vertical.from.y, vertical.to.y)
144
- if (x <= horizontalMin || x >= horizontalMax || y <= verticalMin || y >= verticalMax) continue
145
- count++
146
- }
147
- }
148
- }
149
- }
150
- return count
151
- }
152
-
153
- function sharedRouteCellCount(routes: readonly AuditedRoute[]): number {
154
- let count = 0
155
- const cells = routes.map((route) => new Set(expandedPath(route.points).map((point) => `${point.x}:${point.y}`)))
156
- for (const [index, routeCells] of cells.entries()) {
157
- for (const other of cells.slice(index + 1)) {
158
- for (const cell of routeCells) if (other.has(cell)) count++
159
- }
160
- }
161
- return count
162
- }
163
-
164
- function metrics(
165
- width: number,
166
- height: number,
167
- routes: readonly AuditedRoute[],
168
- viewport: (typeof auditViewports)[number],
169
- ): LayoutMetrics {
170
- return {
171
- width,
172
- height,
173
- area: width * height,
174
- routeLength: routes.reduce((total, route) => total + routeLength(route.points), 0),
175
- bends: routes.reduce((total, route) => total + routeBends(route.points), 0),
176
- crossings: crossingCount(routes),
177
- sharedRouteCells: sharedRouteCellCount(routes),
178
- overflow: Math.max(0, width - viewport),
179
- }
180
- }
181
-
182
- function requireOutputLines(output: string, lines: readonly string[], owner: string, violations: string[]): void {
183
- for (const line of lines.map((line) => line.trim()).filter(Boolean)) {
184
- if (!output.includes(line)) violations.push(`${owner} content missing: ${JSON.stringify(line)}`)
185
- }
186
- }
187
-
188
- function validateRoutes(
189
- routes: readonly AuditedRoute[],
190
- bounds: ReadonlyMap<string, Bounds>,
191
- bodyIds: readonly string[],
192
- violations: string[],
193
- ): void {
194
- for (const [index, route] of routes.entries()) {
195
- if (route.points.length < 2) {
196
- violations.push(`route ${index} ${route.from}->${route.to} is empty`)
197
- continue
198
- }
199
- if (!isOrthogonal(route.points))
200
- violations.push(`route ${index} ${route.from}->${route.to} is not finite and orthogonal`)
201
- const from = bounds.get(route.from)
202
- const to = bounds.get(route.to)
203
- if (!from || !to) {
204
- violations.push(`route ${index} ${route.from}->${route.to} has a missing endpoint bound`)
205
- continue
206
- }
207
- if (!pointTouchesBounds(route.points[0], from))
208
- violations.push(`route ${index} does not touch source ${route.from}`)
209
- if (!pointTouchesBounds(route.points.at(-1)!, to))
210
- violations.push(`route ${index} does not touch target ${route.to}`)
211
- if (!isOrthogonal(route.points)) continue
212
- const bodySpace = SpatialIndex.empty().add(
213
- ...bodyIds.flatMap((id) => {
214
- const bound = bounds.get(id)
215
- return id === route.from || id === route.to || !bound
216
- ? []
217
- : [spatialRectClaim(`body:${id}`, `body:${id}`, "body", bound)]
218
- }),
219
- )
220
- const conflicts = bodySpace.conflicts(spatialPathClaim(`route:${index}`, `route:${index}`, "route", route.points))
221
- for (const id of new Set(conflicts.map((conflict) => conflict.existing.owner.slice("body:".length)))) {
222
- violations.push(`route ${index} ${route.from}->${route.to} intersects unrelated body ${id}`)
223
- }
224
- }
225
- }
226
-
227
- function validateBodies(bounds: ReadonlyMap<string, Bounds>, ids: readonly string[], violations: string[]): void {
228
- let occupied = SpatialIndex.empty()
229
- for (const id of ids) {
230
- const bound = bounds.get(id)
231
- if (!bound) {
232
- violations.push(`missing body bound ${id}`)
233
- continue
234
- }
235
- if (!finiteBounds(bound)) {
236
- violations.push(`body ${id} has invalid bounds`)
237
- continue
238
- }
239
- const claim = spatialRectClaim(`body:${id}`, `body:${id}`, "body", bound)
240
- for (const otherId of new Set(
241
- occupied.conflicts(claim).map((conflict) => conflict.existing.owner.slice("body:".length)),
242
- )) {
243
- violations.push(`bodies ${id} and ${otherId} overlap`)
244
- }
245
- occupied = occupied.add(claim)
246
- }
247
- }
248
-
249
- function auditFlowchart(fixture: LayoutFixture, viewport: (typeof auditViewports)[number]): LayoutAudit {
250
- const violations: string[] = []
251
- const diagram = parseMermaidFlowchartDiagram(fixture.source)
252
- const layout = layoutFlowchartDiagram(diagram, { compact: true, layoutMaxWidth: viewport })
253
- const grid = drawFlowchartDiagramGrid(diagram, { compact: true, layoutMaxWidth: viewport })
254
- const output = grid.toString({ trimTop: true, trimBottom: true })
255
- const size = grid.getTextSize({ trimTop: true, trimBottom: true })
256
- const routes = layout.routes.map((route) => ({ from: route.edge.from, to: route.edge.to, points: route.points }))
257
- const bodyIds = layout.diagram.nodes.map((node) => node.id)
258
- const endpointBounds = new Map<string, Bounds>([...layout.subgraphBounds, ...layout.bounds])
259
-
260
- if (!Number.isFinite(size.width) || !Number.isFinite(size.height) || size.width <= 0 || size.height <= 0)
261
- violations.push("rendered grid has invalid dimensions")
262
- if (!Number.isFinite(layout.width) || !Number.isFinite(layout.height) || layout.width <= 0 || layout.height <= 0)
263
- violations.push("layout has invalid dimensions")
264
- if (layout.routes.length !== layout.diagram.edges.filter((edge) => !edge.orderOnly).length)
265
- violations.push("rendered route count does not match visible edge count")
266
- validateBodies(layout.bounds, bodyIds, violations)
267
- validateRoutes(routes, endpointBounds, bodyIds, violations)
268
-
269
- for (const node of layout.diagram.nodes)
270
- requireOutputLines(output, layout.bounds.get(node.id)?.lines ?? [], `node ${node.id}`, violations)
271
- for (const route of layout.routes) {
272
- if (!route.edge.label) continue
273
- requireOutputLines(
274
- output,
275
- flowchartRouteLabelLayout(route, diagramTextWidth).lines,
276
- `edge ${route.edge.from}->${route.edge.to}`,
277
- violations,
278
- )
279
- const targets = new Set(
280
- layout.diagram.edges.filter((edge) => edge.label && edge.from === route.edge.from).map((edge) => edge.to),
281
- )
282
- const sources = new Set(
283
- layout.diagram.edges.filter((edge) => edge.label && edge.to === route.edge.to).map((edge) => edge.from),
284
- )
285
- const label = flowchartRouteLabelLayout(route, diagramTextWidth)
286
- if (
287
- fixture.family === "grouped-fanout" &&
288
- (targets.size > 1 || sources.size > 1) &&
289
- label.point.x + label.width > viewport
290
- ) {
291
- violations.push(`grouped edge ${route.edge.from}->${route.edge.to} label exceeds viewport`)
292
- }
293
- }
294
- for (const subgraph of layout.diagram.subgraphs ?? []) {
295
- const bound = layout.subgraphBounds.get(subgraph.id)
296
- if (!bound || !finiteBounds(bound)) violations.push(`subgraph ${subgraph.id} has invalid bounds`)
297
- requireOutputLines(output, splitDiagramLines(subgraph.label), `subgraph ${subgraph.id}`, violations)
298
- for (const nodeId of subgraph.nodeIds) {
299
- const node = layout.bounds.get(nodeId)
300
- if (bound && node && !boundsContain(bound, node))
301
- violations.push(`subgraph ${subgraph.id} does not contain ${nodeId}`)
302
- }
303
- }
304
- const subgraphs = layout.diagram.subgraphs ?? []
305
- const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
306
- const ancestorOf = (ancestor: string, id: string) => {
307
- let parentId = subgraphById.get(id)?.parentId
308
- while (parentId) {
309
- if (parentId === ancestor) return true
310
- parentId = subgraphById.get(parentId)?.parentId
311
- }
312
- return false
313
- }
314
- for (const [index, subgraph] of subgraphs.entries()) {
315
- const bound = layout.subgraphBounds.get(subgraph.id)
316
- if (!bound) continue
317
- for (const other of subgraphs.slice(index + 1)) {
318
- if (ancestorOf(subgraph.id, other.id) || ancestorOf(other.id, subgraph.id)) continue
319
- const otherBound = layout.subgraphBounds.get(other.id)
320
- if (otherBound && boundsOverlap(bound, otherBound)) {
321
- violations.push(`subgraphs ${subgraph.id} and ${other.id} overlap`)
322
- }
323
- }
324
- }
325
-
326
- return { fixture, viewport, output, metrics: metrics(size.width, size.height, routes, viewport), violations }
327
- }
328
-
329
- function stateRoute(route: StateTransitionRenderPlan): AuditedRoute {
330
- return {
331
- from: route.route.transition.from,
332
- to: route.route.transition.to,
333
- points: route.path.map(([x, y]) => ({ x, y })),
334
- }
335
- }
336
-
337
- function auditState(fixture: LayoutFixture, viewport: (typeof auditViewports)[number]): LayoutAudit {
338
- const violations: string[] = []
339
- const parsed = parseMermaidStateDiagram(fixture.source)
340
- const drawing = createStateDiagramDrawing(parsed, { minStateGap: 5, layoutMaxWidth: viewport })
341
- const diagram = drawing.diagram
342
- const layout = drawing.layout
343
- const plans = drawing.transitionPlans
344
- const grid = drawing.grid
345
- const routes = plans.map(stateRoute)
346
- const output = grid.toString({ trimTop: true, trimBottom: true })
347
- const size = grid.getTextSize({ trimTop: true, trimBottom: true })
348
- const bodyIds = diagram.states.filter((state) => !isHiddenCompositeMarker(state)).map((state) => state.id)
349
-
350
- if (!Number.isFinite(size.width) || !Number.isFinite(size.height) || size.width <= 0 || size.height <= 0)
351
- violations.push("rendered grid has invalid dimensions")
352
- if (plans.length !== diagram.transitions.length)
353
- violations.push("rendered route count does not match visible transition count")
354
- validateBodies(layout.bounds, bodyIds, violations)
355
- validateRoutes(routes, layout.bounds, bodyIds, violations)
356
- if (diagram.direction === "BT" && fixture.family === "chain") {
357
- for (const transition of diagram.transitions) {
358
- if (transition.from === transition.to) continue
359
- const from = layout.bounds.get(transition.from)
360
- const to = layout.bounds.get(transition.to)
361
- if (from && to && from.centerY <= to.centerY) {
362
- violations.push(`BT transition ${transition.from}->${transition.to} does not travel upward`)
363
- }
364
- }
365
- }
366
-
367
- for (const state of diagram.states) {
368
- if (isHiddenCompositeMarker(state)) continue
369
- requireOutputLines(output, layout.sizes.get(state.id)?.lines ?? [state.label], `state ${state.id}`, violations)
370
- }
371
- for (const plan of plans) {
372
- if (!plan.route.transition.label) continue
373
- if (!plan.label)
374
- violations.push(`transition ${plan.route.transition.from}->${plan.route.transition.to} has no label layout`)
375
- requireOutputLines(
376
- output,
377
- plan.label?.lines ?? [],
378
- `transition ${plan.route.transition.from}->${plan.route.transition.to}`,
379
- violations,
380
- )
381
- }
382
-
383
- const statesById = new Map(diagram.states.map((state) => [state.id, state]))
384
- const compositesById = new Map(diagram.composites.map((composite) => [composite.id, composite]))
385
- const descendantOf = (id: string, compositeId: string) => {
386
- let parentId = statesById.get(id)?.parentId ?? compositesById.get(id)?.parentId
387
- while (parentId) {
388
- if (parentId === compositeId) return true
389
- parentId = compositesById.get(parentId)?.parentId
390
- }
391
- return false
392
- }
393
- for (const composite of diagram.composites) {
394
- const bound = layout.compositeBounds.get(composite.id)
395
- if (!bound || !finiteBounds(bound)) {
396
- violations.push(`composite ${composite.id} has invalid bounds`)
397
- continue
398
- }
399
- requireOutputLines(output, splitDiagramLines(composite.label), `composite ${composite.id}`, violations)
400
- for (const state of diagram.states.filter(
401
- (state) => !isHiddenCompositeMarker(state) && descendantOf(state.id, composite.id),
402
- )) {
403
- const stateBound = layout.bounds.get(state.id)
404
- if (stateBound && !boundsContain(bound, stateBound))
405
- violations.push(`composite ${composite.id} does not contain ${state.id}`)
406
- }
407
- }
408
-
409
- for (const [index, note] of layout.noteBounds.entries()) {
410
- if (!finiteBounds(note)) violations.push(`note ${index} has invalid bounds`)
411
- requireOutputLines(output, note.lines, `note ${index}`, violations)
412
- for (const id of bodyIds) {
413
- const bound = layout.bounds.get(id)
414
- if (bound && boundsOverlap(note, bound)) violations.push(`note ${index} overlaps state ${id}`)
415
- }
416
- for (const other of layout.noteBounds.slice(index + 1)) {
417
- if (boundsOverlap(note, other)) violations.push(`notes ${index} and ${other.id} overlap`)
418
- }
419
- const target = layout.bounds.get(note.note.target)
420
- if (!target) {
421
- violations.push(`note ${index} has no target bound`)
422
- continue
423
- }
424
- for (const point of expandedPath(stateDiagramNoteConnector(note, target).points)) {
425
- for (const id of bodyIds) {
426
- if (id === note.note.target) continue
427
- const bound = layout.bounds.get(id)
428
- if (bound && pointInBounds(point, bound)) violations.push(`note ${index} connector intersects state ${id}`)
429
- }
430
- for (const other of layout.noteBounds) {
431
- if (other === note) continue
432
- if (pointInBounds(point, other)) violations.push(`note ${index} connector intersects note ${other.id}`)
433
- }
434
- }
435
- }
436
-
437
- return { fixture, viewport, output, metrics: metrics(size.width, size.height, routes, viewport), violations }
438
- }
439
-
440
- export function auditFixture(fixture: LayoutFixture, viewport: (typeof auditViewports)[number] = 120): LayoutAudit {
441
- return fixture.kind === "flowchart" ? auditFlowchart(fixture, viewport) : auditState(fixture, viewport)
442
- }
443
-
444
- export function auditAllFixtures(): LayoutAudit[] {
445
- return layoutFixtures().flatMap((fixture, index) => {
446
- if (fixture.curated) return auditViewports.map((viewport) => auditFixture(fixture, viewport))
447
- if (fixture.kind === "flowchart") {
448
- return auditFixture(fixture, auditViewports[index % auditViewports.length])
449
- }
450
- const viewport = fixture.profile === "short" ? 60 : fixture.profile === "unicode" ? 80 : 120
451
- return auditFixture(fixture, viewport)
452
- })
453
- }
454
-
455
- function percentile(values: readonly number[], ratio: number): number {
456
- if (values.length === 0) return 0
457
- return [...values].sort((left, right) => left - right)[Math.ceil(values.length * ratio) - 1] ?? 0
458
- }
459
-
460
- export function summarizeAudits(audits: readonly LayoutAudit[]) {
461
- const summarize = (selected: readonly LayoutAudit[]) => ({
462
- runs: selected.length,
463
- sources: new Set(selected.map((audit) => audit.fixture.id)).size,
464
- violations: selected.reduce((total, audit) => total + audit.violations.length, 0),
465
- area: {
466
- p50: percentile(
467
- selected.map((audit) => audit.metrics.area),
468
- 0.5,
469
- ),
470
- p95: percentile(
471
- selected.map((audit) => audit.metrics.area),
472
- 0.95,
473
- ),
474
- max: Math.max(0, ...selected.map((audit) => audit.metrics.area)),
475
- },
476
- bends: {
477
- p95: percentile(
478
- selected.map((audit) => audit.metrics.bends),
479
- 0.95,
480
- ),
481
- max: Math.max(0, ...selected.map((audit) => audit.metrics.bends)),
482
- },
483
- crossings: {
484
- total: selected.reduce((total, audit) => total + audit.metrics.crossings, 0),
485
- max: Math.max(0, ...selected.map((audit) => audit.metrics.crossings)),
486
- },
487
- routeLength: {
488
- p95: percentile(
489
- selected.map((audit) => audit.metrics.routeLength),
490
- 0.95,
491
- ),
492
- max: Math.max(0, ...selected.map((audit) => audit.metrics.routeLength)),
493
- },
494
- sharedRouteCells: {
495
- p95: percentile(
496
- selected.map((audit) => audit.metrics.sharedRouteCells),
497
- 0.95,
498
- ),
499
- max: Math.max(0, ...selected.map((audit) => audit.metrics.sharedRouteCells)),
500
- },
501
- overflow: {
502
- p95: percentile(
503
- selected.map((audit) => audit.metrics.overflow),
504
- 0.95,
505
- ),
506
- max: Math.max(0, ...selected.map((audit) => audit.metrics.overflow)),
507
- },
508
- })
509
- return {
510
- total: summarize(audits),
511
- flowchart: summarize(audits.filter((audit) => audit.fixture.kind === "flowchart")),
512
- state: summarize(audits.filter((audit) => audit.fixture.kind === "state")),
513
- }
514
- }
515
-
516
- export function worstAudits(audits: readonly LayoutAudit[], metric: keyof LayoutMetrics, limit = 10): LayoutAudit[] {
517
- return [...audits]
518
- .sort(
519
- (left, right) => right.metrics[metric] - left.metrics[metric] || left.fixture.id.localeCompare(right.fixture.id),
520
- )
521
- .slice(0, limit)
522
- }
1
+ import { orthogonalPathPoints, segmentBetween, type DiagramPoint } from "../../core/geometry.js"
2
+ import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "../../core/spatial.js"
3
+ import { diagramTextWidth } from "../../core/text.js"
4
+ import { splitDiagramLines } from "../../core/text-lines.js"
5
+ import { drawFlowchartDiagramGrid } from "../../flowchart/drawing.js"
6
+ import { layoutFlowchartDiagram } from "../../flowchart/layout.js"
7
+ import { flowchartRouteLabelLayout } from "../../flowchart/labels.js"
8
+ import { parseMermaidFlowchartDiagram } from "../../flowchart/parser.js"
9
+ import { createStateDiagramDrawing } from "../../state/drawing.js"
10
+ import type { StateDiagramBoxBounds } from "../../state/layout.js"
11
+ import { stateDiagramNoteConnector } from "../../state/note.js"
12
+ import { parseMermaidStateDiagram } from "../../state/parser.js"
13
+ import type { StateTransitionRenderPlan } from "../../state/routing.js"
14
+ import { isHiddenCompositeMarker } from "../../state/visible-model.js"
15
+ import { layoutFixtures, type LayoutFixture } from "./fixtures.js"
16
+
17
+ export const auditViewports = [60, 80, 120] as const
18
+
19
+ export type LayoutMetrics = {
20
+ width: number
21
+ height: number
22
+ area: number
23
+ routeLength: number
24
+ bends: number
25
+ crossings: number
26
+ sharedRouteCells: number
27
+ overflow: number
28
+ }
29
+
30
+ export type LayoutAudit = {
31
+ fixture: LayoutFixture
32
+ viewport: (typeof auditViewports)[number]
33
+ output: string
34
+ metrics: LayoutMetrics
35
+ violations: string[]
36
+ }
37
+
38
+ type Bounds = Pick<StateDiagramBoxBounds, "left" | "top" | "width" | "height">
39
+ type AuditedRoute = {
40
+ from: string
41
+ to: string
42
+ points: readonly DiagramPoint[]
43
+ }
44
+
45
+ function finiteBounds(bounds: Bounds): boolean {
46
+ return (
47
+ [bounds.left, bounds.top, bounds.width, bounds.height].every(Number.isFinite) &&
48
+ bounds.width > 0 &&
49
+ bounds.height > 0
50
+ )
51
+ }
52
+
53
+ function boundsOverlap(left: Bounds, right: Bounds): boolean {
54
+ return (
55
+ left.left < right.left + right.width &&
56
+ left.left + left.width > right.left &&
57
+ left.top < right.top + right.height &&
58
+ left.top + left.height > right.top
59
+ )
60
+ }
61
+
62
+ function boundsContain(outer: Bounds, inner: Bounds): boolean {
63
+ return (
64
+ inner.left >= outer.left &&
65
+ inner.top >= outer.top &&
66
+ inner.left + inner.width <= outer.left + outer.width &&
67
+ inner.top + inner.height <= outer.top + outer.height
68
+ )
69
+ }
70
+
71
+ function pointInBounds(point: DiagramPoint, bounds: Bounds): boolean {
72
+ return (
73
+ point.x >= bounds.left &&
74
+ point.x < bounds.left + bounds.width &&
75
+ point.y >= bounds.top &&
76
+ point.y < bounds.top + bounds.height
77
+ )
78
+ }
79
+
80
+ function pointTouchesBounds(point: DiagramPoint, bounds: Bounds): boolean {
81
+ if (pointInBounds(point, bounds)) return true
82
+ return (
83
+ ((point.x === bounds.left - 1 || point.x === bounds.left + bounds.width) &&
84
+ point.y >= bounds.top &&
85
+ point.y < bounds.top + bounds.height) ||
86
+ ((point.y === bounds.top - 1 || point.y === bounds.top + bounds.height) &&
87
+ point.x >= bounds.left &&
88
+ point.x < bounds.left + bounds.width)
89
+ )
90
+ }
91
+
92
+ function isOrthogonal(points: readonly DiagramPoint[]): boolean {
93
+ return points.every((point, index) => {
94
+ if (
95
+ !Number.isFinite(point.x) ||
96
+ !Number.isFinite(point.y) ||
97
+ !Number.isInteger(point.x) ||
98
+ !Number.isInteger(point.y)
99
+ )
100
+ return false
101
+ const previous = points[index - 1]
102
+ return !previous || previous.x === point.x || previous.y === point.y
103
+ })
104
+ }
105
+
106
+ function expandedPath(points: readonly DiagramPoint[]): DiagramPoint[] {
107
+ if (!isOrthogonal(points)) return []
108
+ return orthogonalPathPoints(points)
109
+ }
110
+
111
+ function routeLength(points: readonly DiagramPoint[]): number {
112
+ return routeSegments(points).reduce((total, segment) => total + segment.length, 0)
113
+ }
114
+
115
+ function routeBends(points: readonly DiagramPoint[]): number {
116
+ const directions = points.slice(1).flatMap((point, index) => {
117
+ const previous = points[index]
118
+ if (point.x === previous.x && point.y !== previous.y) return ["y"]
119
+ if (point.y === previous.y && point.x !== previous.x) return ["x"]
120
+ return []
121
+ })
122
+ return directions.slice(1).filter((axis, index) => axis !== directions[index]).length
123
+ }
124
+
125
+ function routeSegments(points: readonly DiagramPoint[]) {
126
+ return points.slice(1).flatMap((point, index) => segmentBetween(points[index]!, point) ?? [])
127
+ }
128
+
129
+ function crossingCount(routes: readonly AuditedRoute[]): number {
130
+ let count = 0
131
+ for (const [index, route] of routes.entries()) {
132
+ for (const other of routes.slice(index + 1)) {
133
+ for (const segment of routeSegments(route.points)) {
134
+ for (const otherSegment of routeSegments(other.points)) {
135
+ if (segment.axis === otherSegment.axis) continue
136
+ const horizontal = segment.axis === "x" ? segment : otherSegment
137
+ const vertical = segment.axis === "y" ? segment : otherSegment
138
+ const x = vertical.from.x
139
+ const y = horizontal.from.y
140
+ const horizontalMin = Math.min(horizontal.from.x, horizontal.to.x)
141
+ const horizontalMax = Math.max(horizontal.from.x, horizontal.to.x)
142
+ const verticalMin = Math.min(vertical.from.y, vertical.to.y)
143
+ const verticalMax = Math.max(vertical.from.y, vertical.to.y)
144
+ if (x <= horizontalMin || x >= horizontalMax || y <= verticalMin || y >= verticalMax) continue
145
+ count++
146
+ }
147
+ }
148
+ }
149
+ }
150
+ return count
151
+ }
152
+
153
+ function sharedRouteCellCount(routes: readonly AuditedRoute[]): number {
154
+ let count = 0
155
+ const cells = routes.map((route) => new Set(expandedPath(route.points).map((point) => `${point.x}:${point.y}`)))
156
+ for (const [index, routeCells] of cells.entries()) {
157
+ for (const other of cells.slice(index + 1)) {
158
+ for (const cell of routeCells) if (other.has(cell)) count++
159
+ }
160
+ }
161
+ return count
162
+ }
163
+
164
+ function metrics(
165
+ width: number,
166
+ height: number,
167
+ routes: readonly AuditedRoute[],
168
+ viewport: (typeof auditViewports)[number],
169
+ ): LayoutMetrics {
170
+ return {
171
+ width,
172
+ height,
173
+ area: width * height,
174
+ routeLength: routes.reduce((total, route) => total + routeLength(route.points), 0),
175
+ bends: routes.reduce((total, route) => total + routeBends(route.points), 0),
176
+ crossings: crossingCount(routes),
177
+ sharedRouteCells: sharedRouteCellCount(routes),
178
+ overflow: Math.max(0, width - viewport),
179
+ }
180
+ }
181
+
182
+ function requireOutputLines(output: string, lines: readonly string[], owner: string, violations: string[]): void {
183
+ for (const line of lines.map((line) => line.trim()).filter(Boolean)) {
184
+ if (!output.includes(line)) violations.push(`${owner} content missing: ${JSON.stringify(line)}`)
185
+ }
186
+ }
187
+
188
+ function validateRoutes(
189
+ routes: readonly AuditedRoute[],
190
+ bounds: ReadonlyMap<string, Bounds>,
191
+ bodyIds: readonly string[],
192
+ violations: string[],
193
+ ): void {
194
+ for (const [index, route] of routes.entries()) {
195
+ if (route.points.length < 2) {
196
+ violations.push(`route ${index} ${route.from}->${route.to} is empty`)
197
+ continue
198
+ }
199
+ if (!isOrthogonal(route.points))
200
+ violations.push(`route ${index} ${route.from}->${route.to} is not finite and orthogonal`)
201
+ const from = bounds.get(route.from)
202
+ const to = bounds.get(route.to)
203
+ if (!from || !to) {
204
+ violations.push(`route ${index} ${route.from}->${route.to} has a missing endpoint bound`)
205
+ continue
206
+ }
207
+ if (!pointTouchesBounds(route.points[0], from))
208
+ violations.push(`route ${index} does not touch source ${route.from}`)
209
+ if (!pointTouchesBounds(route.points.at(-1)!, to))
210
+ violations.push(`route ${index} does not touch target ${route.to}`)
211
+ if (!isOrthogonal(route.points)) continue
212
+ const bodySpace = SpatialIndex.empty().add(
213
+ ...bodyIds.flatMap((id) => {
214
+ const bound = bounds.get(id)
215
+ return id === route.from || id === route.to || !bound
216
+ ? []
217
+ : [spatialRectClaim(`body:${id}`, `body:${id}`, "body", bound)]
218
+ }),
219
+ )
220
+ const conflicts = bodySpace.conflicts(spatialPathClaim(`route:${index}`, `route:${index}`, "route", route.points))
221
+ for (const id of new Set(conflicts.map((conflict) => conflict.existing.owner.slice("body:".length)))) {
222
+ violations.push(`route ${index} ${route.from}->${route.to} intersects unrelated body ${id}`)
223
+ }
224
+ }
225
+ }
226
+
227
+ function validateBodies(bounds: ReadonlyMap<string, Bounds>, ids: readonly string[], violations: string[]): void {
228
+ let occupied = SpatialIndex.empty()
229
+ for (const id of ids) {
230
+ const bound = bounds.get(id)
231
+ if (!bound) {
232
+ violations.push(`missing body bound ${id}`)
233
+ continue
234
+ }
235
+ if (!finiteBounds(bound)) {
236
+ violations.push(`body ${id} has invalid bounds`)
237
+ continue
238
+ }
239
+ const claim = spatialRectClaim(`body:${id}`, `body:${id}`, "body", bound)
240
+ for (const otherId of new Set(
241
+ occupied.conflicts(claim).map((conflict) => conflict.existing.owner.slice("body:".length)),
242
+ )) {
243
+ violations.push(`bodies ${id} and ${otherId} overlap`)
244
+ }
245
+ occupied = occupied.add(claim)
246
+ }
247
+ }
248
+
249
+ function auditFlowchart(fixture: LayoutFixture, viewport: (typeof auditViewports)[number]): LayoutAudit {
250
+ const violations: string[] = []
251
+ const diagram = parseMermaidFlowchartDiagram(fixture.source)
252
+ const layout = layoutFlowchartDiagram(diagram, { compact: true, layoutMaxWidth: viewport })
253
+ const grid = drawFlowchartDiagramGrid(diagram, { compact: true, layoutMaxWidth: viewport })
254
+ const output = grid.toString({ trimTop: true, trimBottom: true })
255
+ const size = grid.getTextSize({ trimTop: true, trimBottom: true })
256
+ const routes = layout.routes.map((route) => ({ from: route.edge.from, to: route.edge.to, points: route.points }))
257
+ const bodyIds = layout.diagram.nodes.map((node) => node.id)
258
+ const endpointBounds = new Map<string, Bounds>([...layout.subgraphBounds, ...layout.bounds])
259
+
260
+ if (!Number.isFinite(size.width) || !Number.isFinite(size.height) || size.width <= 0 || size.height <= 0)
261
+ violations.push("rendered grid has invalid dimensions")
262
+ if (!Number.isFinite(layout.width) || !Number.isFinite(layout.height) || layout.width <= 0 || layout.height <= 0)
263
+ violations.push("layout has invalid dimensions")
264
+ if (layout.routes.length !== layout.diagram.edges.filter((edge) => !edge.orderOnly).length)
265
+ violations.push("rendered route count does not match visible edge count")
266
+ validateBodies(layout.bounds, bodyIds, violations)
267
+ validateRoutes(routes, endpointBounds, bodyIds, violations)
268
+
269
+ for (const node of layout.diagram.nodes)
270
+ requireOutputLines(output, layout.bounds.get(node.id)?.lines ?? [], `node ${node.id}`, violations)
271
+ for (const route of layout.routes) {
272
+ if (!route.edge.label) continue
273
+ requireOutputLines(
274
+ output,
275
+ flowchartRouteLabelLayout(route, diagramTextWidth).lines,
276
+ `edge ${route.edge.from}->${route.edge.to}`,
277
+ violations,
278
+ )
279
+ const targets = new Set(
280
+ layout.diagram.edges.filter((edge) => edge.label && edge.from === route.edge.from).map((edge) => edge.to),
281
+ )
282
+ const sources = new Set(
283
+ layout.diagram.edges.filter((edge) => edge.label && edge.to === route.edge.to).map((edge) => edge.from),
284
+ )
285
+ const label = flowchartRouteLabelLayout(route, diagramTextWidth)
286
+ if (
287
+ fixture.family === "grouped-fanout" &&
288
+ (targets.size > 1 || sources.size > 1) &&
289
+ label.point.x + label.width > viewport
290
+ ) {
291
+ violations.push(`grouped edge ${route.edge.from}->${route.edge.to} label exceeds viewport`)
292
+ }
293
+ }
294
+ for (const subgraph of layout.diagram.subgraphs ?? []) {
295
+ const bound = layout.subgraphBounds.get(subgraph.id)
296
+ if (!bound || !finiteBounds(bound)) violations.push(`subgraph ${subgraph.id} has invalid bounds`)
297
+ requireOutputLines(output, splitDiagramLines(subgraph.label), `subgraph ${subgraph.id}`, violations)
298
+ for (const nodeId of subgraph.nodeIds) {
299
+ const node = layout.bounds.get(nodeId)
300
+ if (bound && node && !boundsContain(bound, node))
301
+ violations.push(`subgraph ${subgraph.id} does not contain ${nodeId}`)
302
+ }
303
+ }
304
+ const subgraphs = layout.diagram.subgraphs ?? []
305
+ const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
306
+ const ancestorOf = (ancestor: string, id: string) => {
307
+ let parentId = subgraphById.get(id)?.parentId
308
+ while (parentId) {
309
+ if (parentId === ancestor) return true
310
+ parentId = subgraphById.get(parentId)?.parentId
311
+ }
312
+ return false
313
+ }
314
+ for (const [index, subgraph] of subgraphs.entries()) {
315
+ const bound = layout.subgraphBounds.get(subgraph.id)
316
+ if (!bound) continue
317
+ for (const other of subgraphs.slice(index + 1)) {
318
+ if (ancestorOf(subgraph.id, other.id) || ancestorOf(other.id, subgraph.id)) continue
319
+ const otherBound = layout.subgraphBounds.get(other.id)
320
+ if (otherBound && boundsOverlap(bound, otherBound)) {
321
+ violations.push(`subgraphs ${subgraph.id} and ${other.id} overlap`)
322
+ }
323
+ }
324
+ }
325
+
326
+ return { fixture, viewport, output, metrics: metrics(size.width, size.height, routes, viewport), violations }
327
+ }
328
+
329
+ function stateRoute(route: StateTransitionRenderPlan): AuditedRoute {
330
+ return {
331
+ from: route.route.transition.from,
332
+ to: route.route.transition.to,
333
+ points: route.path.map(([x, y]) => ({ x, y })),
334
+ }
335
+ }
336
+
337
+ function auditState(fixture: LayoutFixture, viewport: (typeof auditViewports)[number]): LayoutAudit {
338
+ const violations: string[] = []
339
+ const parsed = parseMermaidStateDiagram(fixture.source)
340
+ const drawing = createStateDiagramDrawing(parsed, { minStateGap: 5, layoutMaxWidth: viewport })
341
+ const diagram = drawing.diagram
342
+ const layout = drawing.layout
343
+ const plans = drawing.transitionPlans
344
+ const grid = drawing.grid
345
+ const routes = plans.map(stateRoute)
346
+ const output = grid.toString({ trimTop: true, trimBottom: true })
347
+ const size = grid.getTextSize({ trimTop: true, trimBottom: true })
348
+ const bodyIds = diagram.states.filter((state) => !isHiddenCompositeMarker(state)).map((state) => state.id)
349
+
350
+ if (!Number.isFinite(size.width) || !Number.isFinite(size.height) || size.width <= 0 || size.height <= 0)
351
+ violations.push("rendered grid has invalid dimensions")
352
+ if (plans.length !== diagram.transitions.length)
353
+ violations.push("rendered route count does not match visible transition count")
354
+ validateBodies(layout.bounds, bodyIds, violations)
355
+ validateRoutes(routes, layout.bounds, bodyIds, violations)
356
+ if (diagram.direction === "BT" && fixture.family === "chain") {
357
+ for (const transition of diagram.transitions) {
358
+ if (transition.from === transition.to) continue
359
+ const from = layout.bounds.get(transition.from)
360
+ const to = layout.bounds.get(transition.to)
361
+ if (from && to && from.centerY <= to.centerY) {
362
+ violations.push(`BT transition ${transition.from}->${transition.to} does not travel upward`)
363
+ }
364
+ }
365
+ }
366
+
367
+ for (const state of diagram.states) {
368
+ if (isHiddenCompositeMarker(state)) continue
369
+ requireOutputLines(output, layout.sizes.get(state.id)?.lines ?? [state.label], `state ${state.id}`, violations)
370
+ }
371
+ for (const plan of plans) {
372
+ if (!plan.route.transition.label) continue
373
+ if (!plan.label)
374
+ violations.push(`transition ${plan.route.transition.from}->${plan.route.transition.to} has no label layout`)
375
+ requireOutputLines(
376
+ output,
377
+ plan.label?.lines ?? [],
378
+ `transition ${plan.route.transition.from}->${plan.route.transition.to}`,
379
+ violations,
380
+ )
381
+ }
382
+
383
+ const statesById = new Map(diagram.states.map((state) => [state.id, state]))
384
+ const compositesById = new Map(diagram.composites.map((composite) => [composite.id, composite]))
385
+ const descendantOf = (id: string, compositeId: string) => {
386
+ let parentId = statesById.get(id)?.parentId ?? compositesById.get(id)?.parentId
387
+ while (parentId) {
388
+ if (parentId === compositeId) return true
389
+ parentId = compositesById.get(parentId)?.parentId
390
+ }
391
+ return false
392
+ }
393
+ for (const composite of diagram.composites) {
394
+ const bound = layout.compositeBounds.get(composite.id)
395
+ if (!bound || !finiteBounds(bound)) {
396
+ violations.push(`composite ${composite.id} has invalid bounds`)
397
+ continue
398
+ }
399
+ requireOutputLines(output, splitDiagramLines(composite.label), `composite ${composite.id}`, violations)
400
+ for (const state of diagram.states.filter(
401
+ (state) => !isHiddenCompositeMarker(state) && descendantOf(state.id, composite.id),
402
+ )) {
403
+ const stateBound = layout.bounds.get(state.id)
404
+ if (stateBound && !boundsContain(bound, stateBound))
405
+ violations.push(`composite ${composite.id} does not contain ${state.id}`)
406
+ }
407
+ }
408
+
409
+ for (const [index, note] of layout.noteBounds.entries()) {
410
+ if (!finiteBounds(note)) violations.push(`note ${index} has invalid bounds`)
411
+ requireOutputLines(output, note.lines, `note ${index}`, violations)
412
+ for (const id of bodyIds) {
413
+ const bound = layout.bounds.get(id)
414
+ if (bound && boundsOverlap(note, bound)) violations.push(`note ${index} overlaps state ${id}`)
415
+ }
416
+ for (const other of layout.noteBounds.slice(index + 1)) {
417
+ if (boundsOverlap(note, other)) violations.push(`notes ${index} and ${other.id} overlap`)
418
+ }
419
+ const target = layout.bounds.get(note.note.target)
420
+ if (!target) {
421
+ violations.push(`note ${index} has no target bound`)
422
+ continue
423
+ }
424
+ for (const point of expandedPath(stateDiagramNoteConnector(note, target).points)) {
425
+ for (const id of bodyIds) {
426
+ if (id === note.note.target) continue
427
+ const bound = layout.bounds.get(id)
428
+ if (bound && pointInBounds(point, bound)) violations.push(`note ${index} connector intersects state ${id}`)
429
+ }
430
+ for (const other of layout.noteBounds) {
431
+ if (other === note) continue
432
+ if (pointInBounds(point, other)) violations.push(`note ${index} connector intersects note ${other.id}`)
433
+ }
434
+ }
435
+ }
436
+
437
+ return { fixture, viewport, output, metrics: metrics(size.width, size.height, routes, viewport), violations }
438
+ }
439
+
440
+ export function auditFixture(fixture: LayoutFixture, viewport: (typeof auditViewports)[number] = 120): LayoutAudit {
441
+ return fixture.kind === "flowchart" ? auditFlowchart(fixture, viewport) : auditState(fixture, viewport)
442
+ }
443
+
444
+ export function auditAllFixtures(): LayoutAudit[] {
445
+ return layoutFixtures().flatMap((fixture, index) => {
446
+ if (fixture.curated) return auditViewports.map((viewport) => auditFixture(fixture, viewport))
447
+ if (fixture.kind === "flowchart") {
448
+ return auditFixture(fixture, auditViewports[index % auditViewports.length])
449
+ }
450
+ const viewport = fixture.profile === "short" ? 60 : fixture.profile === "unicode" ? 80 : 120
451
+ return auditFixture(fixture, viewport)
452
+ })
453
+ }
454
+
455
+ function percentile(values: readonly number[], ratio: number): number {
456
+ if (values.length === 0) return 0
457
+ return [...values].sort((left, right) => left - right)[Math.ceil(values.length * ratio) - 1] ?? 0
458
+ }
459
+
460
+ export function summarizeAudits(audits: readonly LayoutAudit[]) {
461
+ const summarize = (selected: readonly LayoutAudit[]) => ({
462
+ runs: selected.length,
463
+ sources: new Set(selected.map((audit) => audit.fixture.id)).size,
464
+ violations: selected.reduce((total, audit) => total + audit.violations.length, 0),
465
+ area: {
466
+ p50: percentile(
467
+ selected.map((audit) => audit.metrics.area),
468
+ 0.5,
469
+ ),
470
+ p95: percentile(
471
+ selected.map((audit) => audit.metrics.area),
472
+ 0.95,
473
+ ),
474
+ max: Math.max(0, ...selected.map((audit) => audit.metrics.area)),
475
+ },
476
+ bends: {
477
+ p95: percentile(
478
+ selected.map((audit) => audit.metrics.bends),
479
+ 0.95,
480
+ ),
481
+ max: Math.max(0, ...selected.map((audit) => audit.metrics.bends)),
482
+ },
483
+ crossings: {
484
+ total: selected.reduce((total, audit) => total + audit.metrics.crossings, 0),
485
+ max: Math.max(0, ...selected.map((audit) => audit.metrics.crossings)),
486
+ },
487
+ routeLength: {
488
+ p95: percentile(
489
+ selected.map((audit) => audit.metrics.routeLength),
490
+ 0.95,
491
+ ),
492
+ max: Math.max(0, ...selected.map((audit) => audit.metrics.routeLength)),
493
+ },
494
+ sharedRouteCells: {
495
+ p95: percentile(
496
+ selected.map((audit) => audit.metrics.sharedRouteCells),
497
+ 0.95,
498
+ ),
499
+ max: Math.max(0, ...selected.map((audit) => audit.metrics.sharedRouteCells)),
500
+ },
501
+ overflow: {
502
+ p95: percentile(
503
+ selected.map((audit) => audit.metrics.overflow),
504
+ 0.95,
505
+ ),
506
+ max: Math.max(0, ...selected.map((audit) => audit.metrics.overflow)),
507
+ },
508
+ })
509
+ return {
510
+ total: summarize(audits),
511
+ flowchart: summarize(audits.filter((audit) => audit.fixture.kind === "flowchart")),
512
+ state: summarize(audits.filter((audit) => audit.fixture.kind === "state")),
513
+ }
514
+ }
515
+
516
+ export function worstAudits(audits: readonly LayoutAudit[], metric: keyof LayoutMetrics, limit = 10): LayoutAudit[] {
517
+ return [...audits]
518
+ .sort(
519
+ (left, right) => right.metrics[metric] - left.metrics[metric] || left.fixture.id.localeCompare(right.fixture.id),
520
+ )
521
+ .slice(0, limit)
522
+ }