Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: Mermaid flowcharts ⇄ slides-shaped diagram elements (pure parser + layered layout, no UI) (#575)

nyblnet4eaf4de02d98
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e1c05167..fca50261 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -267,6 +267,17 @@ jobs:
# rows. Needs the shell built above; a skip in CI is a failure.
run: node scripts/test-spaces-chrome.ts
+ - name: Mermaid flowchart ⇄ diagram rig
+ # spaces/src/diagram/: our own Mermaid flowchart parser and layered
+ # layout (the mermaid library is megabytes and nothing is fetched at
+ # runtime). Over a corpus of real README flowcharts: no overlapping
+ # nodes, every connector end exactly where slides' syncConnectors puts
+ # it, byte-identical snapshots, and mermaid → elements → mermaid
+ # semantically equal. Hostile input (caps, __proto__ ids, script in
+ # labels, pathological cycles) inside a time budget, and a size budget
+ # (needs slides' esbuild, installed above).
+ run: node scripts/test-diagram-mermaid.ts
+
- name: spaces rig manifest
# Bookkeeping, not a ninth run of the eight steps above. scripts/
# test-spaces.mjs is the local entry point for the spaces suite (two of
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index b6fe4b91..4509aa6b 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -8799,3 +8799,108 @@ buttons and menus to those values, and checks that every member lands after
the caret's block and is undone in one step. It also checks that `/` agrees
with the bar, that the tiers drop the words and fold the group, and that every
command is still reachable from its new home.
+
+## 2026-09-26 — Mermaid flowcharts: our own parser and layout, and labels are inert text
+
+A diagram can carry Mermaid source, so a page round-trips through Markdown
+(```` ```mermaid ```` renders on GitHub) and an agent can write one. The
+mermaid library is megabytes and nothing may be fetched at runtime (PLATFORM
+§1), so `spaces/src/diagram/` has its own reader: `mermaid.ts` (parser, element
+output, reverse) and `layout.ts` (a layered layout). Neither imports app code
+— the element types are structural copies of slides' — so either app can use
+them, and they are a candidate for the kernel beside the connector engine.
+Nothing calls them yet; the rig is `scripts/test-diagram-mermaid.ts`.
+
+**The target is slides' elements, not a picture.** Nodes are shape elements
+(rect, rounded and stadium by radius, ellipse, triangle, and fixed 100×100
+path templates for the rest), labels are text elements, and edges are
+line/path shapes with `from`/`to` ConnectorEnd refs (`side: 'auto'`). Each
+connector end is written exactly where slides' `syncConnectors` would put it,
+so an edited diagram does not jump on its first edit. Self-loops are the one
+exception: they pin sides, because with `auto` both ends would collapse to
+the node's centre. Slides has no edge labels, so an edge label is a text
+element beside the edge's middle. It does not follow the edge when a node
+moves.
+
+**It is lossy both ways, and says so.** Mermaid → elements invents positions.
+An optional `layout` sidecar (`{id: {x,y,w,h}}`, made by `diagramLayout`)
+makes hand-placed positions win, and new nodes are placed around them.
+Elements → mermaid drops positions, sizes and edge length (`--->`), and
+returns `lost: [{el, what}]` for everything else it cannot say: rotation,
+opacity, gradients, shadows, rich text, tips mermaid has no arrow for, edge
+colour, free text, unanchored lines, and element types. Node and subgraph
+colours survive as `style` statements.
+
+**Labels are text.** `<br>` is a line break and every other tag stays
+literal, escaped and inert. Mermaid would render `<b>`; we show it. The
+emitted source writes `<` and `>` as `#lt;`/`#gt;` so GitHub shows what we
+show. Style is limited to fill/stroke/color. Colours are validated (hex,
+rgb/hsl functions, and named colours by shape — letters only), so a style
+can never carry `url(…)` or a `;` into an element.
+
+**Subgraphs follow mermaid's two rules.**
+
+- **A subgraph none of whose members links outside it is laid out on its
+ own** and then takes part in its parent as a single node. It uses its own
+ `direction`, or the parent's turned (TB becomes LR, anything else becomes
+ TB); the turn is mermaid's, and it is why the docs' "two" draws sideways.
+- **A subgraph whose members DO link outside is a compound.** Its members
+ take part in the parent's layering and ordering, kept contiguous in every
+ layer. Sibling subgraphs keep one order in every layer, so each box is a
+ rectangle. Each box's left and right borders are single variables, solved
+ together with everything around them, so no node that is not a member
+ lands inside a box.
+ - A bend point belongs to the innermost subgraph holding both ends of its
+ edge, so edges between subgraphs bend in the space between the boxes.
+ - Mermaid ignores `direction` on such a subgraph. So do we, and we warn.
+ - An edge drawn to a compound box is laid out against one of its members,
+ so it is drawn straight.
+
+This replaced a first version that laid every subgraph out alone. That
+version could never let one subgraph stand beside another spanning
+subgraph, and it drew edges through other subgraphs: on the corpus, 14 edges
+ran through nodes and 5 through boxes, against 2 and 2 now. The rig ratchets
+both counts, labels sitting on other edges, and total connector length and
+area; they may only go down.
+
+**Edge labels step off other edges.** A label tries the layout's spot, then
+the other side of its edge, then positions further along it. The first spot
+that crosses no other edge and covers no node or label wins. In a crowded
+fan with nothing clear, the layout's spot stands.
+
+**Caps, not hangs.** 500 nodes, 2,000 edges, subgraphs 24 deep, and a budget
+for long-edge bends. Past a cap the rest is dropped with a warning. A
+statement that cannot be read is dropped whole, with a warning. Unsupported
+syntax (`click`, `linkStyle`, directives, other diagram types) produces a
+warning and never throws.
+
+## 2026-10-09 — Mermaid diagrams take the kernel diagram engine's types and geometry
+
+Supersedes one sentence of the 2026-09-26 Mermaid entry: the element types are
+no longer structural copies of slides'. Since the diagram-engine lift (#592,
+#616, #619), `spaces/src/diagram/` imports them from the kernel — `ShapeSpec`
+(shape.ts), `TipKind` (tips.ts), `Box`/`Pt`/`ConnectorSide` (geom.ts), all
+type-only — and computes with the kernel's own pure geometry:
+`connectorEndpoint` places every connector end (the exact call slides'
+`syncConnectors` makes) and `anchorsToPath` writes every curve. The module is
+still DOM-free and imports no app code. `ConnectorEnd` stays declared locally
+over `ConnectorSide`, because the kernel deliberately keeps that format type in
+slides; text elements are not in the kernel yet, so `DText` is still a copy.
+
+**Curves are written the way the curve editor writes them.** A bent connector's
+anchors are rounded to 0.01 BEFORE the Catmull-Rom handles are computed, as
+slides' `setPathAnchors` does, so its `d` is byte-for-byte what slides would
+write for the same anchors. Before, the handles were computed from unrounded
+anchors and could differ by 0.01; 13 corpus snapshots moved for that reason
+alone (no node, end or label moved). The rig now asserts
+`anchorsToPath(parseAnchors(d)) === d` for every bent connector, with a
+negative control, and checks connector ends against the kernel helper itself
+rather than a copy of its formula.
+
+**Still missing in the kernel, and not built here** (the kernel zone's):
+connector ends land on the BOUNDING BOX of every node, so an edge into a
+diamond, circle or hexagon stops short of the outline (`borderPoint` is not
+shape-aware); diamond, hexagon, cylinder and the other closed outlines are
+`path` shapes, which `isLineLike` hands to the line/curve editor; and an edge
+or node label is a free text element, because nothing binds a label to its
+element.
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-chaining.mmd b/scripts/fixtures/mermaid-flowcharts/docs-chaining.mmd
new file mode 100644
index 00000000..97c54c53
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-chaining.mmd
@@ -0,0 +1,4 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart TB
+ A & B--> C & D
+ a --> b & c--> d
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-christmas.mmd b/scripts/fixtures/mermaid-flowcharts/docs-christmas.mmd
new file mode 100644
index 00000000..3e9f629d
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-christmas.mmd
@@ -0,0 +1,7 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart TD
+ A[Christmas] -->|Get money| B(Go shopping)
+ B --> C{Let me think}
+ C -->|One| D[Laptop]
+ C -->|Two| E[iPhone]
+ C -->|Three| F[fa:fa-car Car]
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-entities.mmd b/scripts/fixtures/mermaid-flowcharts/docs-entities.mmd
new file mode 100644
index 00000000..21f7d3c1
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-entities.mmd
@@ -0,0 +1,4 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart LR
+ A["A double quote:#quot;"] --> B["A dec char:#9829;"]
+ C["Entity &amp; more"] --> D["line one<br>line two"]
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-links.mmd b/scripts/fixtures/mermaid-flowcharts/docs-links.mmd
new file mode 100644
index 00000000..b040ed5c
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-links.mmd
@@ -0,0 +1,20 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart LR
+ A-->B
+ A --- B2
+ A-- This is the text! ---C
+ A---|This is the text|D
+ A-->|text|E
+ A-- text -->F
+ A-.->G
+ A-. text .-> H
+ A ==> I
+ A == text ==> J
+ A ~~~ K
+ A --o L
+ A --x M
+ N <--> O
+ P o--o Q
+ R x--x S
+ T ---> U
+ V -- text ----> W
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-markdown-v11.mmd b/scripts/fixtures/mermaid-flowcharts/docs-markdown-v11.mmd
new file mode 100644
index 00000000..1464963a
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-markdown-v11.mmd
@@ -0,0 +1,14 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+---
+title: Frontmatter title
+---
+flowchart LR
+ markdown["`This **is** _Markdown_`"]
+ newLines["`Line1
+ Line 2
+ Line 3`"]
+ markdown --> newLines
+ A@{ shape: cyl, label: "Database" }
+ B@{ shape: tri, label: "Extract" }
+ C@{ shape: bolt }
+ A --> B --> C
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-shapes.mmd b/scripts/fixtures/mermaid-flowcharts/docs-shapes.mmd
new file mode 100644
index 00000000..a9ce0286
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-shapes.mmd
@@ -0,0 +1,15 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart LR
+ id1[This is the text in the box] --> id2(This is the text in the box)
+ id2 --> id3([This is the text in the box])
+ id3 --> id4[[This is the text in the box]]
+ id4 --> id5[(Database)]
+ id5 --> id6((This is the text in the circle))
+ id6 --> id7>This is the text in the box]
+ id7 --> id8{This is the text in the box}
+ id8 --> id9{{This is the text in the box}}
+ id9 --> id10[/This is the text in the box/]
+ id10 --> id11[\This is the text in the box\]
+ id11 --> A[/Christmas\]
+ A --> B[\Go shopping/]
+ B --> id12(((This is the text in the circle)))
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-styling.mmd b/scripts/fixtures/mermaid-flowcharts/docs-styling.mmd
new file mode 100644
index 00000000..64d00550
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-styling.mmd
@@ -0,0 +1,10 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart LR
+ id1(Start)-->id2(Stop)
+ style id1 fill:#f9f,stroke:#333,stroke-width:4px
+ style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
+ A:::someclass --> B
+ classDef someclass fill:#f96
+ C --> D
+ class C,D green
+ classDef green fill:#9f6,stroke:#333,stroke-width:2px;
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-subgraph-direction.mmd b/scripts/fixtures/mermaid-flowcharts/docs-subgraph-direction.mmd
new file mode 100644
index 00000000..fc2c62bf
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-subgraph-direction.mmd
@@ -0,0 +1,15 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart LR
+ subgraph TOP
+ direction TB
+ subgraph B1
+ direction RL
+ i1 -->f1
+ end
+ subgraph B2
+ direction BT
+ i2 -->f2
+ end
+ end
+ A --> TOP --> B
+ B1 --> B2
diff --git a/scripts/fixtures/mermaid-flowcharts/docs-subgraphs.mmd b/scripts/fixtures/mermaid-flowcharts/docs-subgraphs.mmd
new file mode 100644
index 00000000..e77d353e
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/docs-subgraphs.mmd
@@ -0,0 +1,15 @@
+%% source: https://mermaid.js.org/syntax/flowchart.html (MIT, mermaid-js/mermaid)
+flowchart TB
+ c1-->a2
+ subgraph one
+ a1-->a2
+ end
+ subgraph two
+ b1-->b2
+ end
+ subgraph three
+ c1-->c2
+ end
+ one --> two
+ three --> two
+ two --> c2
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-01-spark-sql-flow-plugin.mmd b/scripts/fixtures/mermaid-flowcharts/readme-01-spark-sql-flow-plugin.mmd
new file mode 100644
index 00000000..6d6be0ed
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-01-spark-sql-flow-plugin.mmd
@@ -0,0 +1,18 @@
+%% source: https://github.com/maropu/spark-sql-flow-plugin/blob/HEAD/resources/README.md (Apache-2.0)
+flowchart LR %% Automatically generated by org.apache.spark.sql.flow.sink.MermaidSink
+ Aggregate_f228b39(Aggregate)
+ Filter_88e94c9(Filter)
+ Join_Inner_caa475c(Join_Inner)
+ Project_f949a24(Project)
+ default.testtable[["default.testtable(key,value)"]]
+ testview2[["testview2(key,value,s)"]]
+ Filter_91d962e(Filter)
+ testview1[["testview1(key,s)"]]
+ Join_Inner_caa475c-->Project_f949a24
+ Filter_91d962e-->Join_Inner_caa475c
+ Filter_88e94c9-->Join_Inner_caa475c
+ default.testtable-->Filter_91d962e
+ testview1-->Filter_88e94c9
+ Project_f949a24-->testview2
+ default.testtable-->Aggregate_f228b39
+ Aggregate_f228b39-->testview1
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-02-workflow.mmd b/scripts/fixtures/mermaid-flowcharts/readme-02-workflow.mmd
new file mode 100644
index 00000000..8c6e4d92
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-02-workflow.mmd
@@ -0,0 +1,5 @@
+%% source: https://github.com/chevere/workflow/blob/HEAD/README.md (Apache-2.0)
+graph TD
+ thumb --> store
+ medium --> store
+ large --> store
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-03-workflow.mmd b/scripts/fixtures/mermaid-flowcharts/readme-03-workflow.mmd
new file mode 100644
index 00000000..1c29521a
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-03-workflow.mmd
@@ -0,0 +1,17 @@
+%% source: https://github.com/chevere/workflow/blob/HEAD/README.md (Apache-2.0)
+graph TB;
+ ja("`ja`");
+ j1("`j1`");
+ j2("`j2`");
+ jb("`jb
+*if* res(ja)
+*ifNot* var(var)`");
+ j3("`j3`");
+ j4("`j4`");
+
+ j1-->|"j1->id @ j2(n:)
+j1->name @ j2(m:)"|j2;
+ ja-->jb;
+ jb-->|"jb @ j3(a:)"|j3;
+ j2-->|"j2 @ j4(i:)"|j4;
+ j3-->|"j3 @ j4(j:)"|j4;
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-04-mermaidtui.mmd b/scripts/fixtures/mermaid-flowcharts/readme-04-mermaidtui.mmd
new file mode 100644
index 00000000..2da026bb
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-04-mermaidtui.mmd
@@ -0,0 +1,4 @@
+%% source: https://github.com/tariqshams/mermaidtui/blob/HEAD/README.md (Apache-2.0)
+flowchart LR
+ A[Start Here] --> B[Process A] --> C[End Goal]
+ B --> D[Process B]
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-05-mermaidtui.mmd b/scripts/fixtures/mermaid-flowcharts/readme-05-mermaidtui.mmd
new file mode 100644
index 00000000..30b4e34b
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-05-mermaidtui.mmd
@@ -0,0 +1,6 @@
+%% source: https://github.com/tariqshams/mermaidtui/blob/HEAD/README.md (Apache-2.0)
+flowchart LR
+ A[Root] --> B[Top Node]
+ A --> C[Bottom Node]
+ B --> D[Final]
+ C --> D
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-06-mermaidtui.mmd b/scripts/fixtures/mermaid-flowcharts/readme-06-mermaidtui.mmd
new file mode 100644
index 00000000..95d75eb2
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-06-mermaidtui.mmd
@@ -0,0 +1,6 @@
+%% source: https://github.com/tariqshams/mermaidtui/blob/HEAD/README.md (Apache-2.0)
+flowchart TB
+ A[Root] --> B[Left Node]
+ A --> C[Right Node]
+ B --> D[Final]
+ C --> D
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-07-convert2mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-07-convert2mermaid.mmd
new file mode 100644
index 00000000..e5a7edce
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-07-convert2mermaid.mmd
@@ -0,0 +1,3 @@
+%% source: https://github.com/jgreywolf/convert2mermaid/blob/HEAD/README.md (MIT)
+flowchart TD
+ A["Start"] --> B["End"]
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-09-flowchestra.mmd b/scripts/fixtures/mermaid-flowcharts/readme-09-flowchestra.mmd
new file mode 100644
index 00000000..1e2461ed
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-09-flowchestra.mmd
@@ -0,0 +1,29 @@
+%% source: https://github.com/Sheetaa/flowchestra/blob/HEAD/README.md (MIT)
+flowchart TD
+ begin((Start)) --> prepare[Prepare Code]
+ prepare --> ai_review[AI Review]
+
+ ai_review --> security[Security Check]
+ ai_review --> performance[Performance Check]
+ ai_review --> code_style[Code Style]
+
+ security --> aggregate[Aggregate Results]
+ performance --> aggregate
+ code_style --> aggregate
+
+ aggregate --> human_review{{Human Review}}
+
+ human_review -->|approve| summarize[Generate Summary]
+ human_review -->|reject| prepare
+
+ summarize --> finish((End))
+
+ classDef startend fill:#2ecc71,stroke:#27ae60,color:#fff
+ classDef primary fill:#2980b9,stroke:#2980b9,color:#fff
+ classDef subagent fill:#85c1e9,stroke:#85c1e9,color:#000
+ classDef human fill:#f39c12,stroke:#f39c12,color:#000
+
+ class begin,finish startend
+ class ai_review primary
+ class prepare,security,performance,code_style,aggregate,summarize subagent
+ class human_review human
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-10-tachi.mmd b/scripts/fixtures/mermaid-flowcharts/readme-10-tachi.mmd
new file mode 100644
index 00000000..7029c3c5
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-10-tachi.mmd
@@ -0,0 +1,14 @@
+%% source: https://github.com/davidmatousek/tachi/blob/HEAD/examples/README.md (Apache-2.0)
+graph TD
+ STRIDE[STRIDE Methodology]
+
+ subgraph OWASP Classification Frameworks
+ Web[OWASP Top 10 Web 2025]
+ Agentic[OWASP Agentic Top 10 2026]
+ MCP[OWASP MCP Top 10 2025]
+ end
+
+ STRIDE -->|classifies web findings| Web
+ STRIDE -->|extends with AI agents| Agentic
+ STRIDE -->|extends with MCP agents| MCP
+ Agentic -.->|cross-references| MCP
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-11-clickhouse-table-graph.mmd b/scripts/fixtures/mermaid-flowcharts/readme-11-clickhouse-table-graph.mmd
new file mode 100644
index 00000000..70d497d8
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-11-clickhouse-table-graph.mmd
@@ -0,0 +1,13 @@
+%% source: https://github.com/mbaksheev/clickhouse-table-graph/blob/HEAD/README.md (MIT)
+flowchart TB
+tree.mid_table@{ shape: rect, label: "tree.mid_table (ReplacingMergeTree)" } --> tree.mid_distributed@{ shape: st-rect, label: "tree.mid_distributed (Distributed)" }
+tree.mid_table@{ shape: rect, label: "tree.mid_table (ReplacingMergeTree)" } --> tree.target_table_mv@{ shape: hex, label: "tree.target_table_mv (MaterializedView)" }
+tree.mid_table_mv@{ shape: hex, label: "tree.mid_table_mv (MaterializedView)" } --> tree.mid_table@{ shape: rect, label: "tree.mid_table (ReplacingMergeTree)" }
+tree.base_table@{ shape: rounded, label: "tree.base_table (Null)" } --> tree.mid_table_mv@{ shape: hex, label: "tree.mid_table_mv (MaterializedView)" }
+tree.target_table_mv@{ shape: hex, label: "tree.target_table_mv (MaterializedView)" } --> tree.target_table@{ shape: rect, label: "tree.target_table (ReplacingMergeTree)" }
+tree.target_table@{ shape: rect, label: "tree.target_table (ReplacingMergeTree)" } --> tree.target_2_distributed@{ shape: st-rect, label: "tree.target_2_distributed (Distributed)" }
+tree.target_table@{ shape: rect, label: "tree.target_table (ReplacingMergeTree)" } --> tree.target_distributed@{ shape: st-rect, label: "tree.target_distributed (Distributed)" }
+tree.target_table_mv_2@{ shape: hex, label: "tree.target_table_mv_2 (MaterializedView)" } --> tree.target_table@{ shape: rect, label: "tree.target_table (ReplacingMergeTree)" }
+tree.another_base_table@{ shape: rounded, label: "tree.another_base_table (Null)" } --> tree.target_table_mv_2@{ shape: hex, label: "tree.target_table_mv_2 (MaterializedView)" }
+default.value_dict@{ shape: win-pane, label: "default.value_dict (Dictionary)" } --> tree.target_table_mv_2@{ shape: hex, label: "tree.target_table_mv_2 (MaterializedView)" }
+style tree.mid_table stroke:#f4e022
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-12-clickhouse-table-graph.mmd b/scripts/fixtures/mermaid-flowcharts/readme-12-clickhouse-table-graph.mmd
new file mode 100644
index 00000000..ac1958ee
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-12-clickhouse-table-graph.mmd
@@ -0,0 +1,5 @@
+%% source: https://github.com/mbaksheev/clickhouse-table-graph/blob/HEAD/README.md (MIT)
+flowchart TB
+test_db.target_table_mv@{ shape: hex, label: "test_db.target_table_mv (MaterializedView)" } --> test_db.target_table@{ shape: rect, label: "test_db.target_table (ReplacingMergeTree)" }
+test_db.input_table@{ shape: rounded, label: "test_db.input_table (Null)" } --> test_db.target_table_mv@{ shape: hex, label: "test_db.target_table_mv (MaterializedView)" }
+style test_db.input_table stroke:#f4e022
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-13-dashmotion.mmd b/scripts/fixtures/mermaid-flowcharts/readme-13-dashmotion.mmd
new file mode 100644
index 00000000..bf9748a1
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-13-dashmotion.mmd
@@ -0,0 +1,7 @@
+%% source: https://github.com/csthink/dashmotion/blob/HEAD/README.md (MIT)
+flowchart TB
+ A[Receive ticket] --> B{Severity?}
+ B -->|P1| C[Page on-call]
+ B -->|P2| D[Create incident]
+ C --> E[Mitigate]
+ D --> E
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-14-acg.mmd b/scripts/fixtures/mermaid-flowcharts/readme-14-acg.mmd
new file mode 100644
index 00000000..3ade064b
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-14-acg.mmd
@@ -0,0 +1,25 @@
+%% source: https://github.com/Adversarr/ACG/blob/HEAD/gui/readme.md (MIT)
+flowchart
+ *InitCallback-->Init-->*PreRun
+ *PostRun-->Cleanup-->*CleanupCallback
+ ProcessIO-- Not Running --> *PostRun
+ subgraph WorldLoop
+ *PreRun-->ProcessIO(ProcessInput)
+ ProcessIO -- Still Running --> RunDraw
+ RunDraw-- Physics Running --> *RunPhysics --> ProcessIO
+ RunDraw-- Physics Not Running --> ProcessIO
+ subgraph RunDraw
+ BeginDraw -- ok --> DrawActual
+ BeginDraw -- not ok --> RecreateSwapchain -->End
+ subgraph DrawActual
+ subgraph DrawUI
+ ImGUINewFrame-->*RunUiImpl-->RenderUI
+ end
+ *DrawScene --> Render
+ DrawUI --> Render
+ end
+ DrawActual --> EndDraw
+ EndDraw -- ok --> End
+ EndDraw -- not ok --> RecreateSwapchain
+ end
+ end
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-17-website-privacy-checker-extension.mmd b/scripts/fixtures/mermaid-flowcharts/readme-17-website-privacy-checker-extension.mmd
new file mode 100644
index 00000000..6f78ffdf
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-17-website-privacy-checker-extension.mmd
@@ -0,0 +1,25 @@
+%% source: https://github.com/Advait251206/Website-Privacy-Checker-Extension/blob/HEAD/README.md (MIT)
+%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#E0F2F1', 'edgeLabelBackground':'#FFFFFF', 'tertiaryColor': '#E8F5E9', 'lineColor': '#00796B', 'nodeBorder': '#00796B' }}}%%
+flowchart TD
+ classDef main fill:#E0F2F1,stroke:#00796B,stroke-width:2px,color:#004D40;
+ classDef process fill:#FFF8E1,stroke:#F57F17,stroke-width:2px,color:#5D4037;
+ classDef check fill:#EDE7F6,stroke:#5E35B1,stroke-width:2px,color:#311B92;
+
+ A["🌐 Web Page Loads"]:::main --> B["💉 Content Script Injection (content.js)"]:::main
+ B --> C["🕵️ DOM & Form Privacy Scan"]:::check
+
+ A --> D["⚙️ Service Worker Monitoring (background.js)"]:::main
+ D --> E["📡 WebRequest Tracker Detection"]:::check
+
+ C & E --> F["🧠 Trust Score Calculator Engine (popup.js)"]:::process
+
+ F --> G["🛡️ SSL Check (+20 pts)"]:::process
+ F --> H["📜 Privacy Policy Scan (+20 pts)"]:::process
+ F --> I["🍪 Cookies & Tracker Filter (+30 pts)"]:::process
+ F --> J["🔒 Insecure Form Audit (+30 pts)"]:::process
+
+ G & H & I & J --> K["📊 UI Popup Rendering (popup.html)"]:::main
+
+ class A,B,D,K main;
+ class C,E check;
+ class F,G,H,I,J process;
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-19-obsidian-beautiful-mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-19-obsidian-beautiful-mermaid.mmd
new file mode 100644
index 00000000..a9fcadf8
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-19-obsidian-beautiful-mermaid.mmd
@@ -0,0 +1,5 @@
+%% source: https://github.com/qiaoborui/obsidian-beautiful-mermaid/blob/HEAD/README.md (Apache-2.0)
+graph LR
+ A[API emitEvent] --> B[Fanout exchange]
+ B --> C[Gateway session A]
+ B --> D[Gateway session B]
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-20-ainativelang.mmd b/scripts/fixtures/mermaid-flowcharts/readme-20-ainativelang.mmd
new file mode 100644
index 00000000..74173f93
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-20-ainativelang.mmd
@@ -0,0 +1,7 @@
+%% source: https://github.com/sbhooley/ainativelang/blob/HEAD/README.md (Apache-2.0)
+flowchart LR
+A[AINL Source] --> B[Compiler]
+B --> C[Canonical Graph IR]
+C --> D[Runtime Engine]
+D --> E[Adapters / Tools / State]
+D --> F[Optional LLM Calls]
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-21-ainativelang.mmd b/scripts/fixtures/mermaid-flowcharts/readme-21-ainativelang.mmd
new file mode 100644
index 00000000..6ee6f28c
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-21-ainativelang.mmd
@@ -0,0 +1,12 @@
+%% source: https://github.com/sbhooley/ainativelang/blob/HEAD/README.md (Apache-2.0)
+graph TD
+ direction TB
+
+ subgraph c_retry ["retry"]
+ "retry/ENTRY"[ENTRY] --> "retry/n1"[EXPONENTIAL 5 200]
+ "retry/n1" --> "retry/EXIT_OK"[EXIT_OK]
+ "retry/n1" --> "retry/EXIT_FAIL"[EXIT_FAIL]
+ end
+
+ %% Synthetic edges: Call → included label entry (not explicit in IR)
+ L1[Your Main Logic] -->|"call"| "retry/ENTRY"
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-22-architecture-as-code.mmd b/scripts/fixtures/mermaid-flowcharts/readme-22-architecture-as-code.mmd
new file mode 100644
index 00000000..5a2c7730
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-22-architecture-as-code.mmd
@@ -0,0 +1,7 @@
+%% source: https://github.com/finos/architecture-as-code/blob/HEAD/calm-widgets/README.md (Apache-2.0)
+graph TD;
+load-balancer[Load Balancer]:::highlight;
+conference-website[Conference Website] -- Connects --> load-balancer[Load Balancer];
+load-balancer[Load Balancer] -- Connects --> attendees[Attendees Service];
+load-balancer[Load Balancer] -- Deployed In --> k8s-cluster[Kubernetes Cluster];
+classDef highlight fill:#f2bbae;
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-23-architecture-as-code.mmd b/scripts/fixtures/mermaid-flowcharts/readme-23-architecture-as-code.mmd
new file mode 100644
index 00000000..8de476c2
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-23-architecture-as-code.mmd
@@ -0,0 +1,58 @@
+%% source: https://github.com/finos/architecture-as-code/blob/HEAD/calm-widgets/README.md (Apache-2.0)
+%%{init: {"flowchart": {"htmlLabels": false}}}%%
+flowchart TB
+classDef boundary fill:#f8fafc,stroke:#64748b,stroke-dasharray: 5 4,stroke-width:2px,color:#000;
+classDef node fill:#ffffff,stroke:#1f2937,stroke-width:1px,color:#000;
+classDef iface fill:#f1f5f9,stroke:#64748b,stroke-width:1px,font-size:10px,color:#000;
+classDef highlight fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#000;
+
+ subgraph enterprise-bank["Enterprise Bank"]
+ direction TB
+ subgraph messaging-system["Messaging System"]
+ direction TB
+ message-bus["Message Bus"]:::node
+ message-bus__iface__trade-events-topic["◻ Trade Events Topic"]:::iface
+ end
+ class messaging-system boundary
+ subgraph trading-system["Trading System"]
+ direction TB
+ trade-svc["Trade Service"]:::node
+ trade-svc__iface__api["◻ API: /trades"]:::iface
+ trade-svc__iface__jdbc["◻ JDBC: trading-db"]:::iface
+ trade-svc__iface__events["◻ Topic: trade.events"]:::iface
+ trading-db["Trading DB"]:::node
+ trading-db__iface__sql["◻ SQL Interface"]:::iface
+ trading-ui["Trading UI"]:::node
+ trading-ui__iface__web-ui["◻ Web Interface"]:::iface
+ end
+ class trading-system boundary
+ end
+ class enterprise-bank boundary
+
+
+ trading-ui__iface__web-ui -->|Place Trade| trade-svc__iface__api
+ trade-svc__iface__jdbc -->|Persist| trading-db__iface__sql
+ trade-svc__iface__events -->|Publish Events| message-bus__iface__trade-events-topic
+
+ trading-ui -.- trading-ui__iface__web-ui
+ trade-svc -.- trade-svc__iface__api
+ trade-svc -.- trade-svc__iface__jdbc
+ trade-svc -.- trade-svc__iface__events
+ trading-db -.- trading-db__iface__sql
+ message-bus -.- message-bus__iface__trade-events-topic
+
+ class trade-svc highlight
+ class trading-ui highlight
+ class trading-db highlight
+ class message-bus highlight
+ click message-bus "#message-bus" "Jump to Message Bus"
+ click message-bus__iface__trade-events-topic "#message-bus__iface__trade-events-topic" "Jump to ◻ Trade Events Topic"
+ click trade-svc "#trade-service" "Jump to Trade Service"
+ click trade-svc__iface__api "#trade-service-api" "Jump to ◻ API: /trades"
+ click trade-svc__iface__jdbc "#trade-service-storage" "Jump to ◻ JDBC: trading-db"
+ click trade-svc__iface__events "#trade-service-events" "Jump to ◻ Topic: trade.events"
+ click trading-db "#trading-db" "Jump to Trading DB"
+ click trading-db__iface__sql "#trading-db__iface__sql" "Jump to ◻ SQL Interface"
+ click trading-ui "#trading-ui" "Jump to Trading UI"
+ click trading-ui__iface__web-ui "#trading-ui__iface__web-ui" "Jump to ◻ Web Interface"
+
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-24-architecture-as-code.mmd b/scripts/fixtures/mermaid-flowcharts/readme-24-architecture-as-code.mmd
new file mode 100644
index 00000000..f91bb157
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-24-architecture-as-code.mmd
@@ -0,0 +1,40 @@
+%% source: https://github.com/finos/architecture-as-code/blob/HEAD/calm-widgets/README.md (Apache-2.0)
+%%{init: {"flowchart": {"htmlLabels": false}}}%%
+flowchart TB
+classDef boundary fill:#f8fafc,stroke:#64748b,stroke-dasharray: 5 4,stroke-width:2px,color:#000;
+classDef node fill:#ffffff,stroke:#1f2937,stroke-width:1px,color:#000;
+classDef iface fill:#f1f5f9,stroke:#64748b,stroke-width:1px,font-size:10px,color:#000;
+classDef highlight fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#000;
+
+ subgraph enterprise-bank["Enterprise Bank"]
+ direction TB
+ subgraph messaging-system["Messaging System"]
+ direction TB
+ message-bus["Message Bus"]:::node
+ end
+ class messaging-system boundary
+ subgraph trading-system["Trading System"]
+ direction TB
+ trade-svc["Trade Service"]:::node
+ trading-db["Trading DB"]:::node
+ trading-ui["Trading UI"]:::node
+ end
+ class trading-system boundary
+ end
+ class enterprise-bank boundary
+
+
+ trading-ui -->|Place Trade| trade-svc
+ trade-svc -->|Persist| trading-db
+ trade-svc -->|Publish Events| message-bus
+
+
+ class trade-svc highlight
+ class trading-ui highlight
+ class trading-db highlight
+ class message-bus highlight
+ click message-bus "#message-bus" "Jump to Message Bus"
+ click trade-svc "#trade-service" "Jump to Trade Service"
+ click trading-db "#trading-db" "Jump to Trading DB"
+ click trading-ui "#trading-ui" "Jump to Trading UI"
+
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-25-create-mvp.mmd b/scripts/fixtures/mermaid-flowcharts/readme-25-create-mvp.mmd
new file mode 100644
index 00000000..f6a82c7b
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-25-create-mvp.mmd
@@ -0,0 +1,17 @@
+%% source: https://github.com/qwadratic/create-mvp/blob/HEAD/README.md (MIT)
+graph TD
+ goal.md --> build/effort.json
+ build/effort.json --> build/plan.json
+ goal.md --> build/plan.json
+ build/plan.json --> build/components.mk
+ build/plan.json --> build/life-engine.done
+ build/plan.json --> build/canvas-renderer.done
+ build/life-engine.done --> build/canvas-renderer.done
+ build/plan.json --> build/animation-app.done
+ build/life-engine.done --> build/animation-app.done
+ build/canvas-renderer.done --> build/animation-app.done
+ build/components.mk --> build/report.md
+ build/life-engine.done --> build/report.md
+ build/canvas-renderer.done --> build/report.md
+ build/animation-app.done --> build/report.md
+ build/report.md --> all
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-37-excalidraw-to-mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-37-excalidraw-to-mermaid.mmd
new file mode 100644
index 00000000..908b5df2
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-37-excalidraw-to-mermaid.mmd
@@ -0,0 +1,9 @@
+%% source: https://github.com/moona3k/excalidraw-to-mermaid/blob/HEAD/README.md (MIT)
+graph TD
+ A(Start)
+ B{Valid?}
+ C[Success]
+ D[Error]
+ A --> B
+ B -->|Yes| C
+ B -.->|No| D
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-38-excalidraw-to-mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-38-excalidraw-to-mermaid.mmd
new file mode 100644
index 00000000..74cb6d99
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-38-excalidraw-to-mermaid.mmd
@@ -0,0 +1,9 @@
+%% source: https://github.com/moona3k/excalidraw-to-mermaid/blob/HEAD/README.md (MIT)
+graph LR
+ A[Rectangle]
+ B(Rounded)
+ C{Choice}
+ D((End))
+ A --> B
+ B -.-> C
+ C ==> D
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-39-excalidraw-to-mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-39-excalidraw-to-mermaid.mmd
new file mode 100644
index 00000000..f86f0fdc
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-39-excalidraw-to-mermaid.mmd
@@ -0,0 +1,15 @@
+%% source: https://github.com/moona3k/excalidraw-to-mermaid/blob/HEAD/README.md (MIT)
+graph LR
+ A(CloudFront)
+ B(React SPA)
+ C(REST API)
+ D(Redis)
+ E(Stripe API)
+ F(PostgreSQL)
+ G(S3)
+ A --> B
+ B -->|REST calls| C
+ C -.->|cache| D
+ C -->|payments| E
+ C -->|queries| F
+ F -.->|uploads| G
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-40-drawio-to-mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-40-drawio-to-mermaid.mmd
new file mode 100644
index 00000000..59506167
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-40-drawio-to-mermaid.mmd
@@ -0,0 +1,5 @@
+%% source: https://github.com/kornellewy/drawio_to_mermaid/blob/HEAD/README.md (MIT)
+flowchart TD
+ Nstart(("Start"))
+ Nprocess["Process"]
+ Nstart --> Nprocess
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-41-drawio-to-mermaid.mmd b/scripts/fixtures/mermaid-flowcharts/readme-41-drawio-to-mermaid.mmd
new file mode 100644
index 00000000..9fa986bc
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-41-drawio-to-mermaid.mmd
@@ -0,0 +1,9 @@
+%% source: https://github.com/kornellewy/drawio_to_mermaid/blob/HEAD/README.md (MIT)
+flowchart TD
+ Nstart(("Start"))
+ Ndecision{"Continue?"}
+ Nyes("Process")
+ Nno("End")
+ Nstart --> Ndecision
+ Ndecision -- "Yes" --> Nyes
+ Ndecision -- "No" --> Nno
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-42-mermaid-to-visio.mmd b/scripts/fixtures/mermaid-flowcharts/readme-42-mermaid-to-visio.mmd
new file mode 100644
index 00000000..d7a9802f
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-42-mermaid-to-visio.mmd
@@ -0,0 +1,8 @@
+%% source: https://github.com/rdapaz/mermaid_to_visio/blob/HEAD/README.md (MIT)
+graph TD
+ A[Client Application] --> B[Load Balancer]
+ B --> C[Web Server 1]
+ B --> D[Web Server 2]
+ C --> E[Database Primary]
+ D --> E
+ E --> F[Database Replica]
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-43-codebase-outliner.mmd b/scripts/fixtures/mermaid-flowcharts/readme-43-codebase-outliner.mmd
new file mode 100644
index 00000000..d0337e30
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-43-codebase-outliner.mmd
@@ -0,0 +1,18 @@
+%% source: https://github.com/maomaoc474/codebase-outliner/blob/HEAD/README.md (MIT)
+graph LR
+ subgraph Frontend
+ App["App.tsx"] --> API["services/api.ts"]
+ App --> Views["views/\n9 files"]
+ Views --> API
+ end
+
+ subgraph Backend
+ Start["index.ts"] --> Routes["routes/"]
+ Routes --> Services["services/"]
+ Services --> DB["database.ts"]
+ end
+
+ API -.->|"REST /api/*"| Start
+
+ style App fill:#e1f5fe
+ style Start fill:#e8f5e9
diff --git a/scripts/fixtures/mermaid-flowcharts/readme-46-temporalio-graphs.mmd b/scripts/fixtures/mermaid-flowcharts/readme-46-temporalio-graphs.mmd
new file mode 100644
index 00000000..00caf7d2
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/readme-46-temporalio-graphs.mmd
@@ -0,0 +1,25 @@
+%% source: https://github.com/LucaDeLeo/temporalio-graphs/blob/HEAD/README.md (MIT)
+flowchart TB
+ subgraph OrderWorkflow
+ s_Order((Start)) --> ProcessOrder[Process Order]
+ ProcessOrder --> ext_sig_ship[/Signal 'ship_order'\]
+ ext_sig_ship --> e_Order((End))
+ end
+
+ subgraph ShippingWorkflow
+ sig_handler_ship{{ship_order}}
+ s_Ship((Start)) --> ShipPackage[Ship Package]
+ ShipPackage --> ext_sig_notify[/Signal 'notify_shipped'\]
+ end
+
+ subgraph NotificationWorkflow
+ sig_handler_notify{{notify_shipped}}
+ end
+
+ %% Cross-workflow signal connections
+ ext_sig_ship -.ship_order.-> sig_handler_ship
+ ext_sig_notify -.notify_shipped.-> sig_handler_notify
+
+ %% Signal handler styling
+ style sig_handler_ship fill:#e6f3ff,stroke:#0066cc
+ style sig_handler_notify fill:#e6f3ff,stroke:#0066cc
diff --git a/scripts/fixtures/mermaid-flowcharts/snapshots.json b/scripts/fixtures/mermaid-flowcharts/snapshots.json
new file mode 100644
index 00000000..bd996e87
--- /dev/null
+++ b/scripts/fixtures/mermaid-flowcharts/snapshots.json
@@ -0,0 +1,40 @@
+{
+ "docs-chaining.mmd": "afe0a29eab307372",
+ "docs-christmas.mmd": "d433d962d6aa3cd1",
+ "docs-entities.mmd": "f9e59f9ef90dc72b",
+ "docs-links.mmd": "592e80428b022d2b",
+ "docs-markdown-v11.mmd": "38aed481b13a305e",
+ "docs-shapes.mmd": "6f4e8299e3ec561c",
+ "docs-styling.mmd": "6f24b0395aaf6264",
+ "docs-subgraph-direction.mmd": "f0a6ce8c04ed6254",
+ "docs-subgraphs.mmd": "78f6081701a3f604",
+ "readme-01-spark-sql-flow-plugin.mmd": "df6c3b7090d6f34d",
+ "readme-02-workflow.mmd": "4234e5e3921d9256",
+ "readme-03-workflow.mmd": "c2b1664b0e7a8d92",
+ "readme-04-mermaidtui.mmd": "14df48445021d7d3",
+ "readme-05-mermaidtui.mmd": "104bc5a9751bdbd6",
+ "readme-06-mermaidtui.mmd": "e24b8dc03ba462e4",
+ "readme-07-convert2mermaid.mmd": "1912243f21b4a561",
+ "readme-09-flowchestra.mmd": "c5e26abc1ffa7fa4",
+ "readme-10-tachi.mmd": "36f2475bc74c2348",
+ "readme-11-clickhouse-table-graph.mmd": "a6e0f58ef7d37769",
+ "readme-12-clickhouse-table-graph.mmd": "6d8cbbadeaa3af6a",
+ "readme-13-dashmotion.mmd": "0696325e26000ef7",
+ "readme-14-acg.mmd": "67d54c62ff2ae75d",
+ "readme-17-website-privacy-checker-extension.mmd": "9184b88a44a9971e",
+ "readme-19-obsidian-beautiful-mermaid.mmd": "e207854ee5b6f0d4",
+ "readme-20-ainativelang.mmd": "602956d3aabd2e72",
+ "readme-21-ainativelang.mmd": "d77aa35e5abccf08",
+ "readme-22-architecture-as-code.mmd": "a85ec30220e77200",
+ "readme-23-architecture-as-code.mmd": "b7fd571a926667b0",
+ "readme-24-architecture-as-code.mmd": "3dec84292f926516",
+ "readme-25-create-mvp.mmd": "75b87a073cdd4a0d",
+ "readme-37-excalidraw-to-mermaid.mmd": "19d5c7f2cdd0d46f",
+ "readme-38-excalidraw-to-mermaid.mmd": "f82caf1ed7dddd31",
+ "readme-39-excalidraw-to-mermaid.mmd": "e8d22e5d29e50b3a",
+ "readme-40-drawio-to-mermaid.mmd": "af4aed69691dfb20",
+ "readme-41-drawio-to-mermaid.mmd": "44620deb1c80b21d",
+ "readme-42-mermaid-to-visio.mmd": "0c535475c288b7c0",
+ "readme-43-codebase-outliner.mmd": "4c7a23f6b676cd67",
+ "readme-46-temporalio-graphs.mmd": "1131f0c1cd952230"
+}
diff --git a/scripts/test-diagram-mermaid.ts b/scripts/test-diagram-mermaid.ts
new file mode 100644
index 00000000..0f3fc1db
--- /dev/null
+++ b/scripts/test-diagram-mermaid.ts
@@ -0,0 +1,680 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Mermaid flowcharts ⇄ slides-shaped diagram elements (spaces/src/diagram/).
+//
+// node scripts/test-diagram-mermaid.ts # run
+// node scripts/test-diagram-mermaid.ts --update # rewrite the layout snapshots
+//
+// WHAT THIS PROVES, and why each one fails silently:
+//
+// 1. SYNTAX. Each construct we claim to read (directions, the node shapes,
+// the link kinds and both label forms, chains and `&`, subgraphs,
+// classDef/class/style, comments) parses to the AST it means. A parser
+// that gets `-- text -->` wrong still produces a diagram — a wrong one.
+// 2. REAL FLOWCHARTS. A corpus lifted from GitHub READMEs (MIT/Apache repos,
+// source in each file's first line) and the mermaid docs. Every one must
+// lay out with NO overlapping nodes, every connector end must sit on a
+// real element exactly where slides' syncConnectors would put it (or the
+// diagram jumps on its first edit) — checked with the kernel's own
+// connectorEndpoint, the call syncConnectors makes — every curved
+// connector's `d` must be the bytes slides' curve writer (setPathAnchors:
+// round the anchors, then the kernel's anchorsToPath) gives for its
+// anchors, and it must be byte-for-byte the same every run and match the
+// committed snapshot.
+// 2b. ROUTING. No edge is drawn through a node it does not connect, or
+// through a subgraph box holding neither of its ends; no edge label sits
+// on another edge; no two edges share both ends unless the source says
+// so twice. Corpus totals are ratcheted: they may only go down.
+// 3. ROUND TRIP. mermaid → elements → mermaid is semantically equal: same
+// nodes, labels, shapes, edges, edge labels and kinds, subgraph
+// membership, colours and direction.
+// 4. LOSS IS REPORTED. diagramToMermaid names every element property it
+// drops — exactly those, no more.
+// 5. HOSTILE INPUT. Huge graphs cap with a warning, deep nesting flattens,
+// `__proto__` ids pollute nothing, script in a label stays inert text,
+// pathological cycles and 10k-character labels finish inside a time
+// budget, and random token soup never throws.
+// 6. SIZE. The module is budgeted in minified bytes.
+//
+// Every checker is run once against a planted defect first (NEGATIVE
+// CONTROLS below): a checker that cannot fail proves nothing.
+
+import { readFileSync, readdirSync, writeFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'
+import { createHash } from 'node:crypto'
+import { spawnSync } from 'node:child_process'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ mermaidToDiagram, diagramToMermaid, parseMermaid, diagramLayout, makeIds, validColor, LIMITS, PALETTE,
+ type DElement, type DShape, type DText, type FlowAST,
+} from '../spaces/src/diagram/mermaid.ts'
+import { anchorsToPath, boxCenter, connectorEndpoint, parseAnchors, type ConnectorSide } from '../kernel/src/geom.ts'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const FIX = join(root, 'scripts/fixtures/mermaid-flowcharts')
+const SNAP = join(FIX, 'snapshots.json')
+const UPDATE = process.argv.includes('--update')
+
+let checks = 0, failures = 0
+function ok(cond: unknown, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+}
+function section(t: string) { console.log(`\n${t}`) }
+
+// --- geometry helpers ---------------------------------------------------------
+// Where a connector end belongs is the KERNEL's connectorEndpoint — the exact
+// call slides' syncConnectors makes since the diagram-engine lift — not a copy
+// of its formula here, so this cannot drift from what the editor does.
+
+type Box = { x: number; y: number; w: number; h: number }
+type Pt = { x: number; y: number }
+const center = boxCenter
+/** a connector's two ends in slide coords: line = centre ± half-width along rotation;
+ * path = first and last on-curve points of `d`, mapped out of pathBox */
+function ends(e: DShape): [Pt, Pt] {
+ if (e.shape === 'line') {
+ const c = center(e), r = (e.rotation * Math.PI) / 180, dx = Math.cos(r) * e.w / 2, dy = Math.sin(r) * e.w / 2
+ return [{ x: c.x - dx, y: c.y - dy }, { x: c.x + dx, y: c.y + dy }]
+ }
+ const n = (e.d ?? '').match(/-?\d*\.?\d+(?:e-?\d+)?/g)!.map(Number)
+ const [px, py, pw, ph] = e.pathBox ?? [0, 0, e.w, e.h]
+ const m = (x: number, y: number) => ({ x: e.x + (x - px) * e.w / pw, y: e.y + (y - py) * e.h / ph })
+ return [m(n[0], n[1]), m(n[n.length - 2], n[n.length - 1])]
+}
+const isConn = (e: DElement): e is DShape => e.type === 'shape' && !!(e.from || e.to)
+const isNode = (e: DElement): e is DShape => e.type === 'shape' && !e.from && !e.to && e.role !== 'subgraph'
+const isGroup = (e: DElement): e is DShape => e.type === 'shape' && e.role === 'subgraph'
+
+// --- the checkers --------------------------------------------------------------
+
+function overlapping(els: DElement[]): string[] {
+ const nodes = els.filter(isNode)
+ const bad: string[] = []
+ for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
+ const a = nodes[i], b = nodes[j]
+ if (a.x < b.x + b.w - 0.01 && b.x < a.x + a.w - 0.01 && a.y < b.y + b.h - 0.01 && b.y < a.y + a.h - 0.01) bad.push(`${a.id}×${b.id}`)
+ }
+ return bad
+}
+/** subgraph boxes contain their members and no other node */
+function groupFaults(els: DElement[]): string[] {
+ const bad: string[] = []
+ const inside = (a: Box, b: Box) => a.x >= b.x - 0.01 && a.y >= b.y - 0.01 && a.x + a.w <= b.x + b.w + 0.01 && a.y + a.h <= b.y + b.h + 0.01
+ const hit = (a: Box, b: Box) => a.x < b.x + b.w - 0.01 && b.x < a.x + a.w - 0.01 && a.y < b.y + b.h - 0.01 && b.y < a.y + a.h - 0.01
+ const groups = els.filter(isGroup)
+ for (const g of groups) {
+ for (const n of els.filter(isNode)) {
+ if (n.groupId === g.id && !inside(n, g)) bad.push(`${n.id} outside ${g.id}`)
+ // a node may only overlap its own box and that box's ancestors
+ const own = groups.find((o) => o.id === n.groupId)
+ if (n.groupId !== g.id && hit(n, g) && !(own && inside(own, g))) bad.push(`${n.id} intrudes ${g.id}`)
+ }
+ }
+ return bad
+}
+/** every connector end names a real node/box and sits exactly where syncConnectors would put it */
+function attachFaults(els: DElement[]): string[] {
+ const bad: string[] = []
+ const byId = new Map(els.map((e) => [e.id, e]))
+ for (const e of els.filter(isConn)) {
+ const A = e.from && byId.get(e.from.el), B = e.to && byId.get(e.to.el)
+ if (!A || !B || A.type !== 'shape' || B.type !== 'shape' || isConn(A) || isConn(B)) { bad.push(`${e.id}: dangling`); continue }
+ const [a, b] = ends(e)
+ const wa = connectorEndpoint(A, e.from!.side as ConnectorSide | undefined, center(B))
+ const wb = connectorEndpoint(B, e.to!.side as ConnectorSide | undefined, center(A))
+ if (Math.hypot(a.x - wa.x, a.y - wa.y) > 0.6) bad.push(`${e.id}: start ${JSON.stringify(a)} ≠ ${JSON.stringify(wa)}`)
+ if (Math.hypot(b.x - wb.x, b.y - wb.y) > 0.6) bad.push(`${e.id}: end ${JSON.stringify(b)} ≠ ${JSON.stringify(wb)}`)
+ }
+ return bad
+}
+/** every curved connector is what slides' curve writer would write for its own
+ * anchors (setPathAnchors: anchors rounded, then anchorsToPath) — so the first
+ * edit in the curve editor rewrites nothing. Self-loops (pinned sides) are
+ * hand-drawn cubics and exempt. */
+function curveFaults(els: DElement[]): string[] {
+ return els.filter(isConn)
+ .filter((e) => e.shape === 'path' && e.from?.side === 'auto' && e.to?.side === 'auto')
+ .filter((e) => anchorsToPath(parseAnchors(e.d ?? '')) !== e.d)
+ .map((e) => e.id)
+}
+/** label html is inert: nothing but escaped text and <br> */
+function htmlFaults(els: DElement[]): string[] {
+ return els.filter((e): e is DText => e.type === 'text').filter((t) => /<(?!br>)/.test(t.html) || /[<>]/.test(t.html.replace(/<br>/g, ''))).map((t) => t.id)
+}
+/** a connector's drawn path as a polyline (cubics sampled 8 per segment) */
+function polyline(e: DShape): Pt[] {
+ if (e.shape === 'line') return ends(e)
+ const n = (e.d ?? '').match(/-?\d*\.?\d+(?:e-?\d+)?/g)!.map(Number)
+ const [px, py, pw, ph] = e.pathBox ?? [0, 0, e.w, e.h]
+ const m = (x: number, y: number) => ({ x: e.x + (x - px) * e.w / pw, y: e.y + (y - py) * e.h / ph })
+ const out: Pt[] = [m(n[0], n[1])]
+ for (let i = 2; i + 5 < n.length; i += 6) {
+ const p0 = out[out.length - 1], c1 = m(n[i], n[i + 1]), c2 = m(n[i + 2], n[i + 3]), p1 = m(n[i + 4], n[i + 5])
+ for (let t = 0.125; t <= 1.0001; t += 0.125) {
+ const u = 1 - t
+ out.push({ x: u * u * u * p0.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * p1.x, y: u * u * u * p0.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * p1.y })
+ }
+ }
+ return out
+}
+/** Liang–Barsky: does segment ab enter box r? */
+function segHits(a: Pt, b: Pt, r: Box): boolean {
+ let t0 = 0, t1 = 1
+ const dx = b.x - a.x, dy = b.y - a.y
+ for (const [p, q] of [[-dx, a.x - r.x], [dx, r.x + r.w - a.x], [-dy, a.y - r.y], [dy, r.y + r.h - a.y]]) {
+ if (p === 0) { if (q < 0) return false; continue }
+ const t = q / p
+ if (p < 0) { if (t > t1) return false; if (t > t0) t0 = t } else { if (t < t0) return false; if (t < t1) t1 = t }
+ }
+ return t0 < t1
+}
+const crosses = (pl: Pt[], r: Box) => pl.some((p, i) => i > 0 && segHits(pl[i - 1], p, r))
+/** edges drawn through nodes they do not connect / boxes holding neither end / labels on other edges */
+function routing(els: DElement[]) {
+ const conns = els.filter(isConn), nodes = els.filter(isNode), boxes = els.filter(isGroup)
+ const byId = new Map(els.map((e) => [e.id, e]))
+ const within = (a: Box, b: Box) => a.x >= b.x && a.y >= b.y && a.x + a.w <= b.x + b.w && a.y + a.h <= b.y + b.h
+ const node: string[] = [], box: string[] = [], label: string[] = []
+ for (const c of conns) {
+ const pl = polyline(c), A = byId.get(c.from!.el)!, B = byId.get(c.to!.el)!
+ for (const n of nodes) if (n !== A && n !== B && crosses(pl, { x: n.x + 2, y: n.y + 2, w: n.w - 4, h: n.h - 4 })) node.push(`${c.id} through ${n.id}`)
+ for (const b of boxes) if (b !== A && b !== B && !within(A, b) && !within(B, b) && crosses(pl, { x: b.x + 2, y: b.y + 2, w: b.w - 4, h: b.h - 4 })) box.push(`${c.id} through ${b.id}`)
+ const t = els.find((x) => x.id === `${c.id}-label`)
+ // the label's inked core: the text box carries 12px of slack on its trailing side
+ if (t) for (const o of conns) if (o !== c && crosses(polyline(o), { x: t.x + 6, y: t.y + 2, w: Math.max(0, t.w - 18), h: t.h - 4 })) label.push(`${t.id} on ${o.id}`)
+ }
+ return { node, box, label }
+}
+/** pairs of connectors sharing both ends, beyond what the source declared */
+function doubled(els: DElement[], ast: FlowAST): string[] {
+ const idOf = makeIds(), m = new Map<string, string>()
+ for (const n of ast.nodes) m.set(n.id, idOf(n.id))
+ for (const g of ast.subgraphs) m.set(g.id, idOf(g.id))
+ const key = (a: string, b: string) => [a, b].sort().join(' ~ ')
+ const declared = new Map<string, number>()
+ for (const e of ast.edges) if (e.stroke !== 'invisible') { const k = key(m.get(e.from)!, m.get(e.to)!); declared.set(k, (declared.get(k) ?? 0) + 1) }
+ const drawn = new Map<string, number>()
+ for (const c of els.filter(isConn)) { const k = key(c.from!.el, c.to!.el); drawn.set(k, (drawn.get(k) ?? 0) + 1) }
+ return [...drawn].filter(([k, n]) => n > (declared.get(k) ?? 0)).map(([k, n]) => `${k} ×${n}`)
+}
+function idFaults(els: DElement[]): string[] {
+ const seen = new Set<string>(), bad: string[] = []
+ for (const e of els) {
+ if (seen.has(e.id)) bad.push(`dup ${e.id}`)
+ seen.add(e.id)
+ if (!/^[\w-]+$/.test(e.id) || e.id in Object.prototype) bad.push(`unsafe ${e.id}`)
+ }
+ return bad
+}
+
+/** The semantic content of an AST, with ids as the elements will spell them. */
+function semantics(ast: FlowAST) {
+ const idOf = makeIds(), m = new Map<string, string>()
+ for (const n of ast.nodes) m.set(n.id, idOf(n.id))
+ for (const g of ast.subgraphs) m.set(g.id, idOf(g.id))
+ const nodes = ast.nodes.map((n) => `${m.get(n.id)} ${n.shape} ${JSON.stringify(n.label)} in:${n.parent ? m.get(n.parent) : '-'} ${n.style.fill ?? ''}/${n.style.stroke ?? ''}/${n.style.color ?? ''}`).sort()
+ // effective direction (mermaid's rule): a subgraph whose members link outside
+ // follows its context; otherwise its own direction, or the context's turned
+ const par = new Map<string, string | null>([...ast.nodes.map((n) => [n.id, n.parent] as const), ...ast.subgraphs.map((g) => [g.id, g.parent] as const)])
+ const anc = (x: string) => { const o: string[] = []; for (let p = par.get(x); p; p = par.get(p) ?? null) o.push(p); return o }
+ const linked = new Set<string>()
+ for (const e of ast.edges) {
+ const A = anc(e.from), B = anc(e.to)
+ for (const c of A) if (!B.includes(c) && c !== e.to) linked.add(c)
+ for (const c of B) if (!A.includes(c) && c !== e.from) linked.add(c)
+ }
+ const eff = (g: string | null): string => {
+ if (!g) return ast.dir
+ const sg = ast.subgraphs.find((x) => x.id === g)!
+ const ctx = eff(sg.parent)
+ return linked.has(g) ? ctx : sg.dir ?? (ctx === 'TB' ? 'LR' : 'TB')
+ }
+ const groups = ast.subgraphs.map((g) => `${m.get(g.id)} ${JSON.stringify(g.label)} in:${g.parent ? m.get(g.parent) : '-'} ${g.style.fill ?? ''}/${g.style.stroke ?? ''} dir:${eff(g.id)}`).sort()
+ const edges = ast.edges.filter((e) => e.stroke !== 'invisible').map((e) => {
+ let [a, b, s, t] = [m.get(e.from)!, m.get(e.to)!, e.start, e.end]
+ if (s !== 'none' && t === 'none') [a, b, s, t] = [b, a, t, s]
+ return `${a}→${b} ${s}/${t} ${e.stroke} ${JSON.stringify(e.label)}`
+ }).sort()
+ return { dir: ast.dir, nodes, groups, edges }
+}
+function diffSemantics(a: ReturnType<typeof semantics>, b: ReturnType<typeof semantics>, withDir: boolean): string[] {
+ const out: string[] = []
+ if (withDir && a.dir !== b.dir) out.push(`dir ${a.dir} ≠ ${b.dir}`)
+ for (const k of ['nodes', 'groups', 'edges'] as const) {
+ const A = a[k], B = b[k]
+ const miss = A.filter((x, i) => x !== B[i])
+ if (A.length !== B.length || miss.length) out.push(`${k}: ${JSON.stringify(A.filter((x) => !B.includes(x)).slice(0, 3))} vs ${JSON.stringify(B.filter((x) => !A.includes(x)).slice(0, 3))}`)
+ }
+ return out
+}
+const hash = (v: unknown) => createHash('sha256').update(JSON.stringify(v)).digest('hex').slice(0, 16)
+
+// --- 0. negative controls: every checker must catch a planted defect ----------
+
+section('negative controls')
+{
+ const r = mermaidToDiagram('flowchart TD\nA[One] --> B[Two]\nsubgraph S\nC\nend\nB --> C', { w: 800, h: 600 })
+ const els = structuredClone(r.elements)
+ ok(!overlapping(els).length && !attachFaults(els).length && !groupFaults(els).length && !htmlFaults(els).length && !idFaults(els).length, 'clean baseline passes every checker')
+ const moved = structuredClone(els)
+ const b = moved.find((e) => e.id === 'B')!
+ const a = moved.find((e) => e.id === 'A')!
+ b.x = a.x + 5; b.y = a.y + 5
+ ok(overlapping(moved).length > 0, 'overlap checker catches two stacked nodes')
+ const shifted = structuredClone(els)
+ shifted.find((e) => e.id === 'A-B')!.x += 5
+ ok(attachFaults(shifted).length > 0, 'attach checker catches a connector 5px off its node')
+ const dangling = structuredClone(els)
+ ;(dangling.find((e) => e.id === 'A-B') as DShape).to = { el: 'nope', side: 'auto' }
+ ok(attachFaults(dangling).length > 0, 'attach checker catches a dangling end')
+ const bent = mermaidToDiagram('flowchart TD\nA --> B --> C --> D\nA --> D', { w: 800, h: 600 }).elements
+ const curve = bent.find((e) => e.type === 'shape' && e.shape === 'path' && e.from) as DShape | undefined
+ ok(curve && !curveFaults(bent).length, 'curve baseline: a bent connector is the curve writer\'s bytes')
+ if (curve) {
+ // nudge ONE control handle by 0.01 — the size of the rounding slip this guards
+ let k = 0
+ curve.d = curve.d!.replace(/-?\d*\.?\d+/g, (v) => (k++ === 2 ? String(Math.round((+v + 0.01) * 100) / 100) : v))
+ ok(curveFaults(bent).length > 0, 'curve checker catches a control handle 0.01 off the writer\'s')
+ }
+ const escaped = structuredClone(els)
+ const t = escaped.find((e) => e.type === 'text') as DText
+ t.html = '<img src=x onerror=alert(1)>'
+ ok(htmlFaults(escaped).length > 0, 'html checker catches live markup')
+ const outside = structuredClone(els)
+ outside.find((e) => e.id === 'C')!.x += 2000
+ ok(groupFaults(outside).length > 0, 'group checker catches a member outside its box')
+ const dup = [...structuredClone(els), structuredClone(els[0])]
+ ok(idFaults(dup).length > 0, 'id checker catches a duplicate id')
+ const rr = mermaidToDiagram('flowchart LR\nA --> B\nA -->|a label| C\nD', { w: 800, h: 600 })
+ const clean = routing(rr.elements)
+ ok(!clean.node.length && !clean.box.length && !clean.label.length && !doubled(rr.elements, rr.ast).length, 'clean routing baseline passes')
+ const blocked = structuredClone(rr.elements)
+ const D = blocked.find((e) => e.id === 'D')!, AB = blocked.find((e) => e.id === 'A-B') as DShape
+ const [p0, p1] = ends(AB)
+ D.x = (p0.x + p1.x) / 2 - D.w / 2; D.y = (p0.y + p1.y) / 2 - D.h / 2
+ ok(routing(blocked).node.length > 0, 'routing checker catches an edge through a node')
+ const onEdge = structuredClone(rr.elements)
+ const lab = onEdge.find((e) => e.id === 'A-C-label')!
+ lab.x = (p0.x + p1.x) / 2 - lab.w / 2; lab.y = (p0.y + p1.y) / 2 - lab.h / 2
+ ok(routing(onEdge).label.length > 0, 'routing checker catches a label on another edge')
+ const twice = [...structuredClone(rr.elements), { ...structuredClone(AB), id: 'A-B-again' }]
+ ok(doubled(twice, rr.ast).length > 0, 'doubled-edge checker catches a second A–B connector the source never declared')
+ ok(!doubled(mermaidToDiagram('flowchart LR\nA --> B\nA --> B\nB --> A', { w: 800, h: 600 }).elements, parseMermaid('flowchart LR\nA --> B\nA --> B\nB --> A').ast).length, 'doubled-edge checker allows edges the source declares twice')
+ const sd = semantics(parseMermaid('flowchart TB\nsubgraph s\nx --> y\nend').ast), sd2 = semantics(parseMermaid('flowchart TB\nsubgraph s\ndirection TB\nx --> y\nend').ast)
+ ok(diffSemantics(sd, sd2, true).length > 0, 'round-trip comparator catches a changed subgraph direction')
+ const s1 = semantics(parseMermaid('flowchart TD\nA[x] --> B').ast)
+ for (const [bad, what] of [['flowchart TD\nA[y] --> B', 'a changed label'], ['flowchart TD\nA(x) --> B', 'a changed shape'], ['flowchart TD\nA[x] --- B', 'a changed head'], ['flowchart TD\nA[x]\nB', 'a dropped edge'], ['flowchart LR\nA[x] --> B', 'a changed direction']])
+ ok(diffSemantics(s1, semantics(parseMermaid(bad).ast), true).length > 0, `round-trip comparator catches ${what}`)
+}
+
+// --- 1. syntax coverage ----------------------------------------------------------
+
+section('syntax')
+const P = (src: string) => parseMermaid(src)
+const N = (src: string) => Object.fromEntries(P(src).ast.nodes.map((n) => [n.id, `${n.shape}:${n.label}`]))
+const E = (src: string) => P(src).ast.edges.map((e) => `${e.from}>${e.to} ${e.start}/${e.end} ${e.stroke} ${e.len} ${JSON.stringify(e.label)}`)
+{
+ for (const [h, d] of [['flowchart TD', 'TB'], ['flowchart TB', 'TB'], ['graph BT', 'BT'], ['graph LR', 'LR'], ['flowchart RL', 'RL'], ['graph', 'TB'], ['flowchart-elk LR', 'LR']])
+ ok(P(`${h}\nA-->B`).ast.dir === d, `header "${h}" → ${d}`)
+ const shapes: Array<[string, string]> = [
+ ['A[t]', 'rect'], ['A(t)', 'round'], ['A([t])', 'stadium'], ['A[[t]]', 'subroutine'], ['A[(t)]', 'cylinder'], ['A((t))', 'circle'],
+ ['A(((t)))', 'dblcircle'], ['A{t}', 'diamond'], ['A{{t}}', 'hexagon'], ['A[/t/]', 'lean-r'], ['A[\\t\\]', 'lean-l'], ['A[/t\\]', 'trap-b'],
+ ['A[\\t/]', 'trap-t'], ['A>t]', 'odd'], ['A@{ shape: tri, label: "t" }', 'tri'], ['A@{ shape: cyl, label: "t" }', 'cylinder'],
+ ['A@{ shape: diamond, label: "t" }', 'diamond'], ['A@{ shape: rounded, label: "t" }', 'round'],
+ ]
+ for (const [src, shape] of shapes) ok(N(`flowchart TD\n${src}`).A === `${shape}:t`, `shape ${src} → ${shape}`)
+ const unk = P('flowchart TD\nA@{ shape: bolt, label: "t" }')
+ ok(N('flowchart TD\nA@{ shape: bolt, label: "t" }').A === 'rect:t' && unk.warnings.some((w) => /shape bolt unsupported/.test(w)), 'unknown shape → rect + warning')
+ ok(N('flowchart TD\nA["a (b) [c] {d}"]').A === 'rect:a (b) [c] {d}', 'quoted label holds brackets')
+ ok(N('flowchart TD\nA[messages[] in]').A === 'rect:messages[] in', 'unquoted label with balanced brackets')
+ ok(N('flowchart TD\nA["#quot;q#quot; #35; #9829; &amp; &lt;"]').A === 'rect:"q" # ♥ & <', 'entity codes decode')
+ ok(N('flowchart TD\nA["one<br>two<br/>three"]').A === 'rect:one\ntwo\nthree', '<br> is a line break')
+ ok(N('flowchart TD\nA["`md\nstring`"]').A === 'rect:md\nstring', 'markdown string spans lines, backticks dropped')
+ ok(N('flowchart TD\nA[fa:fa-car Car]').A === 'rect:Car', 'font-awesome icon token dropped')
+ const links: Array<[string, string]> = [
+ ['A-->B', 'A>B none/arrow normal 1 ""'], ['A --- B', 'A>B none/none normal 1 ""'], ['A-.->B', 'A>B none/arrow dotted 1 ""'],
+ ['A-.-B', 'A>B none/none dotted 1 ""'], ['A==>B', 'A>B none/arrow thick 1 ""'], ['A===B', 'A>B none/none thick 1 ""'],
+ ['A --o B', 'A>B none/circle normal 1 ""'], ['A --x B', 'A>B none/cross normal 1 ""'], ['A <--> B', 'A>B arrow/arrow normal 1 ""'],
+ ['A o--o B', 'A>B circle/circle normal 1 ""'], ['A x--x B', 'A>B cross/cross normal 1 ""'], ['A ---> B', 'A>B none/arrow normal 2 ""'],
+ ['A ----> B', 'A>B none/arrow normal 3 ""'], ['A -..-> B', 'A>B none/arrow dotted 2 ""'], ['A ===> B', 'A>B none/arrow thick 2 ""'],
+ ['A-->|hi there|B', 'A>B none/arrow normal 1 "hi there"'], ['A -- hi there --> B', 'A>B none/arrow normal 1 "hi there"'],
+ ['A-- This is the text! ---C', 'A>C none/none normal 1 "This is the text!"'], ['A---|t|D', 'A>D none/none normal 1 "t"'],
+ ['A-. t .->B', 'A>B none/arrow dotted 1 "t"'], ['A == t ==> B', 'A>B none/arrow thick 1 "t"'], ['A --"q: x"--> B', 'A>B none/arrow normal 1 "q: x"'],
+ ['A -.ship.-> B', 'A>B none/arrow dotted 1 "ship"'], ['A --as--o B', 'A>B none/circle normal 1 "as"'], ['A -- one --> B', 'A>B none/arrow normal 1 "one"'],
+ ['A --one--> B', 'A>B none/arrow normal 1 "one"'], ['A ~~~ B', 'A>B none/none invisible 1 ""'], ['A -->|"a|b"| B', 'A>B none/arrow normal 1 "a|b"'],
+ ]
+ for (const [src, want] of links) ok(E(`flowchart LR\n${src}`)[0] === want, `link ${src} → ${want} (got ${E(`flowchart LR\n${src}`)[0]})`)
+ ok(E('flowchart LR\nA --> B --> C').join() === 'A>B none/arrow normal 1 "",B>C none/arrow normal 1 ""', 'chain A --> B --> C')
+ ok(E('flowchart LR\nA & B --> C & D').length === 4, 'A & B --> C & D is four edges')
+ ok(E('flowchart LR\na --> b & c--> d').join('|') === 'a>b none/arrow normal 1 ""|a>c none/arrow normal 1 ""|b>d none/arrow normal 1 ""|c>d none/arrow normal 1 ""', 'mixed chain and &')
+ ok(E('graph TD;A-->B;B-->C;').length === 2 && P('graph TD;A-->B;').ast.dir === 'TB', 'semicolon statements, header on the same line')
+ ok(N('flowchart TD\nA["x;y"] --> B').A === 'rect:x;y', 'semicolon inside a quoted label')
+ const sg = P('flowchart TB\nA\nsubgraph one [First one]\n direction LR\n a1-->a2\n subgraph inner\n x\n end\nend\nsubgraph "Quoted title"\n y\nend\nsubgraph t2\nA\nend\na1 --> one')
+ const g = Object.fromEntries(sg.ast.subgraphs.map((s) => [s.id, `${s.label}|${s.parent}|${s.dir ?? ''}`]))
+ ok(g.one === 'First one|null|LR' && g.inner === 'inner|one|' && g['Quoted title'] === 'Quoted title|null|', `subgraph ids, titles, nesting, direction (${JSON.stringify(g)})`)
+ const par = Object.fromEntries(sg.ast.nodes.map((n) => [n.id, n.parent]))
+ ok(par.a1 === 'one' && par.x === 'inner' && par.y === 'Quoted title' && par.A === 't2', 'membership: first subgraph that mentions a node')
+ ok(sg.ast.edges.some((e) => e.to === 'one') && !sg.ast.nodes.some((n) => n.id === 'one'), 'an edge may point at a subgraph')
+ const st = P('flowchart TD\nA:::hot --> B\nC\nclassDef hot fill:#f96,stroke:#333,stroke-width:4px,color:rgb(1, 2, 3)\nclassDef default fill:#eee\nclass B,C cool\nclassDef cool stroke:blue\nstyle C fill:hsl(10 20% 30%),color:url(x)\nstyle A fill:red;background:url(javascript:alert(1))')
+ const sty = Object.fromEntries(st.ast.nodes.map((n) => [n.id, JSON.stringify(n.style)]))
+ ok(sty.A === '{"fill":"red","stroke":"#333","color":"rgb(1, 2, 3)"}', `classDef + ::: + style, fill/stroke/color only (${sty.A})`)
+ ok(sty.B === '{"fill":"#eee","stroke":"blue"}' && sty.C === '{"fill":"hsl(10 20% 30%)","stroke":"blue"}', `class list + default class + style (${sty.B} ${sty.C})`)
+ ok(st.warnings.some((w) => /stroke-width unsupported/.test(w)) && st.warnings.some((w) => /bad colour url\(x\)/.test(w)), 'unsupported style keys and non-colours warn')
+ for (const [v, good] of [['#abc', true], ['#aabbcc80', true], ['rgb(1,2,3)', true], ['rgba(1, 2, 3, 0.5)', true], ['hsl(1 2% 3%)', true], ['teal', true], ['url(x)', false], ['red;x:y', false], ['expression(alert(1))', false], ['#12', false], ['', false]] as const)
+ ok(!!validColor(v) === good, `validColor ${JSON.stringify(v)} → ${good}`)
+ const cm = P('flowchart TD\n%% a comment\nA --> B %% trailing\n%%{init: {"theme":"dark"}}%%\nB --> C')
+ ok(cm.ast.edges.length === 2 && cm.warnings.some((w) => /directive/.test(w)), 'comments, trailing comments, directives')
+ const bad = P('flowchart TD\nA --> B\nclick A "http://x"\nlinkStyle 0 stroke:red\nA --> ??? ---\naccTitle: t\naccDescr {\n long\n}\nC')
+ ok(bad.ast.nodes.map((n) => n.id).join() === 'A,B,C' && bad.warnings.some((w) => /click unsupported/.test(w)) && bad.warnings.some((w) => /linkStyle unsupported/.test(w)) && bad.warnings.some((w) => /could not read/.test(w)), `unsupported statements warn, the rest still parses (${bad.warnings.join('; ')})`)
+ const seq = mermaidToDiagram('sequenceDiagram\nAlice->>Bob: hi', { w: 400, h: 300 })
+ ok(seq.elements.length === 0 && seq.warnings.some((w) => /sequenceDiagram/.test(w)), 'other diagram types: no elements, a warning')
+ ok(mermaidToDiagram('', { w: 400, h: 300 }).warnings.includes('empty'), 'empty source warns')
+ const fm = P('---\ntitle: T\n---\nflowchart LR\nA-->B')
+ ok(fm.ast.edges.length === 1 && fm.ast.dir === 'LR', 'front matter skipped')
+}
+
+// --- 2 + 3. corpus: invariants, determinism, snapshots, round trip ----------------
+
+section('corpus')
+const files = readdirSync(FIX).filter((f) => f.endsWith('.mmd')).sort()
+ok(files.length >= 30, `corpus has ≥ 30 flowcharts (${files.length})`)
+ok(files.filter((f) => f.startsWith('readme-')).length >= 20, 'corpus has ≥ 20 GitHub README flowcharts')
+const snaps: Record<string, string> = existsSync(SNAP) ? JSON.parse(readFileSync(SNAP, 'utf8')) : {}
+const fresh: Record<string, string> = {}
+// fixtures that are NOT valid mermaid (kept on purpose: they must warn, not crash)
+const INVALID = new Set(['readme-21-ainativelang.mmd'])
+let totalNodes = 0, totalEdges = 0
+// routing ratchet: corpus totals may only go down (measured when the compound
+// layout landed: 14 edges through nodes, 5 through boxes, 5 labels on edges
+// before it; the numbers below after it)
+const RATCHET = { node: 2, box: 2, label: 3, length: 33360, area: 9974 }
+const totals = { node: 0, box: 0, label: 0, length: 0, area: 0 }
+// fixtures that must route perfectly clean
+const CLEAN = new Set(['docs-subgraphs.mmd', 'docs-subgraph-direction.mmd', 'docs-christmas.mmd', 'readme-23-architecture-as-code.mmd', 'readme-24-architecture-as-code.mmd', 'readme-46-temporalio-graphs.mmd', 'readme-10-tachi.mmd', 'readme-09-flowchestra.mmd'])
+for (const f of files) {
+ const src = readFileSync(join(FIX, f), 'utf8')
+ ok(/^%% source: https:\/\/\S+ \((MIT|Apache-2\.0)[^)]*\)/.test(src), `${f}: attributed to a permissively licensed source`)
+ let r: ReturnType<typeof mermaidToDiagram>
+ try { r = mermaidToDiagram(src, { w: 1200, h: 800 }) } catch (e) { ok(false, `${f}: threw ${e}`); continue }
+ totalNodes += r.ast.nodes.length; totalEdges += r.ast.edges.length
+ if (!INVALID.has(f)) ok(!r.warnings.some((w) => /could not read/.test(w)), `${f}: every statement read (${r.warnings.filter((w) => /could not read/.test(w)).join('; ')})`)
+ if (!INVALID.has(f)) ok(r.ast.nodes.length > 0, `${f}: has nodes`)
+ const els = r.elements
+ for (const [name, faults] of [['overlap', overlapping(els)], ['attach', attachFaults(els)], ['groups', groupFaults(els)], ['html', htmlFaults(els)], ['ids', idFaults(els)], ['curves', curveFaults(els)]] as const)
+ ok(!faults.length, `${f}: ${name} ${faults.slice(0, 3).join(', ')}`)
+ const dbl = doubled(els, r.ast)
+ ok(!dbl.length, `${f}: no two edges share both ends unless declared twice (${dbl.join(', ')})`)
+ const rt = routing(els)
+ totals.node += rt.node.length; totals.box += rt.box.length; totals.label += rt.label.length
+ if (CLEAN.has(f)) ok(!rt.node.length && !rt.box.length && !rt.label.length, `${f}: routes clear of nodes, boxes and labels (${[...rt.node, ...rt.box, ...rt.label].join('; ')})`)
+ // compactness, measured unscaled: total connector length and drawing area
+ const big = mermaidToDiagram(src, { w: 1e5, h: 1e5 }).elements
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity
+ for (const e of big) {
+ if (isConn(e)) totals.length += polyline(e).reduce((m, p, i, a) => (i ? m + Math.hypot(p.x - a[i - 1].x, p.y - a[i - 1].y) : 0), 0)
+ x0 = Math.min(x0, e.x); y0 = Math.min(y0, e.y); x1 = Math.max(x1, e.x + e.w); y1 = Math.max(y1, e.y + e.h)
+ }
+ if (big.length) totals.area += (x1 - x0) * (y1 - y0) / 1000
+ const nodeIds = new Set(els.filter(isNode).map((e) => e.id))
+ ok(nodeIds.size === r.ast.nodes.length, `${f}: one shape per node`)
+ const texts = els.filter((e): e is DText => e.type === 'text')
+ for (const n of els.filter(isNode)) {
+ const t = texts.find((x) => x.id === `${n.id}-label`)
+ ok(t && center(t).x >= n.x && center(t).x <= n.x + n.w && center(t).y >= n.y && center(t).y <= n.y + n.h, `${f}: ${n.id} has its label inside it`)
+ }
+ ok(els.every((e) => e.x >= -0.01 && e.y >= -0.01 && e.x + e.w <= 1200.01 && e.y + e.h <= 800.01 || isConn(e)), `${f}: fits the 1200×800 frame`)
+ // determinism: a second run is byte-identical, and matches the snapshot
+ const again = mermaidToDiagram(src, { w: 1200, h: 800 })
+ ok(JSON.stringify(again) === JSON.stringify(r), `${f}: same input, same bytes`)
+ fresh[f] = hash(r.elements)
+ if (!UPDATE) ok(snaps[f] === fresh[f], `${f}: matches layout snapshot (${snaps[f]} → ${fresh[f]}; run with --update if the change is intended)`)
+ // round trip
+ if (INVALID.has(f)) continue
+ const back = diagramToMermaid(els)
+ const r2 = parseMermaid(back.src)
+ ok(!r2.warnings.length, `${f}: emitted mermaid parses clean (${r2.warnings.join('; ')})`)
+ const d = diffSemantics(semantics(r.ast), semantics(r2.ast), r.ast.edges.length > 0)
+ ok(!d.length, `${f}: round trip is semantically equal ${d.join(' | ')}`)
+ ok(!back.lost.length, `${f}: nothing lost on the way back (${JSON.stringify(back.lost.slice(0, 3))})`)
+ // and the emitted source is itself a fixed point
+ ok(diagramToMermaid(mermaidToDiagram(back.src, { w: 1200, h: 800 }).elements).src === back.src, `${f}: emitted source is a fixed point`)
+}
+console.log(` ${files.length} flowcharts, ${totalNodes} nodes, ${totalEdges} edges`)
+totals.length = Math.round(totals.length); totals.area = Math.round(totals.area)
+console.log(` routing: ${totals.node} edges through nodes, ${totals.box} through boxes, ${totals.label} labels on edges; ${totals.length} px of connectors over ${totals.area}k px² unscaled`)
+for (const k of ['node', 'box', 'label', 'length', 'area'] as const) ok(totals[k] <= RATCHET[k], `layout ratchet: ${k} ${totals[k]} ≤ ${RATCHET[k]}`)
+
+section('subgraph layout')
+{
+ const get = (els: DElement[], id: string) => els.find((e) => e.id === id)!
+ const sg = mermaidToDiagram(readFileSync(join(FIX, 'docs-subgraphs.mmd'), 'utf8'), { w: 1200, h: 800 }).elements
+ const b1 = get(sg, 'b1'), b2 = get(sg, 'b2')
+ ok(Math.abs(center(b1).y - center(b2).y) < 1 && b2.x > b1.x + b1.w, 'docs-subgraphs: "two" has no outside links, so it turns LR (b1 → b2 sideways), as in mermaid')
+ const one = get(sg, 'one'), two = get(sg, 'two'), three = get(sg, 'three')
+ const apart = (a: Box, b: Box) => a.x + a.w <= b.x || b.x + b.w <= a.x
+ ok(apart(three, one) && apart(three, two), '"three" stands beside "one" and "two", not stacked on them')
+ ok(one.y + one.h <= two.y, '"one" sits above "two" (one --> two)')
+ ok(three.y <= get(sg, 'c1').y && three.y + three.h >= get(sg, 'c2').y + get(sg, 'c2').h && get(sg, 'c2').y > two.y, '"three" spans from c1 down past "two" to c2')
+ ok((get(sg, 'one-two') as DShape).shape === 'line' && (get(sg, 'three-two') as DShape).shape === 'line', 'an edge drawn to a compound box goes straight (its layout bends belong to a member, not the box)')
+ const sd = mermaidToDiagram(readFileSync(join(FIX, 'docs-subgraph-direction.mmd'), 'utf8'), { w: 1200, h: 800 }).elements
+ const [i1, f1, i2, f2] = ['i1', 'f1', 'i2', 'f2'].map((id) => get(sd, id))
+ ok(f1.x + f1.w <= i1.x && Math.abs(center(f1).y - center(i1).y) < 1, 'direction RL inside a subgraph is honoured (f1 left of i1)')
+ ok(f2.y + f2.h <= i2.y && Math.abs(center(f2).x - center(i2).x) < 1, 'direction BT inside a subgraph is honoured (f2 above i2)')
+ const ig = mermaidToDiagram('flowchart TB\nsubgraph s\ndirection LR\nx --> y\nend\ny --> z', { w: 800, h: 600 })
+ const [x, y] = ['x', 'y'].map((id) => get(ig.elements, id))
+ ok(ig.warnings.some((w) => /direction in subgraph s ignored/.test(w)) && y.y > x.y + x.h, 'direction on a subgraph whose members link outside is ignored, with a warning (as in mermaid)')
+ // compound nesting: members of nested subgraphs that link out keep strangers out of every box
+ const nest = mermaidToDiagram('flowchart TB\nsubgraph A\n a1\n subgraph B\n b1 --> b2\n subgraph C\n c1\n end\n end\nend\nsubgraph D\n d1\nend\nr1 --> a1 --> b1\nb2 --> c1 --> d1 --> r2\nr1 --> d1\nc1 --> r2\na1 --> r2', { w: 1200, h: 800 })
+ ok(!groupFaults(nest.elements).length && !overlapping(nest.elements).length && !attachFaults(nest.elements).length, `nested compound subgraphs: clean (${groupFaults(nest.elements).join()})`)
+}
+if (UPDATE) { writeFileSync(SNAP, JSON.stringify(fresh, null, 1) + '\n'); console.log(` wrote ${SNAP}`) }
+else ok(Object.keys(snaps).sort().join() === Object.keys(fresh).sort().join(), 'snapshot file lists exactly the corpus')
+
+// --- sidecar ----------------------------------------------------------------------
+
+section('layout sidecar')
+{
+ const src = 'flowchart TD\nA --> B --> C\nA --> D'
+ const first = mermaidToDiagram(src, { w: 800, h: 600 })
+ const side = diagramLayout(first.elements)
+ ok(Object.keys(side).join() === 'A,B,C,D', 'diagramLayout names every node')
+ side.B = { x: 600, y: 40, w: 150, h: 60 }
+ const moved = mermaidToDiagram(src, { w: 800, h: 600, layout: side })
+ const B = moved.elements.find((e) => e.id === 'B')!
+ ok(B.x === 600 && B.y === 40 && B.w === 150 && B.h === 60, 'a sidecar position wins')
+ ok(!attachFaults(moved.elements).length, 'connectors re-attach to moved nodes')
+ const grown = mermaidToDiagram(src + '\nC --> E\nD --> F\nB --> G', { w: 800, h: 600, layout: side })
+ ok(!overlapping(grown.elements).length, `new nodes are placed around pinned ones (${overlapping(grown.elements).join()})`)
+ for (const id of ['A', 'B', 'C', 'D']) {
+ const e = grown.elements.find((x) => x.id === id)!
+ ok(e.x === side[id].x && e.y === side[id].y, `pinned ${id} keeps its place when the source grows`)
+ }
+ ok(JSON.stringify(grown) === JSON.stringify(mermaidToDiagram(src + '\nC --> E\nD --> F\nB --> G', { w: 800, h: 600, layout: side })), 'sidecar layout is deterministic')
+ const proto = JSON.parse('{"__proto__": {"x": 1, "y": 1, "w": 10, "h": 10}, "constructor": 5}')
+ const hostile = mermaidToDiagram('flowchart TD\nA-->B', { w: 400, h: 300, layout: proto })
+ ok(hostile.elements.length > 0 && !overlapping(hostile.elements).length, 'a hostile sidecar is ignored, not obeyed')
+ const bogus = mermaidToDiagram('flowchart TD\nA-->B', { w: 400, h: 300, layout: { A: { x: NaN, y: 0, w: 10, h: 10 }, B: { x: 0, y: 0, w: -5, h: 10 } } })
+ ok(bogus.elements.every((e) => Number.isFinite(e.x) && e.w > 0), 'non-finite or negative sidecar boxes are ignored')
+}
+
+// --- 4. what diagramToMermaid reports lost ------------------------------------------
+
+section('edge labels step off other edges')
+{
+ // pinned so that edge C→D crosses the middle of A→B, where its label would go
+ const side = { A: { x: 300, y: 100, w: 60, h: 40 }, B: { x: 300, y: 500, w: 60, h: 40 }, C: { x: 40, y: 300, w: 60, h: 40 }, D: { x: 700, y: 300, w: 60, h: 40 } }
+ const r = mermaidToDiagram('flowchart TD\nA -->|a label here| B\nC --> D', { w: 800, h: 600, layout: side })
+ ok(!routing(r.elements).label.length, `a label whose spot is crossed by another edge moves along its own edge (${routing(r.elements).label.join()})`)
+ const lab = r.elements.find((e) => e.id === 'A-B-label')!
+ ok(lab.y + lab.h < 320 || lab.y > 340, 'it moved off the crossing, not merely beside it')
+ // with nowhere clear to go the layout's spot stands
+ const fan = 'flowchart LR\n' + Array.from({ length: 12 }, (_, i) => `A -->|label ${i}| N${i}`).join('\n')
+ ok(mermaidToDiagram(fan, { w: 800, h: 600 }).elements.filter((e) => e.type === 'text').length === 25, 'a crowded fan still gets every label')
+}
+
+section('reverse: loss is reported exactly')
+{
+ const base = mermaidToDiagram('flowchart LR\nA[One] --> B[Two]', { w: 800, h: 600 }).elements
+ ok(diagramToMermaid(base).lost.length === 0, 'a pure mermaid diagram loses nothing')
+ const els = structuredClone(base) as Array<DElement & Record<string, unknown>>
+ const A = els.find((e) => e.id === 'A')!, B = els.find((e) => e.id === 'B')!
+ A.rotation = 15
+ B.opacity = 0.5
+ ;(A as Record<string, unknown>).fillGradient = { angle: 0, stops: [] }
+ ;(B as Record<string, unknown>).shadow = { blur: 4, color: '#000' }
+ const ab = els.find((e) => e.id === 'A-B') as DShape
+ ab.fill = '#ff0000'
+ ab.lineEnd = 'diamond'
+ const bl = els.find((e) => e.id === 'B-label') as DText
+ bl.html = '<b>Two</b>'
+ els.push({ id: 'img1', type: 'image' } as never)
+ els.push({ id: 'note', type: 'text', x: 5000, y: 5000, w: 10, h: 10, rotation: 0, opacity: 1, html: 'free', fontSize: 12, fontFamily: '', fontWeight: 400, color: '#000', align: 'left', valign: 'top', lineHeight: 1 } as DText)
+ els.push({ id: 'free', type: 'shape', shape: 'line', x: 0, y: 0, w: 10, h: 4, rotation: 0, opacity: 1, fill: '#000', stroke: 'transparent', strokeWidth: 2, radius: 0 } as DShape)
+ const out = diagramToMermaid(els)
+ const got = out.lost.map((l) => `${l.el}:${l.what}`).sort()
+ const want = ['A:rotation', 'A:gradient', 'B:opacity', 'B:shadow or blur', 'A-B:edge colour', 'A-B:tip "diamond"', 'B-label:rich text formatting', 'img1:image element', 'note:free text', 'free:unanchored line'].sort()
+ ok(got.join() === want.join(), `lost list is exactly ${JSON.stringify(want)} (got ${JSON.stringify(got)})`)
+ ok(/B\[Two\]/.test(out.src), 'rich text keeps its words')
+ // colours survive as style statements
+ const styled = mermaidToDiagram('flowchart TD\nA --> B\nstyle A fill:#f96,stroke:#333,color:#fff', { w: 400, h: 300 })
+ ok(/style A fill:#f96,stroke:#333,color:#fff/.test(diagramToMermaid(styled.elements).src), 'node colours come back as a style statement')
+ // hand-made elements: containment finds labels, sizes pick shapes
+ const hand: DElement[] = [
+ { id: 's1', type: 'shape', shape: 'rect', x: 0, y: 0, w: 100, h: 40, rotation: 0, opacity: 1, fill: PALETTE.fill, stroke: PALETTE.stroke, strokeWidth: 1.5, radius: 20 },
+ { id: 't9', type: 'text', x: 10, y: 5, w: 80, h: 30, rotation: 0, opacity: 1, html: 'Start &amp; go', fontSize: 16, fontFamily: '', fontWeight: 400, color: PALETTE.ink, align: 'center', valign: 'middle', lineHeight: 1.2 },
+ { id: 'e2', type: 'shape', shape: 'ellipse', x: 0, y: 200, w: 60, h: 60, rotation: 0, opacity: 1, fill: PALETTE.fill, stroke: PALETTE.stroke, strokeWidth: 1.5, radius: 0 },
+ { id: 'c', type: 'shape', shape: 'line', x: 0, y: 100, w: 150, h: 4, rotation: 90, opacity: 1, fill: PALETTE.edge, stroke: 'transparent', strokeWidth: 2, radius: 0, lineStart: 'arrow', from: { el: 's1' }, to: { el: 'e2' } },
+ ]
+ const hm = diagramToMermaid(hand).src
+ ok(hm.includes('s1(["Start & go"])') && hm.includes('e2((" "))') && hm.includes('e2 --> s1') && hm.startsWith('flowchart TD'), `hand-drawn diagram: stadium by radius, label by containment, start-arrow flips the edge (${hm.replace(/\n/g, ' / ')})`)
+}
+
+// --- 5. hostile input, with a time budget ----------------------------------------------
+
+section('hostile input')
+const BUDGET_MS = 2500
+function timed<T>(label: string, fn: () => T): T {
+ const t = performance.now()
+ const v = fn()
+ const ms = performance.now() - t
+ ok(ms < BUDGET_MS, `${label}: ${ms.toFixed(0)}ms < ${BUDGET_MS}ms`)
+ console.log(` ${label}: ${ms.toFixed(0)}ms`)
+ return v
+}
+{
+ const protoBefore = Object.getOwnPropertyNames(Object.prototype).sort().join()
+ const chain = 'flowchart TD\n' + Array.from({ length: 3000 }, (_, i) => `n${i} --> n${i + 1}`).join('\n')
+ const big = timed('3000-node chain', () => mermaidToDiagram(chain, { w: 1200, h: 800 }))
+ ok(big.warnings.some((w) => w.includes(`over ${LIMITS.nodes} nodes`)) && big.elements.filter(isNode).length === LIMITS.nodes, `huge graph capped at ${LIMITS.nodes} nodes with a warning`)
+ ok(!overlapping(big.elements).length && !attachFaults(big.elements).length, 'capped graph still lays out cleanly')
+ const K = 45
+ const dense = 'flowchart LR\n' + Array.from({ length: K }, (_, i) => Array.from({ length: K }, (_, j) => (i !== j ? `k${i} --> k${j}` : '')).filter(Boolean).join('\n')).join('\n')
+ const kd = timed(`complete digraph K${K} (${K * (K - 1)} edges, every pair a cycle)`, () => mermaidToDiagram(dense, { w: 1200, h: 800 }))
+ ok(!overlapping(kd.elements).length && !attachFaults(kd.elements).length, 'complete digraph lays out cleanly')
+ const wide = 'flowchart TD\n' + Array.from({ length: 2500 }, (_, i) => `root --> w${i}`).join('\n')
+ const wd = timed('2500-edge fan-out', () => mermaidToDiagram(wide, { w: 1200, h: 800 }))
+ ok(wd.warnings.some((w) => /nodes, rest dropped|edges, rest dropped/.test(w)), 'fan-out capped with a warning')
+ const longEdges = 'flowchart TD\n' + Array.from({ length: 499 }, (_, i) => `c${i} --> c${i + 1}`).join('\n') + '\n' + Array.from({ length: 1400 }, (_, i) => `c${i % 50} --> c${499 - (i % 400)}`).join('\n')
+ const le = timed('499-rank chain with 1400 long back/forward edges', () => mermaidToDiagram(longEdges, { w: 1200, h: 800 }))
+ ok(!overlapping(le.elements).length && !attachFaults(le.elements).length, 'long-edge graph lays out cleanly (dummy budget)')
+ const deep = 'flowchart TD\n' + Array.from({ length: 300 }, (_, i) => `subgraph s${i}`).join('\n') + '\nleaf1 --> leaf2\n' + 'end\n'.repeat(300)
+ const dp = timed('300-deep subgraph nesting', () => mermaidToDiagram(deep, { w: 1200, h: 800 }))
+ ok(dp.warnings.some((w) => /deeper than/.test(w)) && dp.ast.subgraphs.length === LIMITS.depth, `nesting flattened at ${LIMITS.depth} with a warning`)
+ ok(!groupFaults(dp.elements).length && !overlapping(dp.elements).length, 'deep nesting: boxes still contain their members')
+ const deepC = 'flowchart TD\nroot\n' + Array.from({ length: 30 }, (_, i) => `subgraph g${i}\nm${i}`).join('\n') + '\n' + 'end\n'.repeat(30) + Array.from({ length: 24 }, (_, i) => `m${i} --> root`).join('\n')
+ const dc = timed('24 nested subgraphs, every level linking out', () => mermaidToDiagram(deepC, { w: 1200, h: 800 }))
+ ok(!groupFaults(dc.elements).length && !overlapping(dc.elements).length && !attachFaults(dc.elements).length, 'deep compound nesting: boxes contain members and nothing else')
+ let seed2 = 7
+ const r2n = () => ((seed2 = (Math.imul(seed2 ^ (seed2 >>> 13), 0x5bd1e995) + 0x9e3779b9) | 0) >>> 0) / 2 ** 32
+ const many = 'flowchart LR\n' + Array.from({ length: 20 }, (_, g) => `subgraph s${g}\n` + Array.from({ length: 20 }, (_, i) => ` n${g}_${i}`).join('\n') + '\nend').join('\n') + '\n' + Array.from({ length: 900 }, () => `n${Math.floor(r2n() * 20)}_${Math.floor(r2n() * 20)} --> n${Math.floor(r2n() * 20)}_${Math.floor(r2n() * 20)}`).join('\n')
+ const mc = timed('400 nodes in 20 subgraphs, 900 random edges across them', () => mermaidToDiagram(many, { w: 1200, h: 800 }))
+ ok(!groupFaults(mc.elements).length && !overlapping(mc.elements).length && !attachFaults(mc.elements).length, 'many compound subgraphs with random cross edges: clean')
+ const proto = mermaidToDiagram('flowchart TD\n__proto__ --> constructor\nconstructor --> toString\nhasOwnProperty["#constructor; #__proto__; &constructor;"] --> __proto__\nclassDef __proto__ fill:red\nclass toString __proto__\nsubgraph prototype\nvalueOf\nend\nstyle __proto__ fill:#fff', { w: 800, h: 600 })
+ ok(Object.getOwnPropertyNames(Object.prototype).sort().join() === protoBefore && !('fill' in Object.prototype), 'Object.prototype untouched')
+ ok(!idFaults(proto.elements).length && proto.elements.filter(isNode).length === 5, `__proto__-style ids become safe, distinct element ids (${proto.elements.map((e) => e.id).join()})`)
+ ok((proto.elements.find((e) => e.id === 'hasOwnProperty_-label') as DText)?.html === '#constructor; #__proto__; &amp;constructor;', 'entity names that are Object.prototype keys stay literal')
+ ok(proto.ast.nodes.find((n) => n.id === 'toString')!.style.fill === 'red', 'a class named __proto__ works as a class')
+ const xss = mermaidToDiagram('flowchart TD\nA["<script>alert(1)</script>"] --> B["<img src=x onerror=alert(1)>"]\nB -->|"<svg onload=alert(1)>"| C[#lt;b#gt;x#lt;/b#gt;]\nC --> D["javascript:alert(1)"]', { w: 800, h: 600 })
+ ok(!htmlFaults(xss.elements).length, 'script-ish labels are escaped text')
+ ok((xss.elements.find((e) => e.id === 'A-label') as DText).html === '&lt;script&gt;alert(1)&lt;/script&gt;', 'the text itself survives, inert')
+ const xback = diagramToMermaid(xss.elements).src
+ ok(!/[<>](?!br>)/.test(xback.replace(/-->|<br>/g, '')) && semantics(parseMermaid(xback).ast).nodes.join() === semantics(xss.ast).nodes.join(), 'emitted mermaid carries no raw < or > (GitHub would render it as HTML) and round-trips')
+ const long = 'x'.repeat(10000), words = Array.from({ length: 2000 }, (_, i) => `w${i}`).join(' ')
+ const ll = timed('10k-character labels', () => mermaidToDiagram(`flowchart TD\nA["${long}"] --> B["${words}"] -->|${long}| C`, { w: 1200, h: 800 }))
+ ok(ll.warnings.some((w) => /longer than/.test(w)), 'over-long labels warn')
+ ok((ll.elements.find((e) => e.id === 'A-label') as DText).html === long, 'a 10k label keeps all of its text')
+ ok(!overlapping(ll.elements).length && !attachFaults(ll.elements).length, '10k labels still lay out cleanly')
+ const comments = 'flowchart TD\n' + '%% comment line\n'.repeat(100000) + 'A --> B'
+ timed('100k comment lines', () => mermaidToDiagram(comments, { w: 400, h: 300 }))
+ const unterminated = ['flowchart TD\nA[unterminated', 'flowchart TD\nA["unterminated --> B', 'flowchart TD\nsubgraph x\nA', 'flowchart TD\nend\nend', 'flowchart TD\nA -->', 'flowchart TD\n--> B', 'flowchart TD\nA@{ shape: ', 'flowchart TD\nA -- never closes', 'flowchart TD\n"q" --> B', 'flowchart TD\nA(((x)) --> B', 'graph TD\n\u0000‮\ud800 --> B']
+ for (const u of unterminated) {
+ let r: ReturnType<typeof mermaidToDiagram> | null = null
+ try { r = mermaidToDiagram(u, { w: 400, h: 300 }) } catch (e) { ok(false, `${JSON.stringify(u)} threw ${e}`) }
+ if (r) ok(!overlapping(r.elements).length && !attachFaults(r.elements).length && !htmlFaults(r.elements).length, `${JSON.stringify(u)}: no crash, clean output`)
+ }
+ // seeded token soup: never throws, output always sound
+ let seed = 0x9e3779b9
+ const rnd = () => ((seed = (Math.imul(seed ^ (seed >>> 15), 0x2c1b3c6d) + 0x6d2b79f5) | 0) >>> 0) / 2 ** 32
+ const T = ['A', 'B', 'c1', '__proto__', '-->', '---', '-.->', '==>', '--', '-.', '==', '|', '"', '[', ']', '(', ')', '{', '}', '((', '))', '>', '/', '\\', '&', ';', '\n', ' ', 'subgraph', 'end', 'classDef', 'class', 'style', ':::', 'fill:#f00', 'x', 'o', '<', '%%', '@{', 'shape:', '#quot;', '<br>', 'direction', 'LR']
+ let soupFaults = 0, threw = 0, lively = 0
+ const soup = timed('2000 random token soups', () => {
+ for (let n = 0; n < 2000; n++) {
+ // half plausible statements with random corruption, half raw token soup
+ const pick = <X,>(xs: X[]) => xs[Math.floor(rnd() * xs.length)]
+ let s = rnd() < 0.9 ? pick(['flowchart TD\n', 'graph LR\n', 'flowchart BT;', 'flowchart RL\n']) : ''
+ const len = 1 + Math.floor(rnd() * 30)
+ for (let k = 0; k < len; k++) {
+ if (rnd() < 0.5) {
+ const node = () => pick(['A', 'B', 'c1', 'end', '__proto__', 'x', 'o', 'q.r', 'n-1']) + (rnd() < 0.5 ? pick(['[t]', '(t)', '{t}', '((t))', '[/t\\]', '>t]', '["a;b"]', '@{ shape: tri }', '[[t]]', '{{t}}']) : '')
+ s += node()
+ for (let m = Math.floor(rnd() * 3); m >= 0; m--) s += ' ' + pick(['-->', '---', '-.->', '==>', '-- l -->', '-->|l|', '<-->', '--o', '--x', '~~~', '&']) + ' ' + node()
+ s += pick(['\n', ';', '\n', ' ' + pick(T)])
+ } else s += pick(T) + (rnd() < 0.5 ? ' ' : '')
+ }
+ try {
+ const r = mermaidToDiagram(s, { w: 600, h: 400 })
+ if (r.elements.some(isConn)) lively++
+ if (overlapping(r.elements).length || attachFaults(r.elements).length || htmlFaults(r.elements).length || idFaults(r.elements).length || groupFaults(r.elements).length) { if (!soupFaults++) console.log(' first fault:', JSON.stringify(s)) }
+ diagramToMermaid(r.elements)
+ } catch (e) { if (!threw++) console.log(' first throw:', JSON.stringify(s), e) }
+ }
+ return true
+ })
+ ok(soup && !threw, `token soup never throws (${threw})`)
+ ok(!soupFaults, `token soup output is always sound (${soupFaults})`)
+ ok(lively >= 200, `the soup is not all rejects: ${lively} of 2000 produce connectors`)
+}
+
+// --- 6. size budget ------------------------------------------------------------------
+
+section('size')
+{
+ const esbuild = join(root, 'slides/node_modules/.bin/esbuild')
+ ok(existsSync(esbuild), 'esbuild is installed (npm ci in slides/) — the size budget cannot be skipped')
+ if (existsSync(esbuild)) {
+ // Minified bytes. The brief's target was 10 KB for parser + layout; see the
+ // PR for why it sits above that. These budgets stop it GROWING unnoticed.
+ const BUDGET = { 'parser + layout': 20500, 'mermaid → elements': 31000, 'whole module (both directions)': 37000 }
+ const entries: Record<keyof typeof BUDGET, string> = {
+ 'parser + layout': "export { parseMermaid } from './spaces/src/diagram/mermaid.ts'; export { layout } from './spaces/src/diagram/layout.ts'",
+ 'mermaid → elements': "export { mermaidToDiagram } from './spaces/src/diagram/mermaid.ts'",
+ 'whole module (both directions)': "export * from './spaces/src/diagram/mermaid.ts'",
+ }
+ const tmp = mkdtempSync(join(tmpdir(), 'bento-mermaid-size-'))
+ try {
+ for (const [name, code] of Object.entries(entries) as Array<[keyof typeof BUDGET, string]>) {
+ const r = spawnSync(esbuild, ['--bundle', '--minify', '--format=esm', '--sourcefile=entry.ts', '--loader=ts'], { input: code, encoding: 'utf8', cwd: root })
+ const bytes = Buffer.byteLength(r.stdout ?? '')
+ ok(r.status === 0 && bytes > 1000, `${name}: bundles (${r.stderr?.slice(0, 200)})`)
+ ok(bytes <= BUDGET[name], `${name}: ${bytes} B ≤ ${BUDGET[name]} B minified`)
+ console.log(` ${name}: ${bytes} B minified`)
+ }
+ } finally { rmSync(tmp, { recursive: true, force: true }) }
+ }
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) { console.log(`${failures} FAILED`); process.exit(1) }
diff --git a/spaces/src/diagram/layout.ts b/spaces/src/diagram/layout.ts
new file mode 100644
index 00000000..353e22f3
--- /dev/null
+++ b/spaces/src/diagram/layout.ts
@@ -0,0 +1,586 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// A small layered (Sugiyama-style) layout for compound directed graphs.
+// Written for mermaid.ts; pure, DOM-free and deterministic: the same input
+// gives the same output byte for byte (no randomness, no Map-order surprises:
+// every iteration order is the input order). A kernel candidate, with
+// mermaid.ts: it imports nothing but the kernel's geometry TYPES.
+//
+// SUBGRAPHS, the way mermaid treats them:
+// · a subgraph none of whose members links outside it is laid out on its own
+// (in its own `direction`, or the parent's flipped: TB ⇄ LR, as mermaid
+// does) and then takes part in its parent as ONE node of its own size;
+// · a subgraph whose members DO link outside is a compound: its members take
+// part in the parent's layering and ordering, kept contiguous in every
+// layer, and its box is solved together with everything around it, so a
+// non-member never lands inside it. Edges between subgraphs get their bend
+// points in the space BETWEEN the boxes. (Mermaid ignores `direction` on
+// such a subgraph, and so do we.)
+//
+// The phases of one layered pass:
+// 1. cycle breaking — depth-first from the sources; an edge that closes a
+// cycle is laid out reversed (it still draws its own way);
+// 2. layer assignment — longest path, then sources pulled down next to their
+// first successor so a lone start node does not float at the top;
+// 3. every rank is DOUBLED (dagre's trick): real nodes sit on even layers and
+// a labelled edge gets a dummy of its label's size on the odd layer in its
+// middle, so edge labels take up real space and never overlap a node;
+// longer edges get a chain of thin dummies, which become their bends. A
+// dummy belongs to the innermost subgraph holding both ends of its edge;
+// 4. crossing reduction — barycentre sweeps down and up, keeping the best
+// ordering seen (crossings counted exactly with a Fenwick tree). The sort
+// key is hierarchical, so a subgraph's members stay contiguous, and a
+// subgraph's key is global, so sibling subgraphs keep one order in every
+// layer (otherwise their boxes could not both be rectangles);
+// 5. coordinates — each layer, subgraph borders included, is placed at the
+// positions its neighbours' mean asks for, subject to the minimum
+// separations: isotonic regression, solved exactly by pool-adjacent-
+// violators, a few rounds. Then one longest-path pass over the separation
+// constraints, with each subgraph's left and right border as ONE variable
+// across all its layers, makes the result legal;
+// 6. the direction (TB/BT/LR/RL) is a final transform of a TB layout.
+
+import type { Box, Pt } from '../../../kernel/src/geom.ts'
+export type { Box, Pt }
+
+export type Dir = 'TB' | 'BT' | 'LR' | 'RL'
+
+/** A node to place. `parent` is the id of the cluster it sits in (null = root). */
+export interface LNode { id: string; w: number; h: number; parent: string | null }
+/** A cluster (subgraph). `top` is the room its title needs above the content. */
+export interface LCluster { id: string; parent: string | null; dir?: Dir; top: number; minW: number }
+/** An edge between two node or cluster ids. `lw/lh` = the label's size (0 when none). */
+export interface LEdge { from: string; to: string; minlen: number; lw: number; lh: number }
+
+export interface LOpts { nodeGap: number; rankGap: number; pad: number; maxDummies: number }
+
+export interface LResult {
+ nodes: Map<string, Box>
+ clusters: Map<string, Box>
+ /** per input edge: the bend points between its two ends (absolute), and the
+ * label centre when it has a label. Endpoints are NOT included — they are
+ * derived on the node borders, the way slides' syncConnectors derives them. */
+ edges: Array<{ bends: Pt[]; label?: Pt }>
+ w: number
+ h: number
+ /** true when the dummy budget ran out and some long edges were left straight */
+ capped: boolean
+ /** subgraphs whose `direction` was ignored because their members link outside */
+ ignoredDir: string[]
+}
+
+/** one entry of a layer. kind: 0 item, 1 bend, 2 label, 3 filler, 4 left border, 5 right border */
+interface Ent { w: number; h: number; g: number; kind: number }
+interface Sub { box: Box[]; groups: Box[]; bends: Map<number, Pt[]>; labels: Map<number, Pt>; w: number; h: number }
+type LE = [number, number, number, number, number, number, number] // u v minlen lw lh edgeIndex group
+
+const r2 = (v: number) => Math.round(v * 100) / 100
+
+export function layout(nodes: LNode[], clusters: LCluster[], edges: LEdge[], dir: Dir, o: LOpts): LResult {
+ const parentOf = new Map<string, string | null>()
+ const cinfo = new Map<string, LCluster>()
+ for (const c of clusters) { parentOf.set(c.id, c.parent); cinfo.set(c.id, c) }
+ for (const n of nodes) parentOf.set(n.id, n.parent)
+ const anc = (x: string): string[] => {
+ const out: string[] = []
+ for (let p = parentOf.get(x); p != null && out.length < 1000; p = parentOf.get(p)) out.push(p)
+ return out
+ }
+ // a subgraph is COMPOUND when an edge has exactly one end strictly inside it
+ // (an edge to the subgraph itself does not count)
+ const compound = new Set<string>()
+ for (const e of edges) {
+ const A = anc(e.from), B = anc(e.to)
+ for (const c of A) if (!B.includes(c) && c !== e.to) compound.add(c)
+ for (const c of B) if (!A.includes(c) && c !== e.from) compound.add(c)
+ }
+ // the context an id is laid out in: its nearest non-compound ancestor (null = root)
+ const ctxOf = (x: string): string | null => anc(x).find((c) => !compound.has(c)) ?? null
+ const res: LResult = { nodes: new Map(), clusters: new Map(), edges: edges.map(() => ({ bends: [] })), w: 0, h: 0, capped: false, ignoredDir: [] }
+ let budget = o.maxDummies
+ const size = new Map<string, { w: number; h: number }>()
+ for (const n of nodes) size.set(n.id, n)
+ const cdir = new Map<string | null, Dir>([[null, dir]])
+ // contexts, children before parents: deeper first, then input order
+ const ctxs: Array<string | null> = clusters.filter((c) => !compound.has(c.id)).map((c) => c.id)
+ ctxs.sort((a, b) => anc(b!).length - anc(a!).length)
+ ctxs.push(null)
+ for (const c of clusters) if (compound.has(c.id) && c.dir) res.ignoredDir.push(c.id)
+ const dirOf = (k: string | null): Dir => {
+ if (cdir.has(k)) return cdir.get(k)!
+ const pd = dirOf(ctxOf(k!))
+ const d = cinfo.get(k!)!.dir ?? (pd === 'TB' ? 'LR' : 'TB')
+ cdir.set(k, d)
+ return d
+ }
+ const subs = new Map<string | null, { sub: Sub; items: string[]; groups: string[] }>()
+ for (const K of ctxs) {
+ // items: nodes and non-compound subgraphs whose context is K; groups: compound subgraphs in K
+ const items: string[] = [], groups: string[] = []
+ for (const n of nodes) if (ctxOf(n.id) === K) items.push(n.id)
+ for (const c of clusters) if (c.id !== K && ctxOf(c.id) === K) (compound.has(c.id) ? groups : items).push(c.id)
+ const ii = new Map(items.map((id, i) => [id, i]))
+ const gi = new Map(groups.map((id, i) => [id, i]))
+ const grpOf = (id: string) => { const p = parentOf.get(id); return p != null && gi.has(p) ? gi.get(p)! : -1 }
+ const gpar = groups.map(grpOf)
+ // lift an endpoint into K: an item, or a compound group (drawn to its box)
+ const lift = (x: string): { i?: number; g?: number } | null => {
+ for (let cur: string | null | undefined = x; cur != null && cur !== K; cur = parentOf.get(cur)) {
+ if (ii.has(cur)) return { i: ii.get(cur)! }
+ if (gi.has(cur)) return cur === x ? { g: gi.get(cur)! } : null
+ }
+ return null
+ }
+ const inGroup = (i: number, g: number) => { for (let p = grpOf(items[i]); p >= 0; p = gpar[p]) if (p === g) return true; return false }
+ const lifted: Array<[{ i?: number; g?: number }, { i?: number; g?: number }, number]> = []
+ edges.forEach((e, k) => {
+ const a = lift(e.from), b = lift(e.to)
+ if (a && b) lifted.push([a, b, k])
+ })
+ // an edge to a compound subgraph's box is laid out against one of its
+ // members: a source member for an edge coming in, a sink member going out
+ const rep = (g: number, incoming: boolean): number => {
+ let first = -1
+ for (let i = 0; i < items.length; i++) {
+ if (!inGroup(i, g)) continue
+ if (first < 0) first = i
+ if (!lifted.some(([a, b]) => a.i !== undefined && b.i !== undefined && inGroup(a.i, g) && inGroup(b.i, g) && (incoming ? b.i === i : a.i === i) && a.i !== b.i)) return i
+ }
+ return first
+ }
+ const chainG = (x: { i?: number; g?: number }): number[] => {
+ const c: number[] = []
+ for (let g = x.i !== undefined ? grpOf(items[x.i]) : gpar[x.g!]; g >= 0; g = gpar[g]) c.push(g)
+ return c
+ }
+ const es: LE[] = []
+ const toBox = new Set<number>()
+ for (const [a, b, k] of lifted) {
+ if (a.g !== undefined || b.g !== undefined) toBox.add(k)
+ const u = a.i ?? rep(a.g!, false), v = b.i ?? rep(b.g!, true)
+ if (u < 0 || v < 0 || u === v) continue
+ const cb = chainG(b)
+ const lca = chainG(a).find((g) => cb.includes(g)) ?? -1
+ es.push([u, v, edges[k].minlen, edges[k].lw, edges[k].lh, k, lca])
+ }
+ const its = items.map((id) => ({ ...size.get(id)!, group: grpOf(id) }))
+ const gs = groups.map((id, i) => ({ parent: gpar[i], top: cinfo.get(id)!.top, minW: cinfo.get(id)!.minW }))
+ const sub = layered(its, gs, es, dirOf(K), o, () => budget, (n) => { budget -= n })
+ if (sub.capped) res.capped = true
+ // an edge drawn to a compound box was laid out against one of its members:
+ // its bends belong to that member, not the box, so it is drawn straight
+ for (const k of toBox) { sub.bends.delete(k); sub.labels.delete(k) }
+ if (K !== null) {
+ const c = cinfo.get(K)!
+ size.set(K, { w: Math.max(sub.w + 2 * o.pad, c.minW + 2 * o.pad), h: sub.h + 2 * o.pad + c.top })
+ }
+ subs.set(K, { sub: { ...sub, w: sub.w, h: sub.h }, items, groups })
+ }
+ // top-down: absolute positions
+ const place = (K: string | null, ox: number, oy: number) => {
+ const { sub, items, groups } = subs.get(K)!
+ let cx = ox, cy = oy
+ if (K !== null) {
+ const c = cinfo.get(K)!, sz = size.get(K)!
+ cx = ox + o.pad + (sz.w - 2 * o.pad - sub.w) / 2
+ cy = oy + o.pad + c.top
+ }
+ const abs = (b: Box): Box => ({ x: r2(cx + b.x), y: r2(cy + b.y), w: r2(b.w), h: r2(b.h) })
+ groups.forEach((id, g) => res.clusters.set(id, abs(sub.groups[g])))
+ items.forEach((id, i) => {
+ const b = abs(sub.box[i])
+ if (cinfo.has(id)) { res.clusters.set(id, b); place(id, b.x, b.y) } else res.nodes.set(id, b)
+ })
+ for (const [i, pts] of sub.bends) res.edges[i].bends = pts.map((p) => ({ x: r2(cx + p.x), y: r2(cy + p.y) }))
+ for (const [i, p] of sub.labels) res.edges[i].label = { x: r2(cx + p.x), y: r2(cy + p.y) }
+ }
+ place(null, 0, 0)
+ const root = subs.get(null)!.sub
+ res.w = r2(root.w)
+ res.h = r2(root.h)
+ return res
+}
+
+/** Layered layout of one context: items, compound groups, edges. TB-space inside. */
+function layered(
+ items: Array<{ w: number; h: number; group: number }>,
+ groups: Array<{ parent: number; top: number; minW: number }>,
+ es: LE[],
+ dir: Dir,
+ o: LOpts,
+ budget: () => number,
+ spend: (n: number) => void,
+): Sub & { capped: boolean } {
+ const horiz = dir === 'LR' || dir === 'RL'
+ const N = items.length, G = groups.length
+ const gpar = groups.map((g) => g.parent)
+ // a group's padding in TB-space: the title sits on whichever side becomes the top
+ const padTop = (g: number) => o.pad + (dir === 'TB' ? groups[g].top : 0)
+ const padBot = (g: number) => o.pad + (dir === 'BT' ? groups[g].top : 0)
+ const padLeft = (g: number) => o.pad + (horiz ? groups[g].top : 0)
+ const out: number[][] = items.map(() => [])
+ es.forEach(([u, v], k) => { if (u !== v) out[u].push(k) })
+ // 1. cycle breaking: depth-first from the sources, in input order (a
+ // flowchart's "reject → back to start" edge is the one reversed, as in
+ // mermaid). A graph with no source — every node on a cycle — is entered at
+ // the node with the most (out − in) edges, parallel edges counted.
+ const deg = new Float64Array(N)
+ const hasIn = new Uint8Array(N)
+ es.forEach(([u, v]) => { if (u !== v) { deg[u]++; deg[v]--; hasIn[v] = 1 } })
+ const roots = [...items.keys()].sort((a, b) => hasIn[a] - hasIn[b] || (hasIn[a] ? deg[b] - deg[a] : 0) || a - b)
+ const rev = new Set<number>()
+ const state = new Uint8Array(N) // 0 new, 1 on stack, 2 done
+ for (const s of roots) {
+ if (state[s]) continue
+ const st: Array<[number, number]> = [[s, 0]]
+ state[s] = 1
+ while (st.length) {
+ const top = st[st.length - 1]
+ const [n, i] = top
+ if (i < out[n].length) {
+ top[1]++
+ const k = out[n][i]
+ const v = es[k][1]
+ if (state[v] === 1) rev.add(k)
+ else if (!state[v]) { state[v] = 1; st.push([v, 0]) }
+ } else { state[n] = 2; st.pop() }
+ }
+ }
+ const dag = es.map(([u, v, m], k): [number, number, number] => (rev.has(k) ? [v, u, m] : [u, v, m]))
+ // 2. longest-path layering (Kahn, input order), minlen doubled
+ const indeg = new Int32Array(N)
+ const succ: number[][] = items.map(() => [])
+ const dagIn = new Uint8Array(N)
+ dag.forEach(([u, v], k) => { if (u !== v) { indeg[v]++; succ[u].push(k); dagIn[v] = 1 } })
+ const layer = new Int32Array(N)
+ const topo: number[] = []
+ for (let i = 0; i < N; i++) if (!indeg[i]) topo.push(i)
+ for (let q = 0; q < topo.length; q++) {
+ const u = topo[q]
+ for (const k of succ[u]) {
+ const [, v, m] = dag[k]
+ layer[v] = Math.max(layer[v], layer[u] + 2 * Math.max(1, m))
+ if (!--indeg[v]) topo.push(v)
+ }
+ }
+ // pull each source down to just above its nearest successor
+ for (let q = topo.length - 1; q >= 0; q--) {
+ const u = topo[q]
+ if (dagIn[u] || !succ[u].length) continue
+ let best = Infinity
+ for (const k of succ[u]) best = Math.min(best, layer[dag[k][1]] - 2 * Math.max(1, dag[k][2]))
+ if (best > layer[u] && best < Infinity) layer[u] = best
+ }
+ // 3. dummies: a chain per long edge; a labelled edge's middle dummy has the label's size
+ const all: Ent[] = items.map((it) => ({ w: horiz ? it.h : it.w, h: horiz ? it.w : it.h, g: it.group, kind: 0 }))
+ const lay: number[] = Array.from(layer)
+ const chains = new Map<number, number[]>() // es index → dummy entry indices
+ const adjUp: number[][] = all.map(() => [])
+ const adjDn: number[][] = all.map(() => [])
+ const add = (e: Ent, l: number) => { all.push(e); lay.push(l); adjUp.push([]); adjDn.push([]); return all.length - 1 }
+ const link = (a: number, b: number) => { adjDn[a].push(b); adjUp[b].push(a) }
+ let capped = false
+ dag.forEach(([u, v], k) => {
+ if (u === v) return
+ const span = lay[v] - lay[u]
+ const [, , , lw, lh, , grp] = es[k]
+ if (span - 1 > budget()) { capped = true; link(u, v); return }
+ spend(span - 1)
+ const mid = lay[u] + (span >> 1) - ((span >> 1) % 2 === 0 ? 1 : 0)
+ const chain: number[] = []
+ let prev = u
+ for (let l = lay[u] + 1; l < lay[v]; l++) {
+ const lab = lw > 0 && l === mid
+ const id = add(lab ? { w: horiz ? lh : lw, h: horiz ? lw : lh, g: grp, kind: 2 } : { w: 2, h: 0, g: grp, kind: 1 }, l)
+ chain.push(id)
+ link(prev, id)
+ prev = id
+ }
+ link(prev, v)
+ chains.set(k, rev.has(k) ? chain.reverse() : chain)
+ })
+ // groups: root-first ancestor chains, layer spans, and a filler wherever a
+ // group spans a layer it has nothing in (else a stranger could sit inside its box)
+ const up = (g: number) => { const c: number[] = []; for (; g >= 0; g = gpar[g]) c.unshift(g); return c }
+ const gchain = groups.map((_, g) => up(g))
+ const lo = new Array<number>(G).fill(Infinity), hi = new Array<number>(G).fill(-Infinity)
+ const has = new Set<number>() // g * Lmax + l
+ let Lmax = 0
+ for (const l of lay) Lmax = Math.max(Lmax, l + 1)
+ const mark = (g: number, l: number) => { for (const x of gchain[g]) { lo[x] = Math.min(lo[x], l); hi[x] = Math.max(hi[x], l); has.add(x * Lmax + l) } }
+ all.forEach((e, n) => { if (e.g >= 0) mark(e.g, lay[n]) })
+ for (let g = G - 1; g >= 0; g--) for (let l = lo[g]; l <= hi[g]; l++) if (!has.has(g * Lmax + l)) { add({ w: 0, h: 0, g, kind: 3 }, l); mark(g, l) }
+ const chainOf = (n: number) => (all[n].g >= 0 ? gchain[all[n].g] : [])
+ // 4. ordering: layers in DFS discovery order, then hierarchical barycentre sweeps
+ const L = Lmax || 1
+ const layers: number[][] = Array.from({ length: L }, () => [])
+ const seen = new Uint8Array(all.length)
+ for (let s = 0; s < N; s++) {
+ if (seen[s] || dagIn[s]) continue
+ const st = [s]
+ while (st.length) {
+ const n = st.pop()!
+ if (seen[n]) continue
+ seen[n] = 1
+ layers[lay[n]].push(n)
+ for (let i = adjDn[n].length - 1; i >= 0; i--) if (!seen[adjDn[n][i]]) st.push(adjDn[n][i])
+ }
+ }
+ for (let s = 0; s < all.length; s++) if (!seen[s]) { seen[s] = 1; layers[lay[s]].push(s) }
+ const pos = new Float64Array(all.length)
+ const setPos = () => layers.forEach((ly) => ly.forEach((n, i) => { pos[n] = i }))
+ setPos()
+ const rel = (n: number) => (pos[n] + 0.5) / layers[lay[n]].length
+ const nkey = new Float64Array(all.length)
+ const gkey = new Float64Array(G)
+ const sortLayer = (l: number) => {
+ layers[l].sort((a, b) => {
+ const ca = chainOf(a), cb = chainOf(b)
+ let i = 0
+ while (i < ca.length && i < cb.length && ca[i] === cb[i]) i++
+ const ka = i < ca.length ? gkey[ca[i]] : nkey[a], kb = i < cb.length ? gkey[cb[i]] : nkey[b]
+ return ka - kb || (i < ca.length ? ca[i] : G + pos[a]) - (i < cb.length ? cb[i] : G + pos[b])
+ })
+ layers[l].forEach((n, i) => { pos[n] = i })
+ }
+ const groupKeys = () => {
+ const sum = new Float64Array(G), cnt = new Float64Array(G)
+ all.forEach((_, n) => { for (const g of chainOf(n)) { sum[g] += rel(n); cnt[g]++ } })
+ for (let g = 0; g < G; g++) gkey[g] = cnt[g] ? sum[g] / cnt[g] : 0
+ }
+ const crossings = () => {
+ let c = 0
+ for (let l = 0; l < L - 1; l++) {
+ const pairs: Array<[number, number]> = []
+ for (const n of layers[l]) for (const m of adjDn[n]) pairs.push([pos[n], pos[m]])
+ pairs.sort((a, b) => a[0] - b[0] || a[1] - b[1])
+ const size = layers[l + 1].length + 1
+ const bit = new Int32Array(size + 1)
+ for (let i = 0; i < pairs.length; i++) {
+ // count earlier pairs whose lower end is to the right of this one's
+ let s = 0
+ for (let j = size; j > 0; j -= j & -j) s += bit[j]
+ let le = 0
+ for (let j = pairs[i][1] + 1; j > 0; j -= j & -j) le += bit[j]
+ c += s - le
+ for (let j = pairs[i][1] + 1; j <= size; j += j & -j) bit[j]++
+ }
+ }
+ return c
+ }
+ // the first pass only makes groups contiguous and consistently ordered
+ groupKeys()
+ for (let n = 0; n < all.length; n++) nkey[n] = rel(n)
+ for (let l = 0; l < L; l++) sortLayer(l)
+ let best = layers.map((l) => l.slice())
+ let bestC = crossings()
+ for (let it = 0; it < 8 && bestC > 0; it++) {
+ const down = it % 2 === 0
+ groupKeys()
+ for (let k = 1; k < L; k++) {
+ const l = down ? k : L - 1 - k
+ const nb = down ? adjUp : adjDn
+ for (const n of layers[l]) {
+ const ns = nb[n]
+ nkey[n] = ns.length ? ns.reduce((s, m) => s + rel(m), 0) / ns.length : rel(n)
+ }
+ sortLayer(l)
+ }
+ const c = crossings()
+ if (c < bestC) { bestC = c; best = layers.map((l) => l.slice()) }
+ }
+ for (let l = 0; l < L; l++) layers[l] = best[l]
+ setPos()
+ // 5. coordinates. Each layer becomes a token list with each group's left and
+ // right borders as zero-width tokens around its members.
+ const E0 = all.length
+ const side = new Map<number, number>() // (g * L + l) * 2 + right → token entry
+ const tokens: number[][] = layers.map((ly, l) => {
+ const t: number[] = [], open: number[] = []
+ const close = (keep: number) => { while (open.length > keep) { const g = open.pop()!; const id = add({ w: 0, h: 0, g, kind: 5 }, l); side.set((g * L + l) * 2 + 1, id); t.push(id) } }
+ for (const n of ly) {
+ const c = chainOf(n)
+ let i = 0
+ while (i < open.length && i < c.length && open[i] === c[i]) i++
+ close(i)
+ for (; i < c.length; i++) { const id = add({ w: 0, h: 0, g: c[i], kind: 4 }, l); side.set((c[i] * L + l) * 2, id); t.push(id); open.push(c[i]) }
+ t.push(n)
+ }
+ close(0)
+ return t
+ })
+ const half = (n: number) => (all[n].kind < 4 ? all[n].w / 2 : 0)
+ const light = (n: number) => all[n].kind === 1 || all[n].kind === 2 || all[n].kind === 3
+ const gap = (a: number, b: number) => {
+ const A = all[a], B = all[b]
+ if (A.kind === 4) return padLeft(A.g)
+ if (B.kind === 5) return o.pad
+ return light(a) && light(b) ? o.nodeGap / 4 : light(a) || light(b) ? o.nodeGap / 2 : o.nodeGap
+ }
+ const sep = (a: number, b: number) => half(a) + gap(a, b) + half(b)
+ const x = new Float64Array(all.length)
+ for (const t of tokens) {
+ let cx = 0
+ t.forEach((n, i) => { if (i) cx += sep(t[i - 1], n); x[n] = cx })
+ }
+ const place = (t: number[], want: (n: number) => number | null) => {
+ if (!t.length) return
+ // target_i = desired_i − offset_i must be non-decreasing: PAVA
+ const off: number[] = [0]
+ for (let i = 1; i < t.length; i++) off.push(off[i - 1] + sep(t[i - 1], t[i]))
+ const blocks: Array<{ v: number; wt: number; n: number }> = []
+ t.forEach((n, i) => {
+ const w = want(n)
+ const wt = all[n].kind >= 4 ? 4 : all[n].kind ? 2 : 1
+ blocks.push({ v: (w ?? x[n]) - off[i], wt: w === null ? 0.01 : wt, n: 1 })
+ while (blocks.length > 1 && blocks[blocks.length - 2].v >= blocks[blocks.length - 1].v) {
+ const b = blocks.pop()!, a = blocks[blocks.length - 1]
+ a.v = (a.v * a.wt + b.v * b.wt) / (a.wt + b.wt)
+ a.wt += b.wt
+ a.n += b.n
+ }
+ })
+ let i = 0
+ for (const b of blocks) for (let j = 0; j < b.n; j++, i++) x[t[i]] = b.v + off[i]
+ }
+ const mean = (ns: number[]) => (ns.length ? ns.reduce((s, m) => s + x[m], 0) / ns.length : null)
+ // a border wants to line up with the same border one layer up and down
+ const border = (n: number, l: number, dirs: number[]) => {
+ const e = all[n], ns: number[] = []
+ for (const d of dirs) { const m = side.get((e.g * L + l + d) * 2 + (e.kind - 4)); if (m !== undefined && l + d >= 0 && l + d < L) ns.push(m) }
+ return mean(ns)
+ }
+ for (let round = 0; round < 6; round++) {
+ const down = round % 2 === 0
+ for (let k = 0; k < L; k++) {
+ const l = down ? k : L - 1 - k
+ const d = round === 5 ? [-1, 1] : [down ? -1 : 1]
+ place(tokens[l], (n) => (all[n].kind >= 4 ? border(n, l, d) : all[n].kind === 3 ? null : mean(round === 5 ? adjUp[n].concat(adjDn[n]) : down ? adjUp[n] : adjDn[n])))
+ }
+ }
+ // legalise: longest path over the separation constraints, a group's left
+ // (and right) border being ONE variable in every layer it spans
+ const V = E0 + 2 * G
+ const vOf = (n: number) => (all[n].kind === 4 ? E0 + 2 * all[n].g : all[n].kind === 5 ? E0 + 2 * all[n].g + 1 : n)
+ const val = new Float64Array(V).fill(-Infinity)
+ for (let n = 0; n < E0; n++) val[n] = x[n]
+ const outs: Array<Array<[number, number]>> = Array.from({ length: V }, () => [])
+ const indg = new Int32Array(V)
+ const need = (a: number, b: number, d: number) => { outs[a].push([b, d]); indg[b]++ }
+ for (let n = E0; n < all.length; n++) if (all[n].kind === 4) val[vOf(n)] = Math.min(val[vOf(n)] === -Infinity ? Infinity : val[vOf(n)], x[n])
+ for (let g = 0; g < G; g++) if (!horiz) need(E0 + 2 * g, E0 + 2 * g + 1, groups[g].minW + 2 * o.pad)
+ for (const t of tokens) for (let i = 1; i < t.length; i++) need(vOf(t[i - 1]), vOf(t[i]), sep(t[i - 1], t[i]))
+ const q: number[] = []
+ for (let v = 0; v < V; v++) if (!indg[v]) q.push(v)
+ const done = new Uint8Array(V)
+ const relax = (v: number) => { done[v] = 1; for (const [w, d] of outs[v]) { if (val[v] + d > val[w]) val[w] = val[v] + d; if (!--indg[w]) q.push(w) } }
+ for (let i = 0; i < q.length; i++) relax(q[i])
+ for (let v = 0; v < V; v++) if (!done[v]) relax(v) // a cycle (should not happen): best effort
+ // pull each left border in as far as its contents allow, innermost first
+ for (const g of [...groups.keys()].sort((a, b) => gchain[b].length - gchain[a].length)) {
+ const Lv = E0 + 2 * g
+ let m = val[Lv + 1] - (horiz ? 0 : groups[g].minW) - 2 * o.pad
+ for (const [w, d] of outs[Lv]) if (w !== Lv + 1) m = Math.min(m, val[w] - d)
+ if (m > val[Lv]) val[Lv] = m
+ }
+ // then improve without ever breaking a constraint: shift each group whole
+ // (members, nested groups and borders together) toward where its members
+ // want to be, as far as its slack allows; then each entry alone, within its
+ // neighbours; then pull the borders tight again
+ const ins: Array<Array<[number, number]>> = Array.from({ length: V }, () => [])
+ outs.forEach((os, v) => { for (const [w, d] of os) ins[w].push([v, d]) })
+ const vch = (v: number) => (v < E0 ? chainOf(v) : gchain[(v - E0) >> 1])
+ const mem: number[][] = groups.map(() => [])
+ for (let v = 0; v < V; v++) for (const g of vch(v)) mem[g].push(v)
+ const want = (v: number) => {
+ const ns = all[v].kind < 3 ? adjUp[v].concat(adjDn[v]) : []
+ return ns.length ? ns.reduce((s, m) => s + val[m], 0) / ns.length : null
+ }
+ const lower = (v: number, skip?: number) => ins[v].reduce((m, [u, d]) => (skip !== undefined && vch(u).includes(skip) ? m : Math.max(m, val[u] + d)), -Infinity)
+ const upper = (v: number, skip?: number) => outs[v].reduce((m, [w, d]) => (skip !== undefined && vch(w).includes(skip) ? m : Math.min(m, val[w] - d)), Infinity)
+ const outer = [...groups.keys()].sort((a, b) => gchain[a].length - gchain[b].length)
+ for (let round = 0; round < 8; round++) {
+ for (const g of outer) {
+ let sum = 0, cnt = 0, lo = -Infinity, hi = Infinity
+ for (const v of mem[g]) {
+ const w = v < E0 ? want(v) : null
+ if (w !== null) { sum += w - val[v]; cnt++ }
+ lo = Math.max(lo, lower(v, g) - val[v])
+ hi = Math.min(hi, upper(v, g) - val[v])
+ }
+ const d = cnt ? Math.max(lo, Math.min(hi, sum / cnt)) : 0
+ if (d) for (const v of mem[g]) val[v] += d
+ }
+ for (let v = 0; v < E0; v++) {
+ const w = want(v)
+ if (w !== null) val[v] = Math.max(lower(v), Math.min(upper(v), w))
+ }
+ for (const g of [...outer].reverse()) {
+ const Lv = E0 + 2 * g
+ val[Lv] = Math.max(lower(Lv), upper(Lv))
+ val[Lv + 1] = Math.min(upper(Lv + 1), lower(Lv + 1))
+ }
+ }
+ for (let n = 0; n < E0; n++) x[n] = val[n]
+ // y: layer thickness, plus room above and below for the groups that start or end there
+ const extT = new Float64Array(G), extB = new Float64Array(G)
+ for (const g of [...groups.keys()].sort((a, b) => gchain[b].length - gchain[a].length)) {
+ extT[g] += padTop(g); extB[g] += padBot(g)
+ const p = gpar[g]
+ if (p >= 0) { if (lo[p] === lo[g]) extT[p] = Math.max(extT[p], extT[g]); if (hi[p] === hi[g]) extB[p] = Math.max(extB[p], extB[g]) }
+ }
+ const gapT = new Float64Array(L), gapB = new Float64Array(L)
+ for (let g = 0; g < G; g++) if (lo[g] <= hi[g]) { gapT[lo[g]] = Math.max(gapT[lo[g]], extT[g]); gapB[hi[g]] = Math.max(gapB[hi[g]], extB[g]) }
+ const ly = new Float64Array(L)
+ let cy = 0
+ for (let l = 0; l < L; l++) {
+ const th = layers[l].reduce((m, n) => Math.max(m, all[n].h), 0)
+ cy += (l ? o.rankGap / 2 + gapB[l - 1] : 0) + gapT[l]
+ ly[l] = cy + th / 2
+ cy += th
+ }
+ cy += L ? gapB[L - 1] : 0
+ // group boxes in TB-space, innermost first
+ const gb: Box[] = groups.map(() => ({ x: 0, y: Infinity, w: 0, h: -Infinity }))
+ for (let n = 0; n < E0; n++) {
+ const g = all[n].g
+ if (g < 0) continue
+ const b = gb[g]
+ b.y = Math.min(b.y, ly[lay[n]] - all[n].h / 2)
+ b.h = Math.max(b.h, ly[lay[n]] + all[n].h / 2)
+ }
+ for (const g of [...groups.keys()].sort((a, b) => gchain[b].length - gchain[a].length)) {
+ const b = gb[g]
+ b.y -= padTop(g); b.h += padBot(g)
+ b.x = val[E0 + 2 * g]
+ b.w = val[E0 + 2 * g + 1] - b.x
+ const p = gpar[g]
+ if (p >= 0) { gb[p].y = Math.min(gb[p].y, b.y); gb[p].h = Math.max(gb[p].h, b.h) }
+ b.h -= b.y
+ }
+ let minX = Infinity, maxX = -Infinity
+ for (let n = 0; n < E0; n++) { minX = Math.min(minX, x[n] - all[n].w / 2); maxX = Math.max(maxX, x[n] + all[n].w / 2) }
+ for (const b of gb) { minX = Math.min(minX, b.x); maxX = Math.max(maxX, b.x + b.w) }
+ if (!E0) minX = maxX = 0
+ const TW = maxX - minX, TH = cy
+ // 6. direction transform, of boxes (TB-space → final)
+ const tr = (b: Box): Box => {
+ const bx = b.x - minX
+ if (dir === 'TB') return { x: bx, y: b.y, w: b.w, h: b.h }
+ if (dir === 'BT') return { x: bx, y: TH - b.y - b.h, w: b.w, h: b.h }
+ if (dir === 'LR') return { x: b.y, y: bx, w: b.h, h: b.w }
+ return { x: TH - b.y - b.h, y: bx, w: b.h, h: b.w }
+ }
+ const at = (n: number): Pt => { const b = tr({ x: x[n], y: ly[lay[n]], w: 0, h: 0 }); return { x: b.x, y: b.y } }
+ const box = items.map((_, n) => tr({ x: x[n] - all[n].w / 2, y: ly[lay[n]] - all[n].h / 2, w: all[n].w, h: all[n].h }))
+ const bends = new Map<number, Pt[]>()
+ const labels = new Map<number, Pt>()
+ for (const [k, chain] of chains) {
+ const k0 = es[k][5]
+ bends.set(k0, chain.map(at))
+ const lab = chain.find((n) => all[n].kind === 2)
+ if (lab !== undefined) labels.set(k0, at(lab))
+ }
+ return { box, groups: gb.map(tr), bends, labels, w: horiz ? TH : TW, h: horiz ? TW : TH, capped }
+}
diff --git a/spaces/src/diagram/mermaid.ts b/spaces/src/diagram/mermaid.ts
new file mode 100644
index 00000000..e93736ef
--- /dev/null
+++ b/spaces/src/diagram/mermaid.ts
@@ -0,0 +1,962 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Mermaid flowcharts ⇄ an editable diagram made of slides' own elements:
+// shape nodes, text labels, and line/path connectors whose ends are anchored
+// with slides' `from`/`to` ConnectorEnd refs (syncConnectors keeps them
+// attached afterwards). Pure and DOM-free. The element types are the kernel
+// diagram engine's (kernel/src/shape.ts ShapeSpec, tips.ts TipKind, geom.ts
+// Box/Pt/ConnectorSide), and connector ends and curves come from the kernel's
+// own geometry (connectorEndpoint, anchorsToPath) — the very calls slides'
+// syncConnectors and curve editor make. No app imports, so slides can import
+// it too: a kernel candidate, beside the connector engine.
+//
+// The official mermaid library is megabytes and nothing may be fetched at
+// runtime (PLATFORM §1), so this is our own reading of the flowchart grammar:
+//
+// mermaidToDiagram(src, {w, h}) → {elements, warnings, ast}
+// diagramToMermaid(elements) → {src, lost}
+//
+// LOSSY BOTH WAYS, and exactly how:
+// · mermaid → elements INVENTS positions (layout.ts). The `layout` sidecar
+// ({id: {x,y,w,h}}, from diagramLayout) makes hand-placed positions win.
+// · elements → mermaid drops positions and sizes (keep the sidecar for
+// those), edge length (`--->`), and whatever `lost` lists per element:
+// rotation, opacity, gradients, shadows, rich text, tips mermaid cannot
+// draw, edge colour, free text, and element types mermaid has no word for.
+// · labels are TEXT. `<br>` is a line break; every other tag stays literal
+// and inert, so a label can never become markup (mermaid would render
+// `<b>`; we show it). Output escapes `<`/`>` so GitHub agrees with us.
+// · slides has no edge labels; an edge label is a text element beside the
+// edge's middle, and it does not follow the edge when nodes move.
+
+import { anchorsToPath, boxCenter, connectorEndpoint, type ConnectorSide } from '../../../kernel/src/geom.ts'
+import type { ShapeSpec } from '../../../kernel/src/shape.ts'
+import type { TipKind } from '../../../kernel/src/tips.ts'
+import { layout, type Box, type Dir, type Pt, type LEdge } from './layout.ts'
+
+// --- the element shapes: the kernel diagram engine's types --------------------
+// A shape node or connector is the kernel's ShapeSpec (what kernel/src/shape.ts
+// renders) plus the element frame. The connector END is still slides' model
+// type (ConnectorEnd lives in slides/src/model.ts — the kernel keeps format
+// types out and exports only its side union), so it is declared here over the
+// kernel's ConnectorSide. Text elements are not in the kernel yet; DText stays a
+// structural copy of slides' TextElement.
+
+export type Tip = TipKind
+export interface ConnectorEnd { el: string; side?: ConnectorSide }
+interface Base { id: string; x: number; y: number; w: number; h: number; rotation: number; opacity: number; groupId?: string; role?: string }
+export interface DShape extends Base, ShapeSpec {
+ type: 'shape'
+ radius: number
+ from?: ConnectorEnd
+ to?: ConnectorEnd
+}
+export interface DText extends Base {
+ type: 'text'
+ html: string
+ fontSize: number
+ fontFamily: string
+ fontWeight: number
+ color: string
+ align: 'left' | 'center' | 'right'
+ valign: 'top' | 'middle' | 'bottom'
+ lineHeight: number
+}
+export type DElement = DShape | DText
+
+// --- the AST ------------------------------------------------------------------
+
+export type NodeShape = 'rect' | 'round' | 'stadium' | 'subroutine' | 'cylinder' | 'circle' | 'dblcircle' | 'diamond' | 'hexagon' | 'lean-r' | 'lean-l' | 'trap-b' | 'trap-t' | 'odd' | 'tri'
+export type Head = 'none' | 'arrow' | 'circle' | 'cross'
+export interface MStyle { fill?: string; stroke?: string; color?: string }
+export interface MNode { id: string; label: string; shape: NodeShape; classes: string[]; style: MStyle; parent: string | null }
+export interface MEdge { from: string; to: string; label: string; start: Head; end: Head; stroke: 'normal' | 'thick' | 'dotted' | 'invisible'; len: number }
+export interface MSubgraph { id: string; label: string; parent: string | null; dir?: Dir; style: MStyle; classes: string[] }
+export interface FlowAST { dir: Dir; nodes: MNode[]; edges: MEdge[]; subgraphs: MSubgraph[] }
+
+/** Caps. Past them the rest is dropped WITH a warning — never a hang. */
+export const LIMITS = { nodes: 500, edges: 2000, depth: 24, labelLines: 12, warnings: 40, dummies: 12000 }
+
+const DIRS: Record<string, Dir> = { TD: 'TB', TB: 'TB', BT: 'BT', LR: 'LR', RL: 'RL' }
+
+// `(((`…`)))` must be tried before `((`…`))` before `(`…`)`: longest opener first.
+// A null closer means "either slash" — `[/ /]` vs `[/ \]` is decided by the end.
+const OPEN: Array<[string, string | null, NodeShape]> = [
+ ['(((', ')))', 'dblcircle'], ['((', '))', 'circle'], ['([', '])', 'stadium'], ['[[', ']]', 'subroutine'],
+ ['[(', ')]', 'cylinder'], ['{{', '}}', 'hexagon'], ['[/', null, 'lean-r'], ['[\\', null, 'lean-l'],
+ ['{', '}', 'diamond'], ['(', ')', 'round'], ['[', ']', 'rect'], ['>', ']', 'odd'],
+]
+// mermaid v11 `A@{ shape: … }` names → ours
+const V11: Record<string, NodeShape> = { __proto__: null as never,
+ rounded: 'round', subproc: 'subroutine', 'fr-rect': 'subroutine', cyl: 'cylinder', database: 'cylinder', circ: 'circle', 'dbl-circ': 'dblcircle',
+ diam: 'diamond', decision: 'diamond', hex: 'hexagon', triangle: 'tri', proc: 'rect', process: 'rect',
+}
+// Named colours are accepted by SHAPE — letters only — rather than from a
+// 148-name list: a name can carry nothing but a colour, and a name the
+// browser does not know paints as the attribute's default, not as anything else.
+const NAMED = /^[a-z]{3,24}$/i
+const NUM = String.raw`\s*-?[\d.]+(?:%|deg)?\s*`
+const FN = new RegExp(`^(rgba?|hsla?)\\(${NUM}[,\\s]${NUM}[,\\s]${NUM}(?:[,/]${NUM})?\\)$`, 'i')
+
+/** A colour we are willing to write into an element, or null. */
+export function validColor(v: string): string | null {
+ v = v.trim().replace(/\s*!important$/i, '')
+ return /^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(v) || FN.test(v) || NAMED.test(v) ? v : null
+}
+
+const ENT: Record<string, string> = { __proto__: null as never, quot: '"', amp: '&', lt: '<', gt: '>', apos: "'", nbsp: ' ', semi: ';', colon: ':', hash: '#', num: '#' }
+const cp = (n: number, m: string) => (n > 0 && n < 0x110000 ? String.fromCodePoint(n) : m)
+/** Mermaid label text → plain text. `<br>` is the only tag with a meaning. */
+function decode(s: string): string {
+ s = s.trim()
+ if (s.length > 1 && s[0] === '"' && s.endsWith('"')) s = s.slice(1, -1)
+ if (s.length > 1 && s[0] === '`' && s.endsWith('`')) s = s.slice(1, -1)
+ return s
+ .replace(/\bfa[bklrs]?:fa-[\w-]+\s?/g, '')
+ .replace(/<br\s*\/?>/gi, '\n')
+ .replace(/#(\w+);/g, (m, n) => (/^\d+$/.test(n) ? cp(+n, m) : ENT[n] ?? m))
+ .replace(/&(#x[\da-f]+|#\d+|\w+);/gi, (m, n: string) =>
+ n[0] === '#' ? cp(n[1] === 'x' || n[1] === 'X' ? parseInt(n.slice(2), 16) : +n.slice(1), m) : ENT[n.toLowerCase()] ?? m)
+}
+
+// --- the parser ---------------------------------------------------------------
+
+/** Parse a Mermaid flowchart. Never throws: what it cannot read is a warning. */
+export function parseMermaid(src: string): { ast: FlowAST; warnings: string[] } {
+ const warnings: string[] = []
+ let dropped = 0
+ const warn = (line: number, msg: string) => {
+ const w = line ? `line ${line}: ${msg}` : msg
+ if (warnings.length < LIMITS.warnings) { if (!warnings.includes(w)) warnings.push(w) } else dropped++
+ }
+ const no = (line: number, what: string) => warn(line, what + ' unsupported')
+ const ast: FlowAST = { dir: 'TB', nodes: [], edges: [], subgraphs: [] }
+ const nodes = new Map<string, MNode>()
+ const subs = new Map<string, MSubgraph>()
+ const classDefs = new Map<string, MStyle>()
+ const stack: MSubgraph[] = []
+ let created: string[] = []
+ let header = false, skipUntil: RegExp | null = null, overDepth = 0
+
+ const node = (id: string): MNode | null => {
+ let n = nodes.get(id)
+ if (!n) {
+ if (nodes.size >= LIMITS.nodes) { warn(0, `over ${LIMITS.nodes} nodes, rest dropped`); return null }
+ n = { id, label: id, shape: 'rect', classes: [], style: {}, parent: null }
+ nodes.set(id, n)
+ created.push(id)
+ }
+ // a node belongs to the first subgraph that mentions it
+ if (!n.parent && stack.length) n.parent = stack[stack.length - 1].id
+ return n
+ }
+ const props = (line: number, s: string): MStyle => {
+ const st: MStyle = {}
+ for (const part of s.split(/[,;](?![^(]*\))/)) {
+ const m = /^\s*([\w-]+)\s*:\s*(.*?)\s*$/.exec(part)
+ if (!m) continue
+ const k = m[1].toLowerCase()
+ if (k !== 'fill' && k !== 'stroke' && k !== 'color') { no(0, `style ${k}`); continue }
+ const c = validColor(m[2])
+ if (c) st[k] = c
+ else warn(line, `bad colour ${m[2].slice(0, 40)}`)
+ }
+ return st
+ }
+
+ // statements: newlines, and `;` outside quotes and brackets; `%%` comments
+ const stmts: Array<[number, string]> = []
+ {
+ let cur = '', q = false, depth = 0, line = 1, startLine = 1
+ const flush = () => { if (cur.trim()) stmts.push([startLine, cur.trim()]); cur = '' }
+ for (let i = 0; i < src.length; i++) {
+ const c = src[i]
+ if (c === '\n') {
+ line++
+ if (q) { cur += c; continue }
+ depth = 0; flush(); startLine = line; continue
+ }
+ if (!q && c === '%' && src[i + 1] === '%') {
+ if (src[i + 2] === '{') no(line, '%%{directive}%%')
+ while (i < src.length && src[i + 1] !== '\n') i++
+ continue
+ }
+ if (c === '"') q = !q && src.indexOf('"', i + 1) > 0
+ else if (!q) {
+ if ('[({'.includes(c)) depth++
+ else if (')]}'.includes(c)) depth = Math.max(0, depth - 1)
+ else if (c === ';' && !depth) { flush(); continue }
+ }
+ cur += c
+ }
+ flush()
+ }
+
+ let front = false
+ for (const [ln, s] of stmts) {
+ if (skipUntil) { if (skipUntil.test(s)) skipUntil = null; continue }
+ if (!header) {
+ if (s === '---') { front = !front; continue }
+ if (front) { if (/^title\s*:/.test(s)) no(ln, 'title'); continue }
+ const h = /^(flowchart(?:-elk)?|graph)\b\s*(\w+)?\s*$/i.exec(s)
+ if (!h) {
+ no(ln, `diagram "${s.split(/\s/)[0].slice(0, 30)}" (only flowchart/graph)`)
+ return { ast, warnings }
+ }
+ header = true
+ if (h[2]) {
+ const d = DIRS[h[2].toUpperCase()]
+ if (d) ast.dir = d
+ else warn(ln, `bad direction ${h[2]}`)
+ }
+ continue
+ }
+ const kw = /^(\w+)\b\s*(.*)$/.exec(s)
+ const k = kw?.[1], rest = kw?.[2] ?? ''
+ if (k === 'subgraph') {
+ if (stack.length >= LIMITS.depth) { overDepth++; warn(ln, `subgraphs deeper than ${LIMITS.depth} flattened`); continue }
+ let id: string, label: string
+ const m = /^([^\s[\]"]+)\s*\[(.*)\]\s*$/.exec(rest)
+ if (m) { id = m[1]; label = decode(m[2]) }
+ else { label = decode(rest); id = /^[^\s"]+$/.test(rest) ? rest : label || `subgraph${subs.size + 1}` }
+ if (subs.has(id)) { warn(ln, `duplicate subgraph ${id}`); id = `${id}_${subs.size + 1}` }
+ const sg: MSubgraph = { id, label, parent: stack.length ? stack[stack.length - 1].id : null, style: {}, classes: [] }
+ subs.set(id, sg)
+ ast.subgraphs.push(sg)
+ stack.push(sg)
+ continue
+ }
+ if (k === 'end' && !rest) { if (overDepth) overDepth--; else if (stack.pop() === undefined) warn(ln, 'stray end'); continue }
+ if (k === 'direction') {
+ const d = DIRS[rest.toUpperCase()]
+ if (!d) warn(ln, `bad direction ${rest}`)
+ else if (stack.length) stack[stack.length - 1].dir = d
+ else ast.dir = d
+ continue
+ }
+ if (k === 'classDef') {
+ const m = /^(\S+)\s+(.*)$/.exec(rest)
+ if (m) { const st = props(ln, m[2]); for (const c of m[1].split(',')) classDefs.set(c, st) }
+ continue
+ }
+ if (k === 'class') {
+ const m = /^(\S+)\s+([\w-]+)\s*$/.exec(rest)
+ if (m) for (const id of m[1].split(',')) (subs.get(id) ?? node(id))?.classes.push(m[2])
+ continue
+ }
+ if (k === 'style') {
+ const m = /^(\S+)\s+(.*)$/.exec(rest)
+ if (m) { const t = subs.get(m[1]) ?? node(m[1]); if (t) Object.assign(t.style, props(ln, m[2])) }
+ continue
+ }
+ if (k === 'linkStyle') { no(ln, k); continue }
+ if (k === 'click' || k === 'href' || k === 'call') { no(0, 'click'); continue }
+ if (k === 'accTitle' || k === 'accDescr') {
+ if (/^\s*\{/.test(rest) && !rest.includes('}')) skipUntil = /\}/
+ no(ln, k)
+ continue
+ }
+ // a statement lands whole or not at all
+ const e0 = ast.edges.length
+ created = []
+ if (!chain(ln, s)) {
+ ast.edges.length = e0
+ for (const id of created) nodes.delete(id)
+ warn(ln, `could not read: ${s.slice(0, 60)}`)
+ }
+ }
+ if (!header) warn(0, 'empty')
+ if (stack.length) warn(0, 'unclosed subgraph')
+ if (dropped) warnings.push(`+${dropped} more`)
+
+ // an id that names a subgraph is the subgraph (edges may point at it)
+ for (const id of subs.keys()) nodes.delete(id)
+ for (const n of nodes.values()) {
+ if (n.parent && !subs.has(n.parent)) n.parent = null
+ n.style = merge(n.classes, n.style)
+ ast.nodes.push(n)
+ }
+ for (const sg of ast.subgraphs) sg.style = merge(sg.classes, sg.style)
+ ast.edges = ast.edges.filter((e) => (nodes.has(e.from) || subs.has(e.from)) && (nodes.has(e.to) || subs.has(e.to)))
+ return { ast, warnings }
+
+ function merge(classes: string[], own: MStyle): MStyle {
+ const out: MStyle = { ...classDefs.get('default') }
+ for (const c of classes) {
+ const d = classDefs.get(c)
+ if (d) Object.assign(out, d)
+ else warn(0, `undefined class ${c}`)
+ }
+ return Object.assign(out, own)
+ }
+
+ // A --> B & C -- text --> D ...
+ function chain(ln: number, s: string): boolean {
+ let i = 0
+ const ws = () => { while (i < s.length && /\s/.test(s[i])) i++ }
+ const group = (): string[] | null => {
+ const ids: string[] = []
+ for (;;) {
+ ws()
+ const id = one()
+ if (id === null) return null
+ ids.push(id)
+ ws()
+ if (s[i] !== '&') return ids
+ i++
+ }
+ }
+ const one = (): string | null => {
+ const st = i
+ while (i < s.length) {
+ const c = s[i], n = s[i + 1]
+ if (/[\s[\](){}<>|&;:"',@]/.test(c)) break
+ if ((c === '-' && (n === '-' || n === '.' || n === '>')) || (c === '=' && n === '=') || (c === '~' && n === '~') || (c === '.' && n === '-')) break
+ i++
+ }
+ if (i === st) return null
+ const id = s.slice(st, i)
+ const n = node(id)
+ shape(n)
+ const cls = /^:::([\w-]+)/.exec(s.slice(i))
+ if (cls) { i += cls[0].length; n?.classes.push(cls[1]) }
+ return id
+ }
+ const shape = (n: MNode | null) => {
+ if (s.startsWith('@{', i)) {
+ const end = s.indexOf('}', i)
+ if (end < 0) { i = s.length; return }
+ const body = s.slice(i + 2, end)
+ i = end + 1
+ let sh: NodeShape = 'rect', lab: string | null = null
+ for (const m of body.matchAll(/(\w+)\s*:\s*("[^"]*"|[^,]+)/g)) {
+ const v = m[2].trim()
+ if (m[1] === 'shape') {
+ const name = decode(v), got = V11[name] ?? (/^(rect|stadium|subroutine|cylinder|circle|diamond|hexagon|lean-[rl]|trap-[bt]|odd|tri)$/.test(name) ? name as NodeShape : null)
+ if (got) sh = got
+ else no(ln, `shape ${name}`)
+ } else if (m[1] === 'label') lab = decode(v)
+ }
+ if (n) { n.shape = sh; if (lab !== null) n.label = lab }
+ return
+ }
+ for (const [o, c, sh] of OPEN) {
+ if (!s.startsWith(o, i)) continue
+ let j = i + o.length
+ const quoted = s[j] === '"'
+ let text: string, endAt: number, kind = sh
+ const closers = c ? [c] : ['/]', '\\]']
+ const from = quoted ? s.indexOf('"', j + 1) + 1 : j
+ if (quoted && from === 0) return
+ let best = -1, which = ''
+ for (const cl of closers) {
+ let at = s.indexOf(cl, from)
+ if (!quoted && cl.length === 1) {
+ // an unquoted label may hold balanced brackets: `[messages[] in]`
+ const op = cl === ']' ? '[' : cl === ')' ? '(' : '{'
+ for (let d = 0, x = from; x < s.length; x++) {
+ if (s[x] === op) d++
+ else if (s[x] === cl && !d--) { at = x; break }
+ }
+ }
+ if (at >= 0 && (best < 0 || at < best)) { best = at; which = cl }
+ }
+ if (best < 0) return
+ text = s.slice(j, best)
+ endAt = best + which.length
+ if (!c) kind = sh === 'lean-r' ? (which === '/]' ? 'lean-r' : 'trap-b') : which === '\\]' ? 'lean-l' : 'trap-t'
+ i = endAt
+ if (n) { n.shape = kind; n.label = decode(text) }
+ return
+ }
+ }
+ const link = (): Omit<MEdge, 'from' | 'to'> | null => {
+ ws()
+ const e = /^[\w-]+@(?=[-=.~<ox])/.exec(s.slice(i))
+ if (e) { i += e[0].length; no(ln, 'edge id') }
+ const rest = s.slice(i)
+ const heads: Record<string, Head> = { '>': 'arrow', '<': 'arrow', o: 'circle', x: 'cross' }
+ // a complete link: `-->`, `---`, `-.->`, `==>`, `~~~`, `<-->`, `--o`, `--x` …
+ const m = /^([<ox](?=[-=.]))?(-{2,}|={2,}|-\.+-|~{3,})(>|[ox](?![\w-]))?/.exec(rest)
+ if (m && (m[3] || !/^(--|==)$/.test(m[2]))) {
+ const body = m[2]
+ i += m[0].length
+ const stroke = body[0] === '~' ? 'invisible' : body[0] === '=' ? 'thick' : body[1] === '.' ? 'dotted' : 'normal'
+ let label = ''
+ ws()
+ const p = /^\|("[^"]*"|[^|]*)\|/.exec(s.slice(i))
+ if (p) { i += p[0].length; label = decode(p[1]) }
+ return { label, start: m[1] ? heads[m[1]] : 'none', end: m[3] ? heads[m[3]] : 'none', stroke, len: Math.max(1, (stroke !== 'normal' && stroke !== 'thick') || !m[3] ? body.length - 2 : body.length - 1) }
+ }
+ // a label inside the link: `A -- text --> B`, `A ==text==> B`, `A -. text .-> B`
+ const open = /^([<ox](?=[-=]))?(--|==|-\.)/.exec(rest)
+ if (!open) return null
+ const dot = open[2] === '-.', ch = open[2][0] === '=' ? '=' : '-'
+ const close = dot ? /(\.+)-(>|[ox](?![\w-]))?/g : ch === '=' ? /(=+)(>|[ox](?![\w-]))?/g : /(-+)(>|[ox](?![\w-]))?/g
+ close.lastIndex = open[0].length
+ for (let c; (c = close.exec(rest));) {
+ const n = c[1].length
+ if (!dot && (n < 2 || (!c[2] && n < 3))) continue
+ const text = rest.slice(open[0].length, c.index)
+ if (!text.trim()) return null
+ i += c.index + c[0].length
+ return {
+ label: decode(text), start: open[1] ? heads[open[1]] : 'none', end: c[2] ? heads[c[2]] : 'none',
+ stroke: dot ? 'dotted' : ch === '=' ? 'thick' : 'normal', len: Math.max(1, dot ? n : c[2] ? n - 1 : n - 2),
+ }
+ }
+ return null
+ }
+ let prev = group()
+ if (!prev) return false
+ for (;;) {
+ ws()
+ if (i >= s.length) return true
+ const l = link()
+ if (!l) return false
+ const next = group()
+ if (!next) return false
+ for (const a of prev) for (const b of next) {
+ if (ast.edges.length >= LIMITS.edges) { warn(0, `over ${LIMITS.edges} edges, rest dropped`); break }
+ ast.edges.push({ from: a, to: b, ...l })
+ }
+ if (l.stroke === 'invisible') warn(ln, '~~~ is layout-only')
+ prev = next
+ }
+ }
+}
+
+// --- ids ----------------------------------------------------------------------
+
+const RESERVED = /^(end|graph|flowchart|subgraph|style|class|classDef|click|linkStyle|direction|default|call|href)$/
+/** A mermaid id → a safe element id (and a safe mermaid id back): [A-Za-z0-9_-],
+ * never a keyword, never an Object.prototype name like `__proto__`. */
+export function makeIds() {
+ const used = new Set<string>()
+ return (raw: string): string => {
+ let id = raw.replace(/[^\w-]/g, '_').slice(0, 64) || 'n'
+ if (RESERVED.test(id) || id in Object.prototype) id += '_'
+ let out = id
+ for (let k = 2; used.has(out); k++) out = `${id}_${k}`
+ used.add(out)
+ return out
+ }
+}
+
+// --- geometry -----------------------------------------------------------------
+
+export interface Palette { fill: string; stroke: string; ink: string; edge: string; groupFill: string; groupStroke: string }
+export const PALETTE: Palette = { fill: '#EEF2F8', stroke: '#5B6B82', ink: '#1E2A3A', edge: '#5B6B82', groupFill: 'rgba(91,107,130,0.06)', groupStroke: '#AEB8C6' }
+export const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
+const F = 16, LH = 1.25, WRAP = 200, PADX = 16, PADY = 10
+
+/** Width of `text` at `fontSize`, without a DOM: per-glyph class widths. */
+export function estimateWidth(text: string, fontSize: number): number {
+ let w = 0
+ for (const ch of text) {
+ const c = ch.codePointAt(0)!
+ w += c >= 0x1100 ? 1 : /[iljtf.,:;'|!()[\] ]/.test(ch) ? 0.3 : /[mwMW@%]/.test(ch) ? 0.86 : /[A-Z0-9#&]/.test(ch) ? 0.66 : 0.55
+ }
+ return w * fontSize
+}
+
+const r2 = (v: number) => Math.round(v * 100) / 100
+// canonical path templates in a 100×100 box; reverse recognises them by string
+const PATHS: Partial<Record<NodeShape, string>> = {
+ diamond: 'M50 0L100 50L50 100L0 50Z',
+ hexagon: 'M15 0L85 0L100 50L85 100L15 100L0 50Z',
+ 'lean-r': 'M15 0L100 0L85 100L0 100Z',
+ 'lean-l': 'M0 0L85 0L100 100L15 100Z',
+ 'trap-b': 'M15 0L85 0L100 100L0 100Z',
+ 'trap-t': 'M0 0L100 0L85 100L15 100Z',
+ odd: 'M0 0L100 0L100 100L0 100L15 50Z',
+ subroutine: 'M0 0L100 0L100 100L0 100Z M8 0L8 100M92 0L92 100',
+ cylinder: 'M0 10C0 -3 100 -3 100 10L100 90C100 103 0 103 0 90Z M0 10C0 23 100 23 100 10',
+ // two circles (r 50 and 42) as four cubics each
+ dblcircle: 'M50 0C77.62 0 100 22.38 100 50C100 77.62 77.62 100 50 100C22.38 100 0 77.62 0 50C0 22.38 22.38 0 50 0Z M50 8C73.2 8 92 26.8 92 50C92 73.2 73.2 92 50 92C26.8 92 8 73.2 8 50C8 26.8 26.8 8 50 8Z',
+}
+// how much of the node's width the label may use, and extra height
+const INNER: Partial<Record<NodeShape, number>> = { diamond: 0.75, hexagon: 0.7, 'lean-r': 0.7, 'lean-l': 0.7, 'trap-b': 0.7, 'trap-t': 0.7, odd: 0.85, subroutine: 0.84, tri: 0.5, circle: 0.72, dblcircle: 0.62 }
+
+const center = boxCenter
+/** Where syncConnectors puts a connector end on box b, toward t (kernel geom:
+ * connectorEndpoint — today the bounding-box border, for every node kind). */
+function border(b: Box, t: Pt, side: ConnectorSide = 'auto'): Pt {
+ const p = connectorEndpoint(b, side, t)
+ return { x: r2(p.x), y: r2(p.y) }
+}
+/** A curve through pts, relative to (ox, oy), written the way slides'
+ * setPathAnchors writes one: anchors rounded to 0.01 FIRST, then the kernel's
+ * anchorsToPath (Catmull-Rom → cubic). So the bytes are the curve editor's own. */
+function smooth(pts: Pt[], ox: number, oy: number): string {
+ return anchorsToPath(pts.map((p) => ({ x: r2(p.x - ox), y: r2(p.y - oy) })))
+}
+const escHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/\n/g, '<br>')
+
+// --- mermaid → elements -------------------------------------------------------
+
+export interface MermaidOpts {
+ w: number
+ h: number
+ /** hand-placed positions by element id; they win, new nodes go around them */
+ layout?: Record<string, Box>
+ measure?: (text: string, fontSize: number) => number
+ palette?: Partial<Palette>
+ fontFamily?: string
+}
+
+export function mermaidToDiagram(src: string, opts: MermaidOpts): { elements: DElement[]; warnings: string[]; ast: FlowAST } {
+ const { ast, warnings } = parseMermaid(String(src ?? ''))
+ const P = { ...PALETTE, ...opts.palette }
+ const measure = opts.measure ?? estimateWidth
+ const font = opts.fontFamily ?? FONT
+ const idOf = makeIds()
+ const eid = new Map<string, string>()
+ for (const n of ast.nodes) eid.set(n.id, idOf(n.id))
+ for (const g of ast.subgraphs) eid.set(g.id, idOf(g.id))
+ let clipped = 0
+
+ // wrap a label to WRAP px and measure it; very long labels size to LIMITS.labelLines
+ const text = (label: string, fs: number) => {
+ const lines: string[] = []
+ let w = 0
+ for (const para of label.split('\n')) {
+ let cur = '', cw = 0
+ for (const word of para.split(/(?<=\s)/)) {
+ const ww = measure(word, fs)
+ if (cur && cw + ww > WRAP * fs / F) { lines.push(cur); w = Math.max(w, cw); cur = ''; cw = 0 }
+ if (ww > WRAP * fs / F) {
+ // hard-break a word longer than the wrap width
+ for (const ch of word) {
+ const c = measure(ch, fs)
+ if (cw + c > WRAP * fs / F && cur) { lines.push(cur); w = Math.max(w, cw); cur = ''; cw = 0 }
+ cur += ch; cw += c
+ }
+ } else { cur += word; cw += ww }
+ if (lines.length > LIMITS.labelLines) break
+ }
+ lines.push(cur); w = Math.max(w, cw)
+ if (lines.length > LIMITS.labelLines) break
+ }
+ if (lines.length > LIMITS.labelLines) clipped++
+ const n = Math.min(lines.length, LIMITS.labelLines)
+ return { w: Math.ceil(w), h: Math.ceil(n * fs * LH) }
+ }
+
+ const size = new Map<string, { w: number; h: number; tw: number }>()
+ for (const n of ast.nodes) {
+ const t = text(n.label, F)
+ let w = t.w + 2 * PADX, h = t.h + 2 * PADY
+ const s = n.shape
+ if (s === 'diamond') w = h = t.w + t.h + 2 * PADX
+ else if (s === 'tri') { w *= 2; h *= 2 }
+ else if (s === 'circle' || s === 'dblcircle') w = h = Math.hypot(t.w, t.h) + 2 * PADY + (s === 'dblcircle' ? 12 : 0)
+ else if (INNER[s]) w = w / INNER[s]!
+ if (s === 'stadium') w += h / 2
+ if (s === 'cylinder') h += 16
+ size.set(n.id, { w: r2(Math.max(w, 40)), h: r2(h), tw: t.w })
+ }
+ const horiz = ast.dir === 'LR' || ast.dir === 'RL'
+ const EF = F * 0.875
+ const elab = ast.edges.map((e) => (e.label ? text(e.label, EF) : null))
+ const lnodes = ast.nodes.map((n) => ({ id: n.id, ...size.get(n.id)!, parent: n.parent }))
+ const lclusters = ast.subgraphs.map((g) => ({ id: g.id, parent: g.parent, dir: g.dir, top: Math.ceil(F * 0.875 * LH) + 8, minW: text(g.label, F * 0.875).w + 8 }))
+ const ledges: LEdge[] = ast.edges.map((e, i) => {
+ const t = elab[i]
+ // a label sits BESIDE its edge: the layout reserves room on both sides of the line
+ const lw = t ? (horiz ? t.w + 8 : 2 * (t.w + 8) + 12) : 0
+ const lh = t ? (horiz ? 2 * (t.h + 4) + 8 : t.h + 4) : 0
+ return { from: e.from, to: e.to, minlen: e.len, lw, lh }
+ })
+ const L = layout(lnodes, lclusters, ledges, ast.dir, { nodeGap: 40, rankGap: 56, pad: 16, maxDummies: LIMITS.dummies })
+ for (const id of L.ignoredDir) warnings.push(`direction in subgraph ${id} ignored: its members link outside it (as in mermaid)`)
+ if (L.capped) warnings.push('the graph is too large to route every long edge; some are drawn straight')
+ if (clipped) warnings.push(`${clipped} label(s) longer than ${LIMITS.labelLines} lines: the text is kept but the shape is sized for ${LIMITS.labelLines}`)
+
+ // fit into w×h: scale down (never up) and centre
+ const M = 16
+ const s = Math.min(1, (opts.w - 2 * M) / (L.w || 1), (opts.h - 2 * M) / (L.h || 1))
+ const k = s > 0 && isFinite(s) ? s : 1
+ if (k < 0.5) warnings.push(`scaled to ${Math.round(k * 100)}% to fit ${opts.w}×${opts.h}`)
+ const ox = (opts.w - L.w * k) / 2, oy = (opts.h - L.h * k) / 2
+ const tp = (p: Pt): Pt => ({ x: r2(ox + p.x * k), y: r2(oy + p.y * k) })
+ const tb = (b: Box): Box => ({ ...tp(b), w: r2(b.w * k), h: r2(b.h * k) })
+ const boxes = new Map<string, Box>()
+ for (const [id, b] of L.nodes) boxes.set(id, tb(b))
+ let bends = L.edges.map((e) => e.bends.map(tp))
+ let labAt = L.edges.map((e) => (e.label ? tp(e.label) : undefined))
+
+ // the layout sidecar: named boxes win; the rest shift to sit around them
+ const side = opts.layout
+ const pinned = new Set<string>()
+ if (side && typeof side === 'object') {
+ const dx: number[] = [], dy: number[] = []
+ for (const n of ast.nodes) {
+ const id = eid.get(n.id)!
+ const b = Object.hasOwn(side, id) ? side[id] : null
+ if (!b || ![b.x, b.y, b.w, b.h].every((v) => typeof v === 'number' && isFinite(v)) || b.w <= 0 || b.h <= 0) continue
+ const a = center(boxes.get(n.id)!), c = center(b)
+ dx.push(c.x - a.x); dy.push(c.y - a.y)
+ boxes.set(n.id, { x: b.x, y: b.y, w: b.w, h: b.h })
+ pinned.add(n.id)
+ }
+ if (pinned.size) {
+ const med = (a: number[]) => a.sort((p, q) => p - q)[a.length >> 1]
+ const tx = med(dx), ty = med(dy)
+ const placed = [...pinned].map((id) => boxes.get(id)!)
+ const hit = (a: Box, b: Box) => a.x < b.x + b.w + 8 && b.x < a.x + a.w + 8 && a.y < b.y + b.h + 8 && b.y < a.y + a.h + 8
+ for (const n of ast.nodes) {
+ if (pinned.has(n.id)) continue
+ const b = boxes.get(n.id)!
+ b.x = r2(b.x + tx); b.y = r2(b.y + ty)
+ for (let guard = 0; guard <= placed.length; guard++) {
+ const o = placed.find((p) => hit(b, p))
+ if (!o) break
+ if (horiz) b.y = r2(o.y + o.h + 16)
+ else b.x = r2(o.x + o.w + 16)
+ }
+ placed.push(b)
+ }
+ bends = bends.map((bs, i) => (pinned.has(ast.edges[i].from) || pinned.has(ast.edges[i].to) ? [] : bs.map((p) => ({ x: r2(p.x + tx), y: r2(p.y + ty) }))))
+ labAt = labAt.map((p, i) => (p && bends[i].length ? { x: r2(p.x + tx), y: r2(p.y + ty) } : undefined))
+ }
+ }
+ // subgraph boxes: the layout's, or (with a sidecar) the hull of their members
+ const depth = (g: MSubgraph) => { let d = 0; for (let p = g.parent; p; p = ast.subgraphs.find((x) => x.id === p)?.parent ?? null) d++; return d }
+ const order = [...ast.subgraphs].sort((a, b) => depth(b) - depth(a))
+ for (const g of order) {
+ let b = tb(L.clusters.get(g.id)!)
+ if (pinned.size) {
+ const kids = [...ast.nodes.filter((n) => n.parent === g.id).map((n) => n.id), ...ast.subgraphs.filter((x) => x.parent === g.id).map((x) => x.id)].map((id) => boxes.get(id)!).filter(Boolean)
+ if (kids.length) {
+ const pad = 16 * k, top = lclusters[0].top * k
+ const x0 = Math.min(...kids.map((q) => q.x)) - pad, y0 = Math.min(...kids.map((q) => q.y)) - pad - top
+ b = { x: r2(x0), y: r2(y0), w: r2(Math.max(...kids.map((q) => q.x + q.w)) + pad - x0), h: r2(Math.max(...kids.map((q) => q.y + q.h)) + pad - y0) }
+ }
+ }
+ boxes.set(g.id, b)
+ }
+
+ const out: DElement[] = []
+ const base = (id: string, b: Box, extra: object = {}) => ({ id, x: r2(b.x), y: r2(b.y), w: r2(b.w), h: r2(b.h), rotation: 0, opacity: 1, ...extra })
+ const label = (id: string, b: Box, str: string, fs: number, color: string, extra: Partial<DText> = {}): DText => ({
+ ...base(idOf(id + '-label'), b), type: 'text', html: escHtml(str), fontSize: r2(fs * k), fontFamily: font, fontWeight: 400,
+ color, align: 'center', valign: 'middle', lineHeight: LH, ...extra,
+ })
+ for (const g of [...ast.subgraphs].sort((a, b) => depth(a) - depth(b))) {
+ const b = boxes.get(g.id)!, id = eid.get(g.id)!
+ out.push({ ...base(id, b), type: 'shape', shape: 'rect', fill: g.style.fill ?? P.groupFill, stroke: g.style.stroke ?? P.groupStroke, strokeWidth: 1, radius: r2(8 * k), role: 'subgraph', groupId: id })
+ out.push(label(id, { x: b.x + 8 * k, y: b.y + 4 * k, w: b.w - 16 * k, h: lclusters[0].top * k - 4 * k }, g.label, F * 0.875, g.style.color ?? P.ink, { align: 'left', valign: 'top', fontWeight: 600, groupId: id }))
+ }
+ const edgeLabels: DText[] = []
+ const polys: Pt[][] = []
+ const jobs: Array<[string, number, Pt[], number]> = []
+ ast.edges.forEach((e, i) => {
+ if (e.stroke === 'invisible') return
+ const A = boxes.get(e.from)!, B = boxes.get(e.to)!
+ const a0 = eid.get(e.from)!, b0 = eid.get(e.to)!
+ const id = idOf(`${a0}-${b0}`)
+ const sw = e.stroke === 'thick' ? 3.5 : 2
+ const tip = (h: Head): Tip | undefined => (h === 'arrow' ? 'arrow' : h === 'circle' ? 'circle-open' : h === 'cross' ? 'bar' : undefined)
+ const deco: Partial<DShape> = { lineStart: tip(e.start), lineEnd: tip(e.end), strokeStyle: e.stroke === 'dotted' ? 'dashed' : undefined }
+ for (const key of ['lineStart', 'lineEnd', 'strokeStyle'] as const) if (deco[key] === undefined) delete deco[key]
+ let pts: Pt[]
+ let el: DShape
+ if (e.from === e.to) {
+ // self-loop: pinned sides, since 'auto' would collapse both ends to the centre
+ const c = center(A)
+ pts = [{ x: A.x + A.w, y: c.y }, { x: A.x + A.w + 24, y: A.y - 24 }, { x: c.x, y: A.y }]
+ const x0 = Math.min(...pts.map((p) => p.x)), y0 = Math.min(...pts.map((p) => p.y))
+ const w = Math.max(...pts.map((p) => p.x)) - x0, h = Math.max(...pts.map((p) => p.y)) - y0
+ el = { ...base(id, { x: x0, y: y0, w, h }), type: 'shape', shape: 'path', fill: 'none', stroke: P.edge, strokeWidth: sw, radius: 0, ...deco,
+ d: `M ${r2(pts[0].x - x0)} ${r2(pts[0].y - y0)} C ${r2(pts[1].x - x0)} ${r2(pts[0].y - y0)} ${r2(pts[1].x - x0)} ${r2(pts[1].y - y0)} ${r2(pts[2].x - x0)} ${r2(pts[1].y - y0)} C ${r2(pts[2].x - x0)} ${r2(pts[1].y - y0)} ${r2(pts[2].x - x0)} ${r2(pts[2].y - y0)} ${r2(pts[2].x - x0)} ${r2(pts[2].y - y0)}`,
+ pathBox: [0, 0, r2(w), r2(h)], from: { el: a0, side: 'right' }, to: { el: b0, side: 'top' } }
+ } else {
+ // ends exactly where slides' syncConnectors would put them, so nothing jumps on the first edit
+ const a = border(A, center(B)), b = border(B, center(A))
+ const bs = bends[i]
+ const len = Math.hypot(b.x - a.x, b.y - a.y) || 1
+ const off = (p: Pt) => Math.abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / len
+ if (!bs.length || bs.every((p) => off(p) < 2)) {
+ const h = sw + 2
+ el = { ...base(id, { x: (a.x + b.x) / 2 - len / 2, y: (a.y + b.y) / 2 - h / 2, w: len, h }), type: 'shape', shape: 'line', fill: P.edge, stroke: 'transparent', strokeWidth: sw, radius: 0, ...deco,
+ rotation: r2((Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI), from: { el: a0, side: 'auto' }, to: { el: b0, side: 'auto' } }
+ pts = [a, b]
+ } else {
+ pts = [a, ...bs, b]
+ const x0 = Math.min(...pts.map((p) => p.x)), y0 = Math.min(...pts.map((p) => p.y))
+ const w = Math.max(Math.max(...pts.map((p) => p.x)) - x0, 1), h = Math.max(Math.max(...pts.map((p) => p.y)) - y0, 1)
+ el = { ...base(id, { x: x0, y: y0, w, h }), type: 'shape', shape: 'path', fill: 'none', stroke: P.edge, strokeWidth: sw, radius: 0, ...deco,
+ d: smooth(pts, x0, y0), pathBox: [0, 0, r2(w), r2(h)], from: { el: a0, side: 'auto' }, to: { el: b0, side: 'auto' } }
+ }
+ }
+ out.push(el)
+ polys.push(pts)
+ if (elab[i]) jobs.push([id, i, pts, polys.length - 1])
+ })
+ // Edge labels: the layout's spot first (beside the edge's middle, where it
+ // reserved room), else the other side, else further along the edge — the
+ // first spot that crosses no other edge and covers no node or label wins.
+ // With no clear spot the layout's stands.
+ const seg = (a: Pt, b: Pt, r: Box) => {
+ // Liang–Barsky: does segment ab enter box r?
+ let t0 = 0, t1 = 1
+ const dx = b.x - a.x, dy = b.y - a.y
+ for (const [p, q] of [[-dx, a.x - r.x], [dx, r.x + r.w - a.x], [-dy, a.y - r.y], [dy, r.y + r.h - a.y]]) {
+ if (!p) { if (q < 0) return false; continue }
+ const t = q / p
+ if (p < 0) { if (t > t1) return false; if (t > t0) t0 = t } else { if (t < t0) return false; if (t < t1) t1 = t }
+ }
+ return t0 < t1
+ }
+ const over = (a: Box, b: Box) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
+ const along = (pts: Pt[], f: number): Pt => {
+ let total = 0
+ for (let j = 1; j < pts.length; j++) total += Math.hypot(pts[j].x - pts[j - 1].x, pts[j].y - pts[j - 1].y)
+ for (let j = 1, acc = 0; j < pts.length; j++) {
+ const d = Math.hypot(pts[j].x - pts[j - 1].x, pts[j].y - pts[j - 1].y)
+ if (acc + d >= total * f) { const u = d ? (total * f - acc) / d : 0; return { x: pts[j - 1].x + (pts[j].x - pts[j - 1].x) * u, y: pts[j - 1].y + (pts[j].y - pts[j - 1].y) * u } }
+ acc += d
+ }
+ return pts[0]
+ }
+ const taken: Box[] = ast.nodes.map((n) => boxes.get(n.id)!)
+ for (const [id, i, pts, own] of jobs) {
+ const t = elab[i]!, e = ast.edges[i]
+ const lw = t.w * k + 8 * k, lh = t.h * k + 4 * k
+ const at = (p: Pt, s: number): Box => {
+ const c = horiz ? { x: p.x, y: p.y + s * (4 * k + lh / 2) } : { x: p.x + s * (6 * k + lw / 2), y: p.y }
+ return { x: c.x - lw / 2, y: c.y - lh / 2, w: lw, h: lh }
+ }
+ const clear = (r: Box) => !taken.some((b) => over(b, r)) && !polys.some((pl, j) => j !== own && pl.some((p, q) => q > 0 && seg(pl[q - 1], p, r)))
+ const first = at(labAt[i] ?? along(pts, 0.5), 1)
+ let best = first
+ if (!clear(first)) {
+ for (const f of [0.5, 0.35, 0.65, 0.25, 0.75]) {
+ const c = [at(along(pts, f), 1), at(along(pts, f), -1)].find(clear)
+ if (c) { best = c; break }
+ }
+ }
+ taken.push(best)
+ // the text box gets 12px of slack past the reserved space: a label that
+ // wraps because the width estimate ran short is worse than a tight one
+ edgeLabels.push(label(id, { x: best.x - (horiz ? 6 * k : 0), y: best.y, w: lw + 12 * k, h: lh }, e.label, EF, P.ink, horiz ? {} : { align: 'left' }))
+ }
+ for (const n of ast.nodes) {
+ const b = boxes.get(n.id)!, id = eid.get(n.id)!
+ const g = n.parent ? { groupId: eid.get(n.parent)! } : {}
+ const st: Partial<DShape> = PATHS[n.shape]
+ ? { shape: 'path', d: PATHS[n.shape], pathBox: [0, 0, 100, 100] }
+ : { shape: n.shape === 'circle' ? 'ellipse' : n.shape === 'tri' ? 'triangle' : 'rect' }
+ out.push({ ...base(id, b, g), type: 'shape', fill: n.style.fill ?? P.fill, stroke: n.style.stroke ?? P.stroke, strokeWidth: 1.5,
+ radius: n.shape === 'round' ? r2(8 * k) : n.shape === 'stadium' ? r2(b.h / 2) : 0, ...st } as DShape)
+ const iw = b.w * (INNER[n.shape] ?? 1)
+ const ty = n.shape === 'tri' ? b.y + b.h * 0.35 : b.y
+ out.push(label(id, { x: b.x + (b.w - iw) / 2, y: ty, w: iw, h: b.y + b.h - ty }, n.label, F, n.style.color ?? P.ink, g))
+ }
+ out.push(...edgeLabels)
+ return { elements: out, warnings, ast }
+}
+
+/** The sidecar for an edited diagram: every node's box, keyed by element id. */
+export function diagramLayout(elements: readonly { type: string; id: string }[]): Record<string, Box> {
+ const out: Record<string, Box> = {}
+ for (const e of elements as DElement[]) {
+ if (e.type !== 'shape' || e.role === 'subgraph' || e.from || e.to || e.shape === 'line') continue
+ Object.defineProperty(out, e.id, { value: { x: e.x, y: e.y, w: e.w, h: e.h }, enumerable: true, writable: true, configurable: true })
+ }
+ return out
+}
+
+// --- elements → mermaid -------------------------------------------------------
+
+const TIPS: Partial<Record<Tip, Head>> = { arrow: 'arrow', 'arrow-open': 'arrow', triangle: 'arrow', 'triangle-open': 'arrow', 'circle-open': 'circle', dot: 'circle', bar: 'cross' }
+const WRAPS: Record<NodeShape, [string, string]> = {
+ rect: ['[', ']'], round: ['(', ')'], stadium: ['([', '])'], subroutine: ['[[', ']]'], cylinder: ['[(', ')]'], circle: ['((', '))'], dblcircle: ['(((', ')))'],
+ diamond: ['{', '}'], hexagon: ['{{', '}}'], 'lean-r': ['[/', '/]'], 'lean-l': ['[\\', '\\]'], 'trap-b': ['[/', '\\]'], 'trap-t': ['[\\', '/]'], odd: ['>', ']'], tri: ['', ''],
+}
+/** Plain text of a label's html (slides' inline subset). */
+function plain(html: string): { text: string; rich: boolean } {
+ const rich = /<(?!br\s*\/?>)[a-z]/i.test(html)
+ const text = html.replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]*>/g, '')
+ .replace(/&(#x[\da-f]+|#\d+|\w+);/gi, (m, n: string) => (n[0] === '#' ? cp(n[1] === 'x' || n[1] === 'X' ? parseInt(n.slice(2), 16) : +n.slice(1), m) : ENT[n.toLowerCase()] ?? m))
+ return { text, rich }
+}
+/** A label as mermaid source: bare when it is plain words, else quoted. */
+function quote(t: string, force = false): string {
+ if (!force && /^[\w ]+$/.test(t) && t.trim() === t) return t
+ return '"' + t.replace(/#(?=\w+;)/g, '#35;').replace(/"/g, '#quot;').replace(/</g, '#lt;').replace(/>/g, '#gt;').replace(/\n/g, '<br>') + '"'
+}
+
+export function diagramToMermaid(elements: readonly { type: string; id: string }[], opts: { direction?: Dir; palette?: Partial<Palette> } = {}): { src: string; lost: Array<{ el: string; what: string }> } {
+ const P = { ...PALETTE, ...opts.palette }
+ const lost: Array<{ el: string; what: string }> = []
+ const els = elements as DElement[]
+ const idOf = makeIds()
+ const mid = new Map<string, string>()
+ const nodes: Array<{ e: DShape; shape: NodeShape }> = [], groups: DShape[] = [], edges: DShape[] = [], texts: DText[] = []
+ for (const e of els) {
+ if (e.type === 'text') { texts.push(e); continue }
+ if (e.type !== 'shape') { const o = e as { id: string; type: string }; lost.push({ el: o.id, what: `${o.type} element` }); continue }
+ if (e.from || e.to) { edges.push(e); continue }
+ if (e.role === 'subgraph') { groups.push(e); mid.set(e.id, idOf(e.id)); continue }
+ let shape: NodeShape = 'rect'
+ if (e.shape === 'line') { lost.push({ el: e.id, what: 'unanchored line' }); continue }
+ if (e.shape === 'path') {
+ const hit = (Object.keys(PATHS) as NodeShape[]).find((k) => PATHS[k] === e.d)
+ if (hit) shape = hit
+ else if (/z\s*$/i.test(e.d ?? '')) lost.push({ el: e.id, what: 'shape: freeform path drawn as a rectangle' })
+ else { lost.push({ el: e.id, what: 'unanchored path' }); continue }
+ } else if (e.shape === 'ellipse') shape = 'circle'
+ else if (e.shape === 'triangle') shape = 'tri'
+ else if (e.shape === 'arrow') lost.push({ el: e.id, what: 'shape: arrow drawn as a rectangle' })
+ else if (e.radius > 0) shape = e.radius >= Math.min(e.w, e.h) / 2 - 0.5 ? 'stadium' : 'round'
+ nodes.push({ e, shape })
+ mid.set(e.id, idOf(e.id))
+ }
+ for (const e of els) {
+ const o = e as DElement & { fillGradient?: unknown; shadow?: unknown; blur?: number }
+ if (o.rotation && !(e.type === 'shape' && (e.shape === 'line' || e.shape === 'path'))) lost.push({ el: e.id, what: 'rotation' })
+ if (o.opacity !== undefined && o.opacity !== 1) lost.push({ el: e.id, what: 'opacity' })
+ if (o.fillGradient) lost.push({ el: e.id, what: 'gradient' })
+ if (o.shadow || o.blur) lost.push({ el: e.id, what: 'shadow or blur' })
+ }
+ // labels: by id convention first, then the smallest shape containing the text's centre
+ const labelOf = new Map<string, string>()
+ const colorOf = new Map<string, string>()
+ const byId = new Map(els.map((e) => [e.id, e]))
+ const spare: DText[] = []
+ for (const t of texts) {
+ const own = t.id.endsWith('-label') ? t.id.slice(0, -6) : ''
+ if (own && byId.has(own) && byId.get(own)!.type === 'shape' && !labelOf.has(own)) take(own, t)
+ else spare.push(t)
+ }
+ for (const t of spare) {
+ const c = center(t)
+ let best: DShape | null = null
+ for (const { e } of nodes) if (!labelOf.has(e.id) && c.x >= e.x && c.x <= e.x + e.w && c.y >= e.y && c.y <= e.y + e.h && (!best || e.w * e.h < best.w * best.h)) best = e
+ if (!best) {
+ // nearest edge midpoint within reach
+ let bd = Math.max(48, Math.hypot(t.w, t.h))
+ for (const e of edges) {
+ if (labelOf.has(e.id)) continue
+ const d = Math.hypot(e.x + e.w / 2 - c.x, e.y + e.h / 2 - c.y)
+ if (d < bd) { bd = d; best = e }
+ }
+ }
+ if (!best) for (const g of groups) if (!labelOf.has(g.id) && c.x >= g.x && c.x <= g.x + g.w && c.y >= g.y && c.y <= g.y + g.h && (!best || g.w * g.h < best.w * best.h)) best = g
+ if (best) take(best.id, t)
+ else lost.push({ el: t.id, what: 'free text' })
+ }
+ function take(id: string, t: DText) {
+ const p = plain(t.html)
+ if (p.rich) lost.push({ el: t.id, what: 'rich text formatting' })
+ labelOf.set(id, p.text)
+ if (t.color !== P.ink) colorOf.set(id, t.color)
+ }
+ // subgraph nesting: the smallest other box containing this one
+ const inside = (a: Box, b: Box) => a.x >= b.x && a.y >= b.y && a.x + a.w <= b.x + b.w && a.y + a.h <= b.y + b.h
+ const parentOf = new Map<string, string | null>()
+ for (const g of groups) {
+ let best: DShape | null = null
+ for (const o of groups) if (o !== g && inside(g, o) && !inside(o, g) && (!best || o.w * o.h < best.w * best.h)) best = o
+ parentOf.set(g.id, best?.id ?? null)
+ }
+ const gids = new Set(groups.map((g) => g.id))
+ const nodeParent = (e: DShape) => (e.groupId && gids.has(e.groupId) ? e.groupId : null)
+
+ // direction, per scope: where the edges between that scope's children point
+ const holder = (id: string): string | null => (gids.has(id) ? parentOf.get(id) ?? null : nodeParent(byId.get(id) as DShape))
+ // the element that stands for x among S's children; a subgraph whose members
+ // link outside is transparent (its members are laid out with S's own)
+ const childOf = (x: string, S: string | null): string | undefined => {
+ let stand = x
+ for (let cur = x, k = 0; k < 100; k++) {
+ const p = holder(cur)
+ if (p === S) return stand
+ if (p === null) return undefined
+ if (!crossed(p)) stand = p
+ cur = p
+ }
+ }
+ // In a layered layout every forward edge moves the same way along the layer
+ // axis while its sideways sign varies, so a direction scores the edges that
+ // move its way (a sum of vectors would let one long edge decide)
+ const DIRS4: Dir[] = ['TB', 'LR', 'BT', 'RL']
+ const infer = (S: string | null | undefined): Dir | undefined => {
+ const votes = [0, 0, 0, 0]
+ for (const e of edges) {
+ if (!e.from || !e.to || !byId.has(e.from.el) || !byId.has(e.to.el)) continue
+ const a = S === undefined ? e.from.el : childOf(e.from.el, S), b = S === undefined ? e.to.el : childOf(e.to.el, S)
+ if (!a || !b || a === b) continue
+ const p = center(byId.get(a)!), q = center(byId.get(b)!), dx = q.x - p.x, dy = q.y - p.y
+ if (dy > 1) votes[0]++
+ if (dx > 1) votes[1]++
+ if (dy < -1) votes[2]++
+ if (dx < -1) votes[3]++
+ }
+ const best = votes.indexOf(Math.max(...votes))
+ return votes[best] ? DIRS4[best] : undefined
+ }
+ // a subgraph none of whose members links outside is laid out in its own direction
+ const within = (x: string, g: string) => { for (let c: string | null = holder(x), k = 0; c && k < 100; c = holder(c), k++) if (c === g) return true; return false }
+ const cross = new Map<string, boolean>()
+ const crossed = (g: string): boolean => cross.get(g) ?? (cross.set(g, edges.some((e) => e.from && e.to && e.from.el !== g && e.to.el !== g && byId.has(e.from.el) && byId.has(e.to.el) && within(e.from.el, g) !== within(e.to.el, g))), cross.get(g)!)
+ const dir = opts.direction ?? infer(null) ?? infer(undefined) ?? 'TB'
+ const lines = [`flowchart ${dir === 'TB' ? 'TD' : dir}`]
+ const styles: string[] = []
+ const style = (e: DShape, dfFill: string, dfStroke: string) => {
+ const s: string[] = []
+ if (e.fill !== dfFill) s.push(`fill:${e.fill}`)
+ if (e.stroke !== dfStroke) s.push(`stroke:${e.stroke}`)
+ const c = colorOf.get(e.id)
+ if (c) s.push(`color:${c}`)
+ if (s.length) styles.push(` style ${mid.get(e.id)} ${s.join(',')}`)
+ }
+ const decl = (n: { e: DShape; shape: NodeShape }, ind: string) => {
+ const id = mid.get(n.e.id)!
+ const lab = labelOf.get(n.e.id) ?? ''
+ if (n.shape === 'tri') lines.push(`${ind}${id}@{ shape: tri, label: ${quote(lab, true)} }`)
+ else if (n.shape === 'rect' && lab === id) lines.push(ind + id)
+ else { const [o, c] = WRAPS[n.shape]; lines.push(`${ind}${id}${o}${quote(lab || ' ')}${c}`) }
+ style(n.e, P.fill, P.stroke)
+ }
+ const emit = (parent: string | null, ind: string, cdir: Dir) => {
+ for (const n of nodes) if (nodeParent(n.e) === parent) decl(n, ind)
+ for (const g of groups) {
+ if (parentOf.get(g.id) !== parent) continue
+ const id = mid.get(g.id)!, lab = labelOf.get(g.id) ?? id
+ lines.push(`${ind}subgraph ${id}${lab === id ? '' : ` [${quote(lab)}]`}`)
+ let d = cdir
+ if (!crossed(g.id)) {
+ // mermaid's default for such a subgraph is the parent's direction turned (TB ⇄ LR)
+ const def: Dir = cdir === 'TB' ? 'LR' : 'TB'
+ d = infer(g.id) ?? def
+ if (d !== def) lines.push(`${ind} direction ${d}`)
+ }
+ emit(g.id, ind + ' ', d)
+ lines.push(`${ind}end`)
+ style(g, P.groupFill, P.groupStroke)
+ }
+ }
+ emit(null, ' ', dir)
+ for (const e of edges) {
+ const a = e.from && mid.get(e.from.el), b = e.to && mid.get(e.to.el)
+ if (!a || !b) { lost.push({ el: e.id, what: e.from && e.to ? 'connector to an element mermaid cannot name' : 'connector with a free end' }); continue }
+ let s = TIPS[e.lineStart ?? 'none'] ?? 'none', t = TIPS[e.lineEnd ?? 'none'] ?? 'none'
+ for (const tip of [e.lineStart, e.lineEnd]) if (tip && tip !== 'none' && tip !== 'arrow' && tip !== 'circle-open' && tip !== 'bar') lost.push({ el: e.id, what: `tip "${tip}"` })
+ let from = a, to = b
+ if (s !== 'none' && t === 'none') { [from, to, s, t] = [b, a, 'none', s] }
+ else if (s !== 'none' && s !== t) { lost.push({ el: e.id, what: 'different tips at the two ends' }); s = 'none' }
+ const colour = e.shape === 'line' ? e.fill : e.stroke
+ if (colour !== P.edge) lost.push({ el: e.id, what: 'edge colour' })
+ const dotted = e.strokeStyle === 'dashed' || e.strokeStyle === 'dotted'
+ const thick = !dotted && e.strokeWidth >= 3
+ const ch = (h: Head, start: boolean) => (h === 'arrow' ? (start ? '<' : '>') : h === 'circle' ? 'o' : h === 'cross' ? 'x' : '')
+ const body = dotted ? (t === 'none' ? '-.-' : '-.-') : thick ? (t === 'none' ? '===' : '==') : t === 'none' ? '---' : '--'
+ const lab = labelOf.get(e.id)
+ lines.push(` ${from} ${ch(s, true)}${body}${ch(t, false)}${lab ? `|${quote(lab)}|` : ''} ${to}`)
+ }
+ return { src: [...lines, ...styles].join('\n') + '\n', lost }
+}