@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,44 @@
1
+ export type GanttTaskState = "task" | "active" | "critical" | "done" | "milestone"
2
+
3
+ export interface GanttSection {
4
+ label: string
5
+ }
6
+
7
+ export interface GanttTask {
8
+ label: string
9
+ id?: string
10
+ section?: GanttSection
11
+ start: number
12
+ end: number
13
+ state: GanttTaskState
14
+ }
15
+
16
+ export type GanttEntry = { type: "section"; section: GanttSection } | { type: "task"; task: GanttTask }
17
+
18
+ export interface GanttDiagram {
19
+ title?: string
20
+ dateFormat: string
21
+ axisFormat: string
22
+ tasks: GanttTask[]
23
+ entries: GanttEntry[]
24
+ }
25
+
26
+ export interface GanttDiagramRenderOptions {
27
+ layoutMaxWidth?: number
28
+ style?: GanttRenderStyle
29
+ track?: "dots" | "line"
30
+ endpoints?: "plain" | "points"
31
+ line?: GanttLineStyle
32
+ labels?: GanttLabelLayout
33
+ sections?: "compact" | "spaced"
34
+ trackTone?: GanttTrackTone
35
+ }
36
+
37
+ export type GanttRenderStyle = "rail" | "block" | "capsule" | "points" | "track"
38
+ export type GanttLineStyle = "heavy" | "thin" | "double" | "dashed"
39
+ export type GanttLabelLayout = "right" | "left" | "tree"
40
+ export type GanttTrackTone = "medium" | "dim" | "faint"
41
+
42
+ export type GanttBaseCellStyle = "title" | "axis" | "section" | GanttTaskState
43
+ export type GanttTrackCellStyle = "trackMedium" | "trackDim" | "trackFaint"
44
+ export type GanttCellStyle = GanttBaseCellStyle | GanttTrackCellStyle
@@ -0,0 +1,183 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { MermaidSyntaxError } from "../diagnostics.js"
3
+ import { renderGitGraphDiagram } from "./diagram.js"
4
+ import { drawGitGraphDiagramGrid } from "./drawing.js"
5
+ import { isMermaidGitGraphDiagram, parseMermaidGitGraphDiagram } from "./parser.js"
6
+ import { renderGitGraphGridText } from "./render-grid.js"
7
+ import { resolveGitGraphStyleColors } from "./style.js"
8
+
9
+ describe("GitGraphDiagram", () => {
10
+ test("detects and parses commits, branches, checkout, tags, types, and merges", () => {
11
+ const diagram = parseMermaidGitGraphDiagram(`gitGraph TB:
12
+ commit id: "init"
13
+ branch feature order: 1
14
+ commit id: "api" msg: "Add API" tag: "ready"
15
+ checkout main
16
+ commit id: "docs" type: HIGHLIGHT
17
+ merge feature id: "merge-feature"`)
18
+
19
+ expect(diagram).toEqual({
20
+ direction: "TB",
21
+ branches: [
22
+ { name: "main", order: 0, head: "merge-feature" },
23
+ { name: "feature", order: 1, head: "api" },
24
+ ],
25
+ commits: [
26
+ { id: "init", tags: [], type: "NORMAL", branch: "main", parents: [] },
27
+ { id: "api", message: "Add API", tags: ["ready"], type: "NORMAL", branch: "feature", parents: ["init"] },
28
+ { id: "docs", tags: [], type: "HIGHLIGHT", branch: "main", parents: ["init"] },
29
+ {
30
+ id: "merge-feature",
31
+ tags: [],
32
+ type: "NORMAL",
33
+ branch: "main",
34
+ parents: ["docs", "api"],
35
+ },
36
+ ],
37
+ })
38
+ })
39
+
40
+ test("renders branch and merge transitions beside compact labels", () => {
41
+ const source = `gitGraph
42
+ commit id: "baseline"
43
+ branch refactor
44
+ commit id: "extract-seam" msg: "Extract seam"
45
+ commit id: "add-tests" tag: "ready"
46
+ checkout main
47
+ commit id: "unrelated-fix"
48
+ merge refactor id: "land-refactor" tag: "v2"`
49
+
50
+ expect(renderGitGraphDiagram(source)).toBe(`● baseline
51
+ ├─╮
52
+ │ ● Extract seam
53
+ │ ● add-tests [refactor] [ready]
54
+ ● │ unrelated-fix
55
+ ◎─╯ land-refactor [main] [v2]`)
56
+ })
57
+
58
+ test("uses deterministic generated ids", () => {
59
+ expect(parseMermaidGitGraphDiagram("gitGraph\n commit\n commit").commits.map((commit) => commit.id)).toEqual([
60
+ "commit-1",
61
+ "commit-2",
62
+ ])
63
+ })
64
+
65
+ test("supports shorthand messages and preserves branch heads without direct commits", () => {
66
+ const diagram = parseMermaidGitGraphDiagram(`gitGraph
67
+ commit "Initial release"
68
+ branch feature
69
+ checkout main
70
+ commit id: next`)
71
+
72
+ expect(diagram.commits[0]?.message).toBe("Initial release")
73
+ expect(diagram.branches).toEqual([
74
+ { name: "main", order: 0, head: "next" },
75
+ { name: "feature", head: "commit-1" },
76
+ ])
77
+ expect(
78
+ renderGitGraphDiagram(`gitGraph
79
+ commit id: base
80
+ branch feature
81
+ checkout main
82
+ commit id: next`),
83
+ ).toContain("base [feature]")
84
+ })
85
+
86
+ test("places unordered branches before explicitly ordered branches", () => {
87
+ const diagram = parseMermaidGitGraphDiagram(`gitGraph
88
+ commit id: base
89
+ branch later order: 2
90
+ checkout main
91
+ branch ordinary
92
+ checkout main
93
+ branch earlier order: 1`)
94
+
95
+ expect(diagram.branches.map((branch) => branch.name)).toEqual(["main", "ordinary", "earlier", "later"])
96
+ })
97
+
98
+ test("keeps comment markers inside quoted labels", () => {
99
+ expect(parseMermaidGitGraphDiagram('gitGraph\n commit id: "release%%candidate" %% comment').commits[0]?.id).toBe(
100
+ "release%%candidate",
101
+ )
102
+ })
103
+
104
+ test("uses rounded routing for wide lane transitions", () => {
105
+ expect(
106
+ renderGitGraphDiagram(`gitGraph
107
+ commit id: base
108
+ branch one
109
+ branch two
110
+ commit id: work`),
111
+ ).toBe(`● base [main] [one]
112
+ ├───╮
113
+ ● work [two]`)
114
+ })
115
+
116
+ test("preserves direction semantics while rendering vertically", () => {
117
+ const source = "gitGraph BT:\n commit id: one"
118
+ const diagram = parseMermaidGitGraphDiagram(source)
119
+ expect(diagram.direction).toBe("BT")
120
+ expect(renderGitGraphGridText(drawGitGraphDiagramGrid(diagram, { direction: "LR" }))).toBe(
121
+ renderGitGraphDiagram(source),
122
+ )
123
+ })
124
+
125
+ test("reports semantic failures with source diagnostics", () => {
126
+ expect(() => parseMermaidGitGraphDiagram("gitGraph\n checkout missing")).toThrow(
127
+ new MermaidSyntaxError("gitGraph", 2, "checkout missing", 'Unknown branch "missing"'),
128
+ )
129
+ expect(() => parseMermaidGitGraphDiagram("gitGraph\n cherry-pick id: one")).toThrow(
130
+ new MermaidSyntaxError("gitGraph", 2, "cherry-pick id: one", "Cherry-pick is not supported"),
131
+ )
132
+ expect(() => parseMermaidGitGraphDiagram("gitGraph\n commit id: same\n commit id: same")).toThrow(
133
+ 'Duplicate commit id "same"',
134
+ )
135
+ expect(() => parseMermaidGitGraphDiagram("gitGraph\n branch feature\n checkout main\n branch feature")).toThrow(
136
+ 'Duplicate branch "feature"',
137
+ )
138
+ expect(() =>
139
+ parseMermaidGitGraphDiagram("gitGraph\n branch feature\n commit id: work\n checkout main\n merge feature"),
140
+ ).toThrow('Branch "main" has no commits')
141
+ })
142
+
143
+ test("draws semantic styles for rails, commit types, merges, and labels", () => {
144
+ const grid = drawGitGraphDiagramGrid(
145
+ parseMermaidGitGraphDiagram(`gitGraph
146
+ commit id: base
147
+ branch feature
148
+ commit id: work type: REVERSE
149
+ checkout main
150
+ commit id: checkpoint type: HIGHLIGHT
151
+ merge feature id: done`),
152
+ )
153
+ const styles = new Set(grid.rows.flatMap((row) => row.map((cell) => cell.style).filter(Boolean)))
154
+
155
+ expect(styles).toEqual(new Set(["branch0", "branch1", "commit", "reverse", "highlight", "merge", "label"]))
156
+ expect(Object.keys(resolveGitGraphStyleColors()).sort()).toEqual(
157
+ [
158
+ "branch0",
159
+ "branch1",
160
+ "branch2",
161
+ "branch3",
162
+ "branch4",
163
+ "branch5",
164
+ "branch6",
165
+ "branch7",
166
+ "commit",
167
+ "highlight",
168
+ "label",
169
+ "merge",
170
+ "reverse",
171
+ ].sort(),
172
+ )
173
+ })
174
+
175
+ test("recognizes only GitGraph headers", () => {
176
+ expect(isMermaidGitGraphDiagram("%% comment\ngitGraph LR:\n commit")).toBe(true)
177
+ expect(isMermaidGitGraphDiagram("graph LR\n A --> B")).toBe(false)
178
+ expect(() => parseMermaidGitGraphDiagram("commit id: missing-header")).toThrow("GitGraph header is required")
179
+ expect(() => parseMermaidGitGraphDiagram("gitGraph\n commit\n gitGraph")).toThrow(
180
+ "GitGraph header can only appear once",
181
+ )
182
+ })
183
+ })
@@ -0,0 +1,8 @@
1
+ import { drawGitGraphDiagramGrid } from "./drawing.js"
2
+ import { parseMermaidGitGraphDiagram } from "./parser.js"
3
+ import { renderGitGraphGridText } from "./render-grid.js"
4
+ import type { GitGraphDiagramRenderOptions } from "./types.js"
5
+
6
+ export function renderGitGraphDiagram(content: string, options: GitGraphDiagramRenderOptions = {}): string {
7
+ return renderGitGraphGridText(drawGitGraphDiagramGrid(parseMermaidGitGraphDiagram(content), options))
8
+ }
@@ -0,0 +1,234 @@
1
+ import { DiagramCanvas } from "../core/canvas.js"
2
+ import { diagramTextWidth } from "../core/text.js"
3
+ import type { GitGraphGrid } from "./render-grid.js"
4
+ import type { GitGraphCellStyle, GitGraphCommit, GitGraphDiagram, GitGraphDiagramRenderOptions } from "./types.js"
5
+
6
+ interface BranchSpan {
7
+ first: number
8
+ last: number
9
+ }
10
+
11
+ interface Connections {
12
+ up?: boolean
13
+ down?: boolean
14
+ left?: boolean
15
+ right?: boolean
16
+ style: GitGraphCellStyle
17
+ }
18
+
19
+ const LANE_WIDTH = 2
20
+ const LABEL_GAP = 2
21
+
22
+ export function drawGitGraphDiagramGrid(
23
+ diagram: GitGraphDiagram,
24
+ _options: GitGraphDiagramRenderOptions = {},
25
+ ): GitGraphGrid {
26
+ if (diagram.commits.length === 0) return new DiagramCanvas(0, 0)
27
+ const laneByBranch = new Map(diagram.branches.map((branch, index) => [branch.name, index]))
28
+ const commitById = new Map(diagram.commits.map((commit) => [commit.id, commit]))
29
+ const spans = branchSpans(diagram, commitById)
30
+ const heads = branchHeads(diagram)
31
+ const graphWidth = (diagram.branches.length - 1) * LANE_WIDTH + 1
32
+ let labelWidth = 0
33
+ for (const commit of diagram.commits) labelWidth = Math.max(labelWidth, diagramTextWidth(commitLabel(commit, heads)))
34
+ const forks = diagram.commits.map((commit) => isFork(commit, laneByBranch, commitById))
35
+ const height = diagram.commits.length + forks.filter(Boolean).length
36
+ const grid: GitGraphGrid = new DiagramCanvas(graphWidth + LABEL_GAP + labelWidth, height)
37
+
38
+ let row = 0
39
+ diagram.commits.forEach((commit, index) => {
40
+ if (forks[index]) {
41
+ drawTransitionRow(grid, spans, laneByBranch, commitById, commit, index, row)
42
+ row += 1
43
+ }
44
+ drawCommitRow(grid, diagram, spans, laneByBranch, commitById, commit, index, row)
45
+ grid.setText(graphWidth + LABEL_GAP, row, commitLabel(commit, heads), "label")
46
+ row += 1
47
+ })
48
+ return grid
49
+ }
50
+
51
+ function drawTransitionRow(
52
+ grid: GitGraphGrid,
53
+ spans: Map<string, BranchSpan>,
54
+ laneByBranch: Map<string, number>,
55
+ commitById: Map<string, GitGraphCommit>,
56
+ commit: GitGraphCommit,
57
+ index: number,
58
+ y: number,
59
+ ): void {
60
+ const cells = new Map<number, Connections>()
61
+ for (const [branch, span] of spans) {
62
+ if (span.first >= index || span.last < index) continue
63
+ const lane = laneByBranch.get(branch)!
64
+ connect(cells, lane * LANE_WIDTH, { up: true, down: true }, branchStyle(lane))
65
+ }
66
+
67
+ const lane = laneByBranch.get(commit.branch)!
68
+ const firstParent = commit.parents[0] === undefined ? undefined : commitById.get(commit.parents[0])
69
+ if (firstParent && firstParent.branch !== commit.branch) {
70
+ const parentLane = laneByBranch.get(firstParent.branch)!
71
+ connectHorizontal(
72
+ cells,
73
+ parentLane,
74
+ lane,
75
+ { sourceUp: true, sourceDown: true, targetDown: true },
76
+ branchStyle(lane),
77
+ )
78
+ }
79
+ paintConnections(grid, cells, y)
80
+ }
81
+
82
+ function drawCommitRow(
83
+ grid: GitGraphGrid,
84
+ diagram: GitGraphDiagram,
85
+ spans: Map<string, BranchSpan>,
86
+ laneByBranch: Map<string, number>,
87
+ commitById: Map<string, GitGraphCommit>,
88
+ commit: GitGraphCommit,
89
+ index: number,
90
+ y: number,
91
+ ): void {
92
+ const cells = new Map<number, Connections>()
93
+ for (const branch of diagram.branches) {
94
+ const span = spans.get(branch.name)
95
+ if (!span || span.first > index || (span.last <= index && branch.name !== commit.branch)) continue
96
+ const lane = laneByBranch.get(branch.name)!
97
+ connect(cells, lane * LANE_WIDTH, { up: index > 0, down: span.last > index }, branchStyle(lane))
98
+ }
99
+
100
+ const lane = laneByBranch.get(commit.branch)!
101
+ const secondParent = commit.parents[1] === undefined ? undefined : commitById.get(commit.parents[1])
102
+ if (secondParent) {
103
+ const parentLane = laneByBranch.get(secondParent.branch)!
104
+ connectHorizontal(cells, lane, parentLane, { sourceUp: true, targetUp: true }, branchStyle(parentLane))
105
+ }
106
+ paintConnections(grid, cells, y)
107
+ grid.setCell(lane * LANE_WIDTH, y, commitGlyph(commit), commitStyle(commit))
108
+ }
109
+
110
+ function connectHorizontal(
111
+ cells: Map<number, Connections>,
112
+ sourceLane: number,
113
+ targetLane: number,
114
+ vertical: { sourceUp?: boolean; sourceDown?: boolean; targetUp?: boolean; targetDown?: boolean },
115
+ style: GitGraphCellStyle,
116
+ ): void {
117
+ if (sourceLane === targetLane) return
118
+ const source = sourceLane * LANE_WIDTH
119
+ const target = targetLane * LANE_WIDTH
120
+ const direction = Math.sign(target - source)
121
+ connect(
122
+ cells,
123
+ source,
124
+ { ...verticalAt(vertical.sourceUp, vertical.sourceDown), ...(direction > 0 ? { right: true } : { left: true }) },
125
+ style,
126
+ )
127
+ for (let x = source + direction; x !== target; x += direction) {
128
+ connect(cells, x, { left: true, right: true }, style)
129
+ }
130
+ connect(
131
+ cells,
132
+ target,
133
+ { ...verticalAt(vertical.targetUp, vertical.targetDown), ...(direction > 0 ? { left: true } : { right: true }) },
134
+ style,
135
+ )
136
+ }
137
+
138
+ function verticalAt(up: boolean | undefined, down: boolean | undefined): Pick<Connections, "up" | "down"> {
139
+ return { ...(up ? { up: true } : {}), ...(down ? { down: true } : {}) }
140
+ }
141
+
142
+ function connect(
143
+ cells: Map<number, Connections>,
144
+ x: number,
145
+ additions: Omit<Connections, "style">,
146
+ style: GitGraphCellStyle,
147
+ ): void {
148
+ const current = cells.get(x)
149
+ cells.set(x, { ...current, ...additions, style: current?.style ?? style })
150
+ }
151
+
152
+ function paintConnections(grid: GitGraphGrid, cells: Map<number, Connections>, y: number): void {
153
+ for (const [x, connections] of cells) grid.setCell(x, y, connectionGlyph(connections), connections.style)
154
+ }
155
+
156
+ function connectionGlyph({ up, down, left, right }: Connections): string {
157
+ const mask = `${up ? 1 : 0}${down ? 1 : 0}${left ? 1 : 0}${right ? 1 : 0}`
158
+ const glyphs: Record<string, string> = {
159
+ "1100": "│",
160
+ "0011": "─",
161
+ "0101": "╭",
162
+ "0110": "╮",
163
+ "1001": "╰",
164
+ "1010": "╯",
165
+ "1101": "├",
166
+ "1110": "┤",
167
+ "0111": "┬",
168
+ "1011": "┴",
169
+ "1111": "┼",
170
+ "1000": "│",
171
+ "0100": "│",
172
+ "0010": "─",
173
+ "0001": "─",
174
+ }
175
+ return glyphs[mask] ?? " "
176
+ }
177
+
178
+ function branchSpans(diagram: GitGraphDiagram, commitById: Map<string, GitGraphCommit>): Map<string, BranchSpan> {
179
+ const spans = new Map<string, BranchSpan>()
180
+ diagram.commits.forEach((commit, index) => {
181
+ const span = spans.get(commit.branch)
182
+ if (span) span.last = index
183
+ else spans.set(commit.branch, { first: index, last: index })
184
+ for (const parentId of commit.parents) {
185
+ const parent = commitById.get(parentId)
186
+ if (!parent || parent.branch === commit.branch) continue
187
+ const parentSpan = spans.get(parent.branch)
188
+ if (parentSpan) parentSpan.last = Math.max(parentSpan.last, index)
189
+ }
190
+ })
191
+ return spans
192
+ }
193
+
194
+ function branchHeads(diagram: GitGraphDiagram): Map<string, string[]> {
195
+ const heads = new Map<string, string[]>()
196
+ for (const branch of diagram.branches) {
197
+ if (branch.head === undefined) continue
198
+ const names = heads.get(branch.head) ?? []
199
+ names.push(branch.name)
200
+ heads.set(branch.head, names)
201
+ }
202
+ return heads
203
+ }
204
+
205
+ function isFork(
206
+ commit: GitGraphCommit,
207
+ laneByBranch: Map<string, number>,
208
+ commitById: Map<string, GitGraphCommit>,
209
+ ): boolean {
210
+ const parent = commit.parents[0] === undefined ? undefined : commitById.get(commit.parents[0])
211
+ return parent !== undefined && laneByBranch.get(parent.branch) !== laneByBranch.get(commit.branch)
212
+ }
213
+
214
+ function commitGlyph(commit: GitGraphCommit): string {
215
+ if (commit.type === "REVERSE") return "⊗"
216
+ if (commit.type === "HIGHLIGHT") return "◆"
217
+ return commit.parents.length > 1 ? "◎" : "●"
218
+ }
219
+
220
+ function commitStyle(commit: GitGraphCommit): GitGraphCellStyle {
221
+ if (commit.type === "REVERSE") return "reverse"
222
+ if (commit.type === "HIGHLIGHT") return "highlight"
223
+ return commit.parents.length > 1 ? "merge" : "commit"
224
+ }
225
+
226
+ function commitLabel(commit: GitGraphCommit, heads: Map<string, string[]>): string {
227
+ const subject = commit.message ?? commit.id
228
+ const decorations = [...(heads.get(commit.id) ?? []), ...commit.tags].map((value) => `[${value}]`)
229
+ return decorations.length === 0 ? subject : `${subject} ${decorations.join(" ")}`
230
+ }
231
+
232
+ function branchStyle(lane: number): GitGraphCellStyle {
233
+ return `branch${lane % 8}` as GitGraphCellStyle
234
+ }
@@ -0,0 +1,219 @@
1
+ import { firstMeaningfulMermaidLine, meaningfulNumberedMermaidLines, stripMermaidQuotes } from "../core/mermaid.js"
2
+ import { MermaidSyntaxError } from "../diagnostics.js"
3
+ import type { GitGraphBranch, GitGraphCommit, GitGraphCommitType, GitGraphDiagram, GitGraphDirection } from "./types.js"
4
+
5
+ const HEADER_RE = /^gitGraph(?:\s+(LR|TB|BT))?\s*:?$/i
6
+ const ACCESSIBILITY_RE = /^acc(?:Title|Descr)(?::|\s|$)/i
7
+
8
+ export function isMermaidGitGraphDiagram(content: string): boolean {
9
+ return HEADER_RE.test(firstMeaningfulMermaidLine(content) ?? "")
10
+ }
11
+
12
+ export function parseMermaidGitGraphDiagram(content: string): GitGraphDiagram {
13
+ const firstLine = firstMeaningfulMermaidLine(content)
14
+ if (!HEADER_RE.test(firstLine ?? "")) throw syntaxError(1, firstLine ?? "", "GitGraph header is required")
15
+ const branches: GitGraphBranch[] = [{ name: "main", order: 0 }]
16
+ const commits: GitGraphCommit[] = []
17
+ const heads = new Map<string, string | undefined>([["main", undefined]])
18
+ const ids = new Set<string>()
19
+ let direction: GitGraphDirection = "LR"
20
+ let currentBranch = "main"
21
+ let generatedId = 1
22
+ let inAccessibilityDescription = false
23
+ let headerSeen = false
24
+
25
+ for (const source of meaningfulNumberedMermaidLines(content)) {
26
+ const line = stripComment(source.text)
27
+ if (inAccessibilityDescription) {
28
+ if (line === "}") inAccessibilityDescription = false
29
+ continue
30
+ }
31
+ if (/^accDescr\s*\{$/i.test(line)) {
32
+ inAccessibilityDescription = true
33
+ continue
34
+ }
35
+ if (!line || ACCESSIBILITY_RE.test(line) || /^title(?:\s|$)/i.test(line)) continue
36
+
37
+ const header = line.match(HEADER_RE)
38
+ if (header) {
39
+ if (headerSeen) throw syntaxError(source.lineNumber, line, "GitGraph header can only appear once")
40
+ headerSeen = true
41
+ direction = (header[1]?.toUpperCase() as GitGraphDirection | undefined) ?? "LR"
42
+ continue
43
+ }
44
+
45
+ const [command = "", ...rest] = tokenize(line)
46
+ const operation = command.toLowerCase()
47
+ if (operation === "commit") {
48
+ const shorthandMessage = rest[0]?.match(/^(["']).*\1$/) ? stripMermaidQuotes(rest.shift()!) : undefined
49
+ const attributes = parseAttributes(rest, source.lineNumber, line, ["id", "msg", "tag", "type"])
50
+ const id = single(attributes, "id", source.lineNumber, line) ?? `commit-${generatedId++}`
51
+ if (!id) throw syntaxError(source.lineNumber, line, "GitGraph commit id cannot be empty")
52
+ if (ids.has(id)) throw syntaxError(source.lineNumber, line, `Duplicate commit id "${id}"`)
53
+ const type = parseCommitType(single(attributes, "type", source.lineNumber, line), source.lineNumber, line)
54
+ const parent = heads.get(currentBranch)
55
+ const message = single(attributes, "msg", source.lineNumber, line) ?? shorthandMessage
56
+ const commit: GitGraphCommit = {
57
+ id,
58
+ ...(message === undefined ? {} : { message }),
59
+ tags: attributes.get("tag") ?? [],
60
+ type,
61
+ branch: currentBranch,
62
+ parents: parent === undefined ? [] : [parent],
63
+ }
64
+ commits.push(commit)
65
+ ids.add(id)
66
+ heads.set(currentBranch, id)
67
+ continue
68
+ }
69
+
70
+ if (operation === "branch") {
71
+ if (rest.length === 0) throw syntaxError(source.lineNumber, line, "GitGraph branch name cannot be empty")
72
+ const name = stripMermaidQuotes(rest[0]!)
73
+ if (!name) throw syntaxError(source.lineNumber, line, "GitGraph branch name cannot be empty")
74
+ if (heads.has(name)) throw syntaxError(source.lineNumber, line, `Duplicate branch "${name}"`)
75
+ const attributes = parseAttributes(rest.slice(1), source.lineNumber, line, ["order"])
76
+ const orderValue = single(attributes, "order", source.lineNumber, line)
77
+ const order = orderValue === undefined ? undefined : Number(orderValue)
78
+ if (order !== undefined && (!Number.isInteger(order) || order < 0)) {
79
+ throw syntaxError(source.lineNumber, line, "GitGraph branch order must be a non-negative integer")
80
+ }
81
+ branches.push({ name, ...(order === undefined ? {} : { order }) })
82
+ heads.set(name, heads.get(currentBranch))
83
+ currentBranch = name
84
+ continue
85
+ }
86
+
87
+ if (operation === "checkout" || operation === "switch") {
88
+ if (rest.length !== 1) throw syntaxError(source.lineNumber, line, `GitGraph ${operation} requires one branch`)
89
+ const name = stripMermaidQuotes(rest[0]!)
90
+ if (!heads.has(name)) throw syntaxError(source.lineNumber, line, `Unknown branch "${name}"`)
91
+ currentBranch = name
92
+ continue
93
+ }
94
+
95
+ if (operation === "merge") {
96
+ if (rest.length === 0) throw syntaxError(source.lineNumber, line, "GitGraph merge requires a branch")
97
+ const branch = stripMermaidQuotes(rest[0]!)
98
+ if (!heads.has(branch)) throw syntaxError(source.lineNumber, line, `Unknown branch "${branch}"`)
99
+ if (branch === currentBranch)
100
+ throw syntaxError(source.lineNumber, line, "GitGraph cannot merge a branch into itself")
101
+ const currentHead = heads.get(currentBranch)
102
+ const mergedHead = heads.get(branch)
103
+ if (currentHead === undefined)
104
+ throw syntaxError(source.lineNumber, line, `Branch "${currentBranch}" has no commits`)
105
+ if (mergedHead === undefined) throw syntaxError(source.lineNumber, line, `Branch "${branch}" has no commits`)
106
+ if (currentHead === mergedHead)
107
+ throw syntaxError(source.lineNumber, line, `Branches already share head "${mergedHead}"`)
108
+ const attributes = parseAttributes(rest.slice(1), source.lineNumber, line, ["id", "tag", "type"])
109
+ const id = single(attributes, "id", source.lineNumber, line) ?? `commit-${generatedId++}`
110
+ if (ids.has(id)) throw syntaxError(source.lineNumber, line, `Duplicate commit id "${id}"`)
111
+ const commit: GitGraphCommit = {
112
+ id,
113
+ tags: attributes.get("tag") ?? [],
114
+ type: parseCommitType(single(attributes, "type", source.lineNumber, line), source.lineNumber, line),
115
+ branch: currentBranch,
116
+ parents: [currentHead, mergedHead],
117
+ }
118
+ commits.push(commit)
119
+ ids.add(id)
120
+ heads.set(currentBranch, id)
121
+ continue
122
+ }
123
+
124
+ if (operation === "cherry-pick") {
125
+ throw syntaxError(source.lineNumber, line, "Cherry-pick is not supported")
126
+ }
127
+ throw syntaxError(source.lineNumber, line)
128
+ }
129
+
130
+ const resolvedBranches = branches.map((branch) => {
131
+ const head = heads.get(branch.name)
132
+ return { ...branch, ...(head === undefined ? {} : { head }) }
133
+ })
134
+ return { direction, branches: orderBranches(resolvedBranches), commits }
135
+ }
136
+
137
+ function tokenize(line: string): string[] {
138
+ const tokens: string[] = []
139
+ let token = ""
140
+ let quote: '"' | "'" | undefined
141
+ for (const char of line) {
142
+ if ((char === '"' || char === "'") && (quote === undefined || quote === char)) {
143
+ quote = quote === char ? undefined : char
144
+ token += char
145
+ continue
146
+ }
147
+ if (/\s/.test(char) && quote === undefined) {
148
+ if (token) tokens.push(token)
149
+ token = ""
150
+ continue
151
+ }
152
+ token += char
153
+ }
154
+ if (quote !== undefined) return [line]
155
+ if (token) tokens.push(token)
156
+ return tokens
157
+ }
158
+
159
+ function parseAttributes(
160
+ tokens: string[],
161
+ lineNumber: number,
162
+ line: string,
163
+ allowed: readonly string[],
164
+ ): Map<string, string[]> {
165
+ const result = new Map<string, string[]>()
166
+ for (let index = 0; index < tokens.length; index += 1) {
167
+ const keyToken = tokens[index]!
168
+ const separator = keyToken.indexOf(":")
169
+ const key = (separator < 0 ? keyToken : keyToken.slice(0, separator)).toLowerCase()
170
+ if (!allowed.includes(key)) throw syntaxError(lineNumber, line, `Unsupported GitGraph attribute "${key}"`)
171
+ const inline = separator < 0 ? "" : keyToken.slice(separator + 1)
172
+ const valueToken = inline || tokens[++index]
173
+ if (valueToken === undefined) throw syntaxError(lineNumber, line, `GitGraph attribute "${key}" requires a value`)
174
+ const values = result.get(key) ?? []
175
+ values.push(stripMermaidQuotes(valueToken))
176
+ result.set(key, values)
177
+ }
178
+ return result
179
+ }
180
+
181
+ function single(attributes: Map<string, string[]>, key: string, lineNumber: number, line: string): string | undefined {
182
+ const values = attributes.get(key)
183
+ if (values && values.length > 1) throw syntaxError(lineNumber, line, `GitGraph attribute "${key}" cannot repeat`)
184
+ return values?.[0]
185
+ }
186
+
187
+ function parseCommitType(value: string | undefined, lineNumber: number, line: string): GitGraphCommitType {
188
+ if (value === undefined) return "NORMAL"
189
+ const type = value.toUpperCase()
190
+ if (type === "NORMAL" || type === "REVERSE" || type === "HIGHLIGHT") return type
191
+ throw syntaxError(lineNumber, line, `Unknown GitGraph commit type "${value}"`)
192
+ }
193
+
194
+ function orderBranches(branches: GitGraphBranch[]): GitGraphBranch[] {
195
+ const main = branches[0]!
196
+ const rest = branches.slice(1).map((branch, index) => ({ branch, index }))
197
+ const unordered = rest.filter(({ branch }) => branch.order === undefined)
198
+ const ordered = rest
199
+ .filter(({ branch }) => branch.order !== undefined)
200
+ .sort((left, right) => left.branch.order! - right.branch.order! || left.index - right.index)
201
+ return [main, ...unordered.map(({ branch }) => branch), ...ordered.map(({ branch }) => branch)]
202
+ }
203
+
204
+ function stripComment(value: string): string {
205
+ let quote: '"' | "'" | undefined
206
+ for (let index = 0; index < value.length - 1; index += 1) {
207
+ const char = value[index]
208
+ if ((char === '"' || char === "'") && (quote === undefined || quote === char)) {
209
+ quote = quote === char ? undefined : char
210
+ continue
211
+ }
212
+ if (quote === undefined && char === "%" && value[index + 1] === "%") return value.slice(0, index).trim()
213
+ }
214
+ return value.trim()
215
+ }
216
+
217
+ function syntaxError(lineNumber: number, sourceLine: string, reason?: string): MermaidSyntaxError {
218
+ return new MermaidSyntaxError("gitGraph", lineNumber, sourceLine, reason)
219
+ }