@zyro-sec/merman 0.0.0-stage → 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 (69) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.ts +228 -0
  4. package/src/core/color/style.ts +56 -0
  5. package/src/core/drawing.ts +301 -0
  6. package/src/core/geometry.ts +347 -0
  7. package/src/core/mermaid.ts +38 -0
  8. package/src/core/render-grid.ts +51 -0
  9. package/src/core/spatial.ts +243 -0
  10. package/src/core/text-lines.ts +32 -0
  11. package/src/core/text.ts +44 -0
  12. package/src/detect.ts +17 -0
  13. package/src/diagnostics.ts +16 -0
  14. package/src/flowchart/drawing.ts +340 -0
  15. package/src/flowchart/labels.ts +144 -0
  16. package/src/flowchart/layout.ts +1427 -0
  17. package/src/flowchart/options.ts +12 -0
  18. package/src/flowchart/parser.ts +467 -0
  19. package/src/flowchart/render.ts +10 -0
  20. package/src/flowchart/routing.ts +1542 -0
  21. package/src/flowchart/style.ts +79 -0
  22. package/src/flowchart/types.ts +65 -0
  23. package/src/gantt/diagram.ts +8 -0
  24. package/src/gantt/drawing.ts +191 -0
  25. package/src/gantt/parser.ts +161 -0
  26. package/src/gantt/render-grid.ts +17 -0
  27. package/src/gantt/style.ts +36 -0
  28. package/src/gantt/types.ts +44 -0
  29. package/src/gitgraph/diagram.ts +8 -0
  30. package/src/gitgraph/drawing.ts +234 -0
  31. package/src/gitgraph/parser.ts +219 -0
  32. package/src/gitgraph/render-grid.ts +17 -0
  33. package/src/gitgraph/style.ts +37 -0
  34. package/src/gitgraph/types.ts +36 -0
  35. package/src/markdown.ts +336 -0
  36. package/src/palette.ts +75 -0
  37. package/src/plugin.ts +15 -0
  38. package/src/sequence/diagram.ts +8 -0
  39. package/src/sequence/drawing.ts +287 -0
  40. package/src/sequence/options.ts +8 -0
  41. package/src/sequence/parser.ts +282 -0
  42. package/src/sequence/placement.ts +684 -0
  43. package/src/sequence/render-grid.ts +22 -0
  44. package/src/sequence/style.ts +81 -0
  45. package/src/sequence/types.ts +74 -0
  46. package/src/state/diagram.ts +8 -0
  47. package/src/state/drawing.ts +360 -0
  48. package/src/state/endpoint.ts +15 -0
  49. package/src/state/layout.ts +1134 -0
  50. package/src/state/note.ts +59 -0
  51. package/src/state/options.ts +11 -0
  52. package/src/state/parser.ts +224 -0
  53. package/src/state/render-grid.ts +22 -0
  54. package/src/state/routing.ts +1522 -0
  55. package/src/state/search.ts +103 -0
  56. package/src/state/style.ts +52 -0
  57. package/src/state/types.ts +63 -0
  58. package/src/state/visible-model.ts +77 -0
  59. package/src/test/diagram.ts +32 -0
  60. package/src/test/layout-audit/fixtures.ts +538 -0
  61. package/src/test/layout-audit/harness.ts +522 -0
  62. package/src/timeline/diagram.ts +8 -0
  63. package/src/timeline/drawing.ts +109 -0
  64. package/src/timeline/parser.ts +119 -0
  65. package/src/timeline/render-grid.ts +17 -0
  66. package/src/timeline/style.ts +36 -0
  67. package/src/timeline/types.ts +31 -0
  68. package/tsconfig.json +10 -0
  69. package/README.md +0 -3
@@ -0,0 +1,81 @@
1
+ import { RGBA } from "@opentui/core"
2
+ import {
3
+ createColorRampTheme,
4
+ DIAGRAM_FADE_STEPS,
5
+ numberedStyleKeys,
6
+ rgba,
7
+ type DiagramRgb,
8
+ } from "../core/color/style.js"
9
+ import type { FadeStyle, LifelineRampStyle, SequenceCellStyle } from "./types.js"
10
+
11
+ export interface SequenceStyleColors {
12
+ participant?: RGBA
13
+ lifeline?: RGBA
14
+ group?: RGBA
15
+ request?: RGBA
16
+ response?: RGBA
17
+ fragment?: RGBA
18
+ fragmentLabelBg?: RGBA
19
+ note?: RGBA
20
+ noteBg?: RGBA
21
+ }
22
+
23
+ export const SEQUENCE_FADE_STEPS = DIAGRAM_FADE_STEPS
24
+ const LIFELINE_RAMP_STYLES = [
25
+ "lifelineRamp1",
26
+ "lifelineRamp2",
27
+ "lifelineRamp3",
28
+ ] as const satisfies readonly LifelineRampStyle[]
29
+
30
+ const DEFAULT_THEME_RGB = {
31
+ participant: [228, 239, 232],
32
+ lifeline: [111, 138, 126],
33
+ group: [76, 99, 89],
34
+ request: [134, 225, 200],
35
+ response: [230, 177, 126],
36
+ fragment: [154, 184, 169],
37
+ fragmentLabelBg: [28, 43, 36],
38
+ noteFg: [215, 229, 221],
39
+ noteBg: [36, 56, 47],
40
+ } as const satisfies Record<string, DiagramRgb>
41
+
42
+ export function resolveSequenceStyleColors(
43
+ colors: SequenceStyleColors = {},
44
+ ): Required<SequenceStyleColors> & Record<FadeStyle | LifelineRampStyle, RGBA> {
45
+ const participant = colors.participant ?? rgba(DEFAULT_THEME_RGB.participant)
46
+ const lifeline = colors.lifeline ?? rgba(DEFAULT_THEME_RGB.lifeline)
47
+ const request = colors.request ?? rgba(DEFAULT_THEME_RGB.request)
48
+ const response = colors.response ?? rgba(DEFAULT_THEME_RGB.response)
49
+ return {
50
+ participant,
51
+ lifeline,
52
+ group: colors.group ?? rgba(DEFAULT_THEME_RGB.group),
53
+ request,
54
+ response,
55
+ fragment: colors.fragment ?? rgba(DEFAULT_THEME_RGB.fragment),
56
+ fragmentLabelBg: colors.fragmentLabelBg ?? rgba(DEFAULT_THEME_RGB.fragmentLabelBg),
57
+ note: colors.note ?? rgba(DEFAULT_THEME_RGB.noteFg),
58
+ noteBg: colors.noteBg ?? rgba(DEFAULT_THEME_RGB.noteBg),
59
+ ...createColorRampTheme(numberedStyleKeys("requestFade", SEQUENCE_FADE_STEPS), lifeline, request),
60
+ ...createColorRampTheme(numberedStyleKeys("responseFade", SEQUENCE_FADE_STEPS), lifeline, response),
61
+ ...createColorRampTheme(LIFELINE_RAMP_STYLES, participant, lifeline),
62
+ }
63
+ }
64
+
65
+ export function sequenceStyleColor(
66
+ style: SequenceCellStyle | undefined,
67
+ colors: Required<SequenceStyleColors> & Record<FadeStyle | LifelineRampStyle, RGBA>,
68
+ ): RGBA | undefined {
69
+ if (style === "noteBadge") return colors.note
70
+ if (style === "fragmentLabel") return colors.fragment
71
+ return style ? colors[style] : undefined
72
+ }
73
+
74
+ export function sequenceStyleBackgroundColor(
75
+ style: SequenceCellStyle | undefined,
76
+ colors: Required<SequenceStyleColors>,
77
+ ): RGBA | undefined {
78
+ if (style === "note" || style === "noteBadge") return colors.noteBg
79
+ if (style === "fragmentLabel") return colors.fragmentLabelBg
80
+ return undefined
81
+ }
@@ -0,0 +1,74 @@
1
+ import type { BorderStyle } from "@opentui/core"
2
+
3
+ export interface SequenceParticipant {
4
+ id: string
5
+ label: string
6
+ }
7
+
8
+ export interface SequenceParticipantGroup {
9
+ label: string
10
+ participantIds: string[]
11
+ }
12
+
13
+ export interface SequenceMessage {
14
+ from: string
15
+ to: string
16
+ label: string
17
+ style: "solid" | "dashed"
18
+ head?: SequenceArrowHead
19
+ number?: number
20
+ activate?: string
21
+ deactivate?: string
22
+ }
23
+
24
+ export type SequenceArrowHead = "open" | "cross" | "async"
25
+
26
+ export interface SequenceNote {
27
+ over: string[]
28
+ label: string
29
+ position?: "over" | "left" | "right"
30
+ }
31
+
32
+ export interface SequenceActivation {
33
+ participant: string
34
+ active: boolean
35
+ }
36
+
37
+ export interface SequenceFragment {
38
+ kind: "alt" | "else" | "loop" | "end"
39
+ label: string
40
+ }
41
+
42
+ export type SequenceStep =
43
+ | { type: "message"; message: SequenceMessage }
44
+ | { type: "note"; note: SequenceNote }
45
+ | { type: "activation"; activation: SequenceActivation }
46
+ | { type: "fragment"; fragment: SequenceFragment }
47
+
48
+ export interface SequenceDiagram {
49
+ participants: SequenceParticipant[]
50
+ messages: SequenceMessage[]
51
+ steps: SequenceStep[]
52
+ groups: SequenceParticipantGroup[]
53
+ }
54
+
55
+ export interface SequenceDiagramRenderOptions {
56
+ compact?: boolean
57
+ minParticipantGap?: number
58
+ fragmentBorderStyle?: BorderStyle
59
+ }
60
+
61
+ export type MessageStyle = "request" | "response"
62
+ export type FadeStyle = `${MessageStyle}Fade${1 | 2 | 3 | 4 | 5}`
63
+ export type LifelineRampStyle = `lifelineRamp${1 | 2 | 3}`
64
+ export type SequenceCellStyle =
65
+ | "participant"
66
+ | "lifeline"
67
+ | "group"
68
+ | MessageStyle
69
+ | FadeStyle
70
+ | LifelineRampStyle
71
+ | "fragment"
72
+ | "fragmentLabel"
73
+ | "note"
74
+ | "noteBadge"
@@ -0,0 +1,8 @@
1
+ import { drawStateDiagramGrid } from "./drawing.js"
2
+ import { parseMermaidStateDiagram } from "./parser.js"
3
+ import { renderStateGridText } from "./render-grid.js"
4
+ import type { StateDiagramRenderOptions } from "./types.js"
5
+
6
+ export function renderStateDiagram(content: string, options: StateDiagramRenderOptions = {}): string {
7
+ return renderStateGridText(drawStateDiagramGrid(parseMermaidStateDiagram(content), options))
8
+ }
@@ -0,0 +1,360 @@
1
+ import { BorderChars, type BorderCharacters, type BorderStyle } from "@opentui/core"
2
+ import { DiagramCanvas, DiagramCanvasSizeError, type DiagramCanvasCell } from "../core/canvas.js"
3
+ import { directionBetween, orthogonalPathPoints, type DiagramDirection } from "../core/geometry.js"
4
+ import {
5
+ diagramArrowHead,
6
+ diagramLineGlyph,
7
+ drawDiagramFrame,
8
+ fillDiagramFrameInterior,
9
+ mergeDiagramLineGlyph,
10
+ } from "../core/drawing.js"
11
+ import { DIAGRAM_LABEL_PADDING_X, diagramTextWidth } from "../core/text.js"
12
+ import {
13
+ createStateDiagramLayout,
14
+ expandCompositeBoundsForFeedback,
15
+ expandCompositeBoundsForInternalTransitions,
16
+ separateExternalBoundsFromComposites,
17
+ translateStateDiagramLayout,
18
+ type StateDiagramBoxBounds as BoxBounds,
19
+ type StateDiagramNoteBounds as StateNoteBounds,
20
+ } from "./layout.js"
21
+ import { stateDiagramNoteConnector } from "./note.js"
22
+ import { DEFAULT_STATE_ARROW_HEAD_STYLE, DEFAULT_STATE_BORDER_STYLE, normalizeStateMinStateGap } from "./options.js"
23
+ import type { StateGrid } from "./render-grid.js"
24
+ import {
25
+ createStateTransitionJunctionPlans,
26
+ createStateTransitionRenderPlans,
27
+ measureStateTransitionLabel,
28
+ type StateTransitionRenderPlan,
29
+ } from "./routing.js"
30
+ import { createStateSearchBudget } from "./search.js"
31
+ import { NOTE_CONNECTOR_RAMP_STYLES, STATE_DEPARTURE_RAMP_STYLES } from "./style.js"
32
+ import type {
33
+ StateCellStyle,
34
+ StateDiagram,
35
+ StateDiagramArrowHeadStyle,
36
+ StateDiagramRenderOptions,
37
+ StateDiagramState,
38
+ } from "./types.js"
39
+ import { isHiddenCompositeMarker, prepareVisibleStateDiagram } from "./visible-model.js"
40
+
41
+ type StateCell = DiagramCanvasCell<StateCellStyle>
42
+
43
+ function translateTransitionPlans(
44
+ plans: readonly StateTransitionRenderPlan[],
45
+ dx: number,
46
+ dy: number,
47
+ ): StateTransitionRenderPlan[] {
48
+ return plans.map((plan) => ({
49
+ ...plan,
50
+ cells: plan.cells.map((cell) => ({ ...cell, x: cell.x + dx, y: cell.y + dy })),
51
+ path: plan.path.map(([x, y]) => [x + dx, y + dy]),
52
+ label: plan.label ? { ...plan.label, x: plan.label.x + dx, y: plan.label.y + dy } : undefined,
53
+ }))
54
+ }
55
+
56
+ function makeGrid(width: number, height: number): StateGrid {
57
+ return new DiagramCanvas(width, height, {
58
+ mergeCell: (existing, incoming): StateCell => {
59
+ const existingIsTransition = existing.style === "transition" || existing.style?.startsWith("stateDepartureRamp")
60
+ const incomingIsTransition = incoming.style === "transition" || incoming.style?.startsWith("stateDepartureRamp")
61
+ const shouldMerge = incomingIsTransition && existingIsTransition
62
+ return {
63
+ ...incoming,
64
+ char: shouldMerge
65
+ ? (mergeDiagramLineGlyph(existing.char, incoming.char, "rounded") ?? incoming.char)
66
+ : incoming.char,
67
+ }
68
+ },
69
+ })
70
+ }
71
+
72
+ function setCell(grid: StateGrid, x: number, y: number, char: string, style?: StateCellStyle): void {
73
+ grid.setCell(x, y, char, style)
74
+ }
75
+
76
+ function setText(grid: StateGrid, x: number, y: number, text: string, style?: StateCellStyle): void {
77
+ grid.setText(x, y, text, style)
78
+ }
79
+
80
+ function drawBox(
81
+ grid: StateGrid,
82
+ state: StateDiagramState,
83
+ bounds: BoxBounds,
84
+ lines: string[],
85
+ borderStyle: BorderStyle,
86
+ ): void {
87
+ if (isHiddenCompositeMarker(state)) return
88
+
89
+ if (state.kind !== "state") {
90
+ setCell(grid, bounds.left, bounds.top, state.label, state.kind)
91
+ return
92
+ }
93
+ fillDiagramFrameInterior(bounds, (x, y) => setCell(grid, x, y, " ", "state"))
94
+ drawStateFrame(grid, bounds, BorderChars[borderStyle], "stateBorder")
95
+ lines.forEach((line, index) => {
96
+ setText(grid, bounds.left + 2, bounds.top + 1 + index, line, "state")
97
+ })
98
+ }
99
+
100
+ function drawStateFrame(grid: StateGrid, bounds: BoxBounds, chars: BorderCharacters, style: StateCellStyle): void {
101
+ drawDiagramFrame(bounds, chars, (x, y, char) => setCell(grid, x, y, char, style))
102
+ }
103
+
104
+ function drawContainerFrame(
105
+ grid: StateGrid,
106
+ bounds: BoxBounds,
107
+ label: string,
108
+ chars: BorderCharacters,
109
+ style: StateCellStyle,
110
+ ): void {
111
+ drawDiagramFrame(bounds, chars, (x, y, char) => setCell(grid, x, y, char, style))
112
+ drawContainerLabel(grid, bounds, label, style)
113
+ }
114
+
115
+ function drawContainerLabel(grid: StateGrid, bounds: BoxBounds, label: string, style: StateCellStyle): void {
116
+ if (label) setText(grid, bounds.left + 2, bounds.top, ` ${label} `, style)
117
+ }
118
+
119
+ function noteConnectorGlyph(directions: ReadonlySet<DiagramDirection>): string {
120
+ const chars = BorderChars.double
121
+ const up = directions.has("up")
122
+ const down = directions.has("down")
123
+ const left = directions.has("left")
124
+ const right = directions.has("right")
125
+ if (up && down && left && right) return chars.cross
126
+ if (up && down && right) return chars.leftT
127
+ if (up && down && left) return chars.rightT
128
+ if (left && right && down) return chars.topT
129
+ if (left && right && up) return chars.bottomT
130
+ if (up && right) return chars.bottomLeft
131
+ if (up && left) return chars.bottomRight
132
+ if (down && right) return chars.topLeft
133
+ if (down && left) return chars.topRight
134
+ if (up || down) return chars.vertical
135
+ return chars.horizontal
136
+ }
137
+
138
+ function drawNote(grid: StateGrid, bounds: StateNoteBounds, target: BoxBounds): void {
139
+ const chars = BorderChars.double
140
+ const connector = stateDiagramNoteConnector(bounds, target)
141
+ const points = orthogonalPathPoints(connector.points)
142
+ for (const [index, point] of points.entries()) {
143
+ const directions = new Set<DiagramDirection>()
144
+ const previous = points[index - 1]
145
+ const next = points[index + 1]
146
+ if (previous) directions.add(directionBetween(point, previous)!)
147
+ if (next) directions.add(directionBetween(point, next)!)
148
+ const distanceFromNote = points.length - index - 1
149
+ const style = distanceFromNote < 3 ? NOTE_CONNECTOR_RAMP_STYLES[2 - distanceFromNote]! : "noteConnector"
150
+ setCell(grid, point.x, point.y, noteConnectorGlyph(directions), style)
151
+ }
152
+
153
+ drawContainerFrame(grid, bounds, "", chars, "noteBorder")
154
+ setCell(
155
+ grid,
156
+ bounds.note.position === "right" ? bounds.left : bounds.left + bounds.width - 1,
157
+ connector.connectorY,
158
+ bounds.note.position === "right" ? chars.rightT : chars.leftT,
159
+ "noteBorder",
160
+ )
161
+ bounds.lines.forEach((line, index) => setText(grid, bounds.left + 2, bounds.top + 1 + index, line, "noteText"))
162
+ }
163
+
164
+ function drawTransitionRenderPlan(
165
+ grid: StateGrid,
166
+ plan: StateTransitionRenderPlan,
167
+ arrowHeadStyle: StateDiagramArrowHeadStyle,
168
+ rampDeparture: boolean,
169
+ ): void {
170
+ const departure = new Map(
171
+ rampDeparture
172
+ ? plan.path.slice(0, 3).map(([x, y], index) => [`${x}:${y}`, STATE_DEPARTURE_RAMP_STYLES[index]!])
173
+ : [],
174
+ )
175
+ for (const cell of plan.cells) {
176
+ const char = cell.arrowDirection ? diagramArrowHead(cell.arrowDirection, arrowHeadStyle) : cell.char
177
+ setCell(grid, cell.x, cell.y, char, departure.get(`${cell.x}:${cell.y}`) ?? "transition")
178
+ }
179
+ if (plan.label) {
180
+ plan.label.lines.forEach((line, index) => {
181
+ const y = plan.label!.y + index
182
+ const leftX = plan.label!.x - DIAGRAM_LABEL_PADDING_X
183
+ if (grid.getCell(leftX, y)?.char === " ") setCell(grid, leftX, y, " ", "label")
184
+ setText(grid, plan.label!.x, y, line, "label")
185
+ const rightX = plan.label!.x + diagramTextWidth(line) + DIAGRAM_LABEL_PADDING_X - 1
186
+ if (grid.getCell(rightX, y)?.char === " ") setCell(grid, rightX, y, " ", "label")
187
+ })
188
+ }
189
+ }
190
+
191
+ function drawTransitionJunctionPlans(
192
+ grid: StateGrid,
193
+ diagram: StateDiagram,
194
+ bounds: Map<string, BoxBounds>,
195
+ renderPlans: readonly StateTransitionRenderPlan[],
196
+ ): void {
197
+ for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
198
+ const style = plan.kind === "choice" ? "choice" : "transition"
199
+ const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
200
+ setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
201
+ }
202
+ }
203
+
204
+ export function drawStateDiagramGrid(sourceDiagram: StateDiagram, options: StateDiagramRenderOptions = {}): StateGrid {
205
+ return createStateDiagramDrawing(sourceDiagram, options).grid
206
+ }
207
+
208
+ export function createStateDiagramDrawing(sourceDiagram: StateDiagram, options: StateDiagramRenderOptions = {}) {
209
+ const direction = options.direction ?? sourceDiagram.direction
210
+ if (direction !== "LR" && direction !== "RL") {
211
+ return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
212
+ }
213
+ if (options.layoutMaxWidth === undefined || !Number.isFinite(options.layoutMaxWidth)) {
214
+ return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
215
+ }
216
+ const fallbackDirection = direction === "RL" ? "BT" : "TB"
217
+ const maxWidth = Math.max(1, Math.trunc(options.layoutMaxWidth))
218
+ const drawing = (() => {
219
+ try {
220
+ return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
221
+ } catch (error) {
222
+ if (error instanceof DiagramCanvasSizeError) return undefined
223
+ throw error
224
+ }
225
+ })()
226
+ if (!drawing) return createStateDiagramDrawingWithDirection(sourceDiagram, options, fallbackDirection)
227
+ if (drawing.grid.getTextSize({ trimTop: true, trimBottom: true }).width <= maxWidth) {
228
+ return drawing
229
+ }
230
+ const fallback = createStateDiagramDrawingWithDirection(sourceDiagram, options, fallbackDirection)
231
+ if (
232
+ fallback.grid.getTextSize({ trimTop: true, trimBottom: true }).width >=
233
+ drawing.grid.getTextSize({ trimTop: true, trimBottom: true }).width
234
+ ) {
235
+ return drawing
236
+ }
237
+ return fallback
238
+ }
239
+
240
+ function createStateDiagramDrawingWithDirection(
241
+ sourceDiagram: StateDiagram,
242
+ options: StateDiagramRenderOptions,
243
+ direction: StateDiagram["direction"],
244
+ ) {
245
+ const diagram = prepareVisibleStateDiagram(
246
+ direction === sourceDiagram.direction ? sourceDiagram : { ...sourceDiagram, direction },
247
+ )
248
+ const borderStyle = options.borderStyle ?? DEFAULT_STATE_BORDER_STYLE
249
+ const arrowHeadStyle = options.arrowHeadStyle ?? DEFAULT_STATE_ARROW_HEAD_STYLE
250
+ const minStateGap = normalizeStateMinStateGap(options.minStateGap)
251
+ const searchBudget = createStateSearchBudget()
252
+ const layout = createStateDiagramLayout(diagram, {
253
+ minStateGap,
254
+ searchBudget,
255
+ })
256
+ const { bounds, sizes, compositeBounds, noteBounds } = layout
257
+ let allBounds = [...bounds.values(), ...noteBounds]
258
+ let maxY = Math.max(0, ...allBounds.map((bound) => bound.top + bound.height))
259
+ const feedbackLaneY = maxY + 3
260
+ const feedbackTopY = Math.min(0, ...allBounds.map((bound) => bound.top)) - 3
261
+ expandCompositeBoundsForFeedback(diagram, bounds, compositeBounds, feedbackLaneY)
262
+ let transitionPlans: StateTransitionRenderPlan[] = []
263
+ const separationAttempts = diagram.states.length + diagram.composites.length + 1
264
+ for (let attempt = 0; attempt < separationAttempts; attempt++) {
265
+ transitionPlans = createStateTransitionRenderPlans(diagram, bounds, feedbackLaneY, {
266
+ feedbackTopY,
267
+ noteBounds,
268
+ searchBudget,
269
+ })
270
+ expandCompositeBoundsForInternalTransitions(diagram, compositeBounds, transitionPlans)
271
+ if (!separateExternalBoundsFromComposites(diagram, layout)) break
272
+ if (attempt === separationAttempts - 1) throw new Error("State composite separation did not converge")
273
+ }
274
+ const connectorPoints = noteBounds.flatMap((bound) => bound.connector?.points ?? [])
275
+ const contentLeft = Math.min(
276
+ 0,
277
+ ...[...bounds.values(), ...noteBounds].map((bound) => bound.left),
278
+ ...connectorPoints.map((point) => point.x),
279
+ ...transitionPlans.flatMap((plan) => [
280
+ ...plan.cells.map((cell) => cell.x),
281
+ ...(plan.label ? [plan.label.x - DIAGRAM_LABEL_PADDING_X] : []),
282
+ ]),
283
+ )
284
+ const contentTop = Math.min(
285
+ 0,
286
+ ...[...bounds.values(), ...noteBounds].map((bound) => bound.top),
287
+ ...connectorPoints.map((point) => point.y),
288
+ ...transitionPlans.flatMap((plan) => [...plan.cells.map((cell) => cell.y), ...(plan.label ? [plan.label.y] : [])]),
289
+ )
290
+ if (contentLeft < 0 || contentTop < 0) {
291
+ translateStateDiagramLayout(layout, -contentLeft, -contentTop)
292
+ transitionPlans = translateTransitionPlans(transitionPlans, -contentLeft, -contentTop)
293
+ }
294
+ allBounds = [...bounds.values(), ...noteBounds]
295
+ const translatedConnectorPoints = noteBounds.flatMap((bound) => bound.connector?.points ?? [])
296
+ const maxX = Math.max(
297
+ 0,
298
+ ...allBounds.map((bound) => bound.left + bound.width),
299
+ ...translatedConnectorPoints.map((point) => point.x + 1),
300
+ )
301
+ maxY = Math.max(
302
+ 0,
303
+ ...allBounds.map((bound) => bound.top + bound.height),
304
+ ...translatedConnectorPoints.map((point) => point.y + 1),
305
+ )
306
+ const transitionLabelSizes = diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label))
307
+ const maxTransitionLabelWidth = Math.max(0, ...transitionLabelSizes.map((size) => size.width))
308
+ const maxTransitionLabelLines = Math.max(0, ...transitionLabelSizes.map((size) => size.height))
309
+ const transitionRight = Math.max(
310
+ maxX,
311
+ ...transitionPlans.flatMap((plan) => [
312
+ ...plan.cells.map((cell) => cell.x + 1),
313
+ ...(plan.label
314
+ ? [plan.label.x + measureStateTransitionLabel(plan.route.transition.label).width + DIAGRAM_LABEL_PADDING_X]
315
+ : []),
316
+ ]),
317
+ )
318
+ const transitionBottom = Math.max(
319
+ maxY,
320
+ ...transitionPlans.flatMap((plan) => [
321
+ ...plan.cells.map((cell) => cell.y + 1),
322
+ ...(plan.label ? [plan.label.y + plan.label.lines.length] : []),
323
+ ]),
324
+ )
325
+ const grid = makeGrid(
326
+ Math.max(maxX + Math.max(24, maxTransitionLabelWidth + 4), transitionRight + 2),
327
+ Math.max(maxY + 8 + maxTransitionLabelLines, transitionBottom + 2),
328
+ )
329
+ for (const composite of diagram.composites) {
330
+ const bound = compositeBounds.get(composite.id)
331
+ if (!bound) continue
332
+ drawContainerFrame(grid, bound, composite.label, BorderChars[borderStyle], "composite")
333
+ }
334
+
335
+ for (const state of diagram.states) {
336
+ const bound = bounds.get(state.id)
337
+ const size = sizes.get(state.id)
338
+ if (!bound || !size) continue
339
+ drawBox(grid, state, bound, size.lines, borderStyle)
340
+ }
341
+
342
+ for (const plan of transitionPlans) {
343
+ const source = diagram.states.find((state) => state.id === plan.route.transition.from)
344
+ drawTransitionRenderPlan(grid, plan, arrowHeadStyle, source?.kind === "state")
345
+ }
346
+
347
+ drawTransitionJunctionPlans(grid, diagram, bounds, transitionPlans)
348
+
349
+ for (const composite of diagram.composites) {
350
+ const bound = compositeBounds.get(composite.id)
351
+ if (bound) drawContainerLabel(grid, bound, composite.label, "compositeLabel")
352
+ }
353
+
354
+ for (const noteBound of noteBounds) {
355
+ const target = bounds.get(noteBound.note.target)
356
+ if (target) drawNote(grid, noteBound, target)
357
+ }
358
+
359
+ return { grid, diagram, layout, transitionPlans }
360
+ }
@@ -0,0 +1,15 @@
1
+ export function stateDiagramStartMarkerId(scope?: string): string {
2
+ return scope ? `${scope}.__start` : "__start"
3
+ }
4
+
5
+ export function stateDiagramEndMarkerId(scope?: string): string {
6
+ return scope ? `${scope}.__end` : "__end"
7
+ }
8
+
9
+ export function stateDiagramMarkerId(position: "from" | "to", scope?: string): string {
10
+ return position === "from" ? stateDiagramStartMarkerId(scope) : stateDiagramEndMarkerId(scope)
11
+ }
12
+
13
+ export function normalizeStateDiagramEndpoint(value: string, position: "from" | "to", scope?: string): string {
14
+ return value === "[*]" ? stateDiagramMarkerId(position, scope) : value
15
+ }