Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(structurizr): make the exported DSL openable, and correct three parser bugs (#1144)
Raghav Chamadiyaf433b149ab3e
diff --git a/docs/architecture/structurizr-export.md b/docs/architecture/structurizr-export.mdindex 96179c23f..e6dc4fe6e 100644--- a/docs/architecture/structurizr-export.md+++ b/docs/architecture/structurizr-export.md@@ -27,12 +27,28 @@ that is already there.## 1. The two-file mental model+**Which one do you want?**++| You | Take | Command |+|---|---|---|+| Have no `workspace.dsl` and want a picture now | A complete workspace | `repowise export --format structurizr --standalone` |+| Already keep a hand-written `workspace.dsl` | A model fragment | `repowise export --format structurizr` |++The fragment is the CLI default because the CLI writes into a repo you own,+where a `workspace.dsl` usually already exists. **It does not open on its+own** — it has no `workspace` block, so a parser given it directly fails with+`Unexpected tokens (expected: workspace)`, and structurizr.com cannot resolve+the `!include` that fixes that because includes are read from disk. If you are+about to upload a file somewhere, you want `--standalone`.++The web UI offers both and leads with the workspace, since anyone exporting+from a browser is unlikely to have a workspace file to include it from.+**We own the model. You own the presentation.**-By default the export writes `repowise-model.dsl`, which holds the contents of-a `model { … }` block and nothing else — no views, no styles, no `workspace`-line. You include it from your own `workspace.dsl`, where your views, styles,-documentation and ADRs live:+The fragment holds the contents of a `model { … }` block and nothing else — no+views, no styles, no `workspace` line. You include it from your own+`workspace.dsl`, where your views, styles, documentation and ADRs live:```workspace "your name" {@@ -55,7 +71,15 @@ anything you wrote. Re-export as often as you like — the diff shows whatchanged in the architecture, not in your formatting.If you have no `workspace.dsl` yet, `--standalone` writes a complete one with-default views so you get a picture from a single command.+default views so you get a picture from a single command. That file is a+*starting point you take over*, not a generated artefact — edit its views and+styles freely, and once you have, switch to the fragment so re-exporting stops+overwriting your work.++Because `--standalone` targets `workspace.dsl`, which is exactly what your own+hand-written workspace is called, the export **refuses to overwrite a file it+did not write**. It names both ways out: emit a fragment beside your file+instead, or pass `--force` to replace it deliberately.---@@ -182,8 +206,10 @@ styles {}```-Tag styles apply in declaration order, so `Hotspot` before `Dead` means a box-that is both reads as dead — the more actionable of the two.+When a box carries both tags, which style wins is decided by the order of the+tags **on the element**, not by the order you declare the rules — reordering+the blocks above changes nothing. We emit `Hotspot` before `Dead`, so a box+that is both reads as dead, the more actionable of the two.---@@ -213,6 +239,7 @@ see the shape before writing your own.| `--components` | off | Include the component level: one box per directory || `--no-externals` | on (externals included) | Leave third-party dependencies out || `--output PATH` | repo root | Where to write; `.dsl` names the file |+| `--force` | off | Overwrite the destination even if Repowise did not write it |**Why components are off by default.** In a hand-curated Structurizr model acomponent is a grouping somebody chose. Ours is a directory. Architects whodiff --git a/packages/cli/src/repowise/cli/commands/export_cmd.py b/packages/cli/src/repowise/cli/commands/export_cmd.pyindex ee592901a..5f104959b 100644--- a/packages/cli/src/repowise/cli/commands/export_cmd.py+++ b/packages/cli/src/repowise/cli/commands/export_cmd.py@@ -56,6 +56,13 @@ from repowise.cli.helpers import (default=False,help="structurizr only: include the component level (one box per directory).",)+ "--force",+ is_flag=True,+ default=False,+ help="structurizr only: overwrite the output file even if Repowise did not "+ "write it. --standalone targets workspace.dsl, which may be your own.",+)@click.option("--no-externals","include_externals",@@ -71,6 +78,7 @@ def export_command(standalone: bool = False,include_components: bool = False,include_externals: bool = True,+ force: bool = False,) -> None:"""Export wiki pages, or the architecture model, to files."""repo_path = resolve_repo_path(path)@@ -85,6 +93,7 @@ def export_command(standalone=standalone,include_components=include_components,include_externals=include_externals,+ force=force,)if code:raise SystemExit(code)diff --git a/packages/cli/src/repowise/cli/commands/export_structurizr.py b/packages/cli/src/repowise/cli/commands/export_structurizr.pyindex f46e64e67..719a92f69 100644--- a/packages/cli/src/repowise/cli/commands/export_structurizr.py+++ b/packages/cli/src/repowise/cli/commands/export_structurizr.py@@ -26,6 +26,27 @@ _LITE_COMMAND = ("docker run --rm -p 8080:8080 -v .:/usr/local/structurizr structurizr/structurizr local")+#: Present in the first line of everything we emit. Used to tell a file we may+#: overwrite from one somebody wrote by hand.+_GENERATED_MARKER = "generated by Repowise."+++def _is_generated(path: Path) -> bool:+ """True if *path* looks like a file we wrote.++ Only the head is read: these files run to hundreds of lines and the marker+ is on line one by construction. An unreadable or undecodable file is+ treated as *not* ours, which is the safe direction — the caller refuses to+ overwrite it.+ """+ try:+ with path.open("r", encoding="utf-8") as handle:+ return _GENERATED_MARKER in handle.readline()+ except OSError:+ return False+ except UnicodeDecodeError:+ return False+def _resolve_output(output: str | None, repo_path: Path, *, standalone: bool) -> Path:"""Where to write. A path ending in ``.dsl`` is the file; anything else is@@ -126,8 +147,14 @@ def _print_next_steps(destination: Path, *, standalone: bool, system_id: str) ->"""Say what to do next, not just what was written."""directory = destination.parentif standalone:- _line("\n View it:")+ # This one renders on its own, so lead with the two ways to look at it+ # and put the upload route first: it needs nothing installed.+ _line("\n Open it:")+ _line(" Paste it into https://structurizr.com/dsl — nothing to install")_line(f" cd {directory} && {_LITE_COMMAND}\n")+ _line(" The views and styles in it are yours to edit. Once you have")+ _line(" changed them, keep them by switching to the model fragment:")+ _line(" repowise export --format structurizr\n")return_line("\n Add this to your workspace.dsl:\n")@@ -146,7 +173,9 @@ def _print_next_steps(destination: Path, *, standalone: bool, system_id: str) -># someone who already keeps a workspace.dsl is how a helpful hint becomes# noise.if not (directory / STANDALONE_FILENAME).exists():- _line(" No workspace.dsl yet?")+ _line(" No workspace.dsl yet? This file cannot be opened on its own —")+ _line(" a fragment has no workspace block, and structurizr.com cannot")+ _line(" resolve !include. For a file that renders as-is:")_line(" repowise export --format structurizr --standalone\n")_line(" View it:")@@ -160,6 +189,7 @@ def export_structurizr(standalone: bool,include_components: bool,include_externals: bool,+ force: bool = False,) -> int:"""Write the DSL. Returns a process exit code."""from repowise.cli.helpers import run_async@@ -186,6 +216,24 @@ def export_structurizr(return 1destination = _resolve_output(output, repo_path, standalone=standalone)++ # --standalone defaults to workspace.dsl in the repo root, which is exactly+ # the filename a Structurizr user's own hand-written workspace already has.+ # Overwriting it would destroy views, styles and docs that took real work+ # and live nowhere else. Anything carrying our marker is ours to replace.+ if destination.exists() and not force and not _is_generated(destination):+ console.print(+ f"[yellow]{destination} already exists and was not written by Repowise.[/yellow]"+ )+ _line("\n Refusing to overwrite it. Pick one:")+ _line(+ f" repowise export --format structurizr -o {destination.parent / FRAGMENT_FILENAME}"+ )+ _line(" …then !include that file from the workspace.dsl you have")+ _line(" repowise export --format structurizr --standalone --force")+ _line(" …to replace it anyway\n")+ return 1+destination.parent.mkdir(parents=True, exist_ok=True)destination.write_text(to_dsl(diff --git a/packages/server/src/repowise/server/services/c4_builder/structurizr/__init__.py b/packages/server/src/repowise/server/services/c4_builder/structurizr/__init__.pyindex 972d3535c..de213d6ee 100644--- a/packages/server/src/repowise/server/services/c4_builder/structurizr/__init__.py+++ b/packages/server/src/repowise/server/services/c4_builder/structurizr/__init__.py@@ -156,25 +156,47 @@ def system_identifier(model: C4Model, *, include_components: bool = False) -> stdef _write_header(writer: Writer, model: C4Model, *, standalone: bool) -> None:"""The comment block a person reads first, in their editor or a diff.+ The two shapes want opposite advice, which is the whole reason this+ branches. The fragment is ours and gets overwritten, so it says don't edit.+ The standalone workspace is a *starting point* the user is meant to take+ over — telling them not to edit it would leave them with a file they can+ neither change nor regenerate around.+Deliberately carries no timestamp: a timestamp makes every regeneration adiff, which destroys the "commit it and watch it change meaningfully"workflow this file exists for."""writer.comment(f"Structurizr DSL model for {model.system.name}, generated by Repowise.")writer.comment()- writer.comment("Regenerating overwrites this file — do not hand-edit it.")- if not standalone:- writer.comment("It holds the model only; your views, styles and docs stay in")- writer.comment("your own workspace.dsl. Include it from inside the workspace")- writer.comment("block — the parser rejects an include that sits outside one:")+ if standalone:+ writer.comment("A complete workspace: open it as-is in Structurizr Lite, the")+ writer.comment("Structurizr CLI, or by pasting it into structurizr.com.")writer.comment()- writer.comment(' workspace "your name" {')- writer.comment(f" !include {DEFAULT_FILENAME}")+ writer.comment("This file is yours now — edit the views and styles below freely.")+ writer.comment("Re-exporting overwrites the whole file, so once you have made it")+ writer.comment("your own, switch to the model fragment instead and keep your")+ writer.comment("presentation in a workspace.dsl the generator never touches:")writer.comment()- writer.comment(" views {")- writer.comment(" ...")- writer.comment(" }")- writer.comment(" }")+ writer.comment(" repowise export --format structurizr")+ writer.comment()+ return++ writer.comment("Regenerating overwrites this file — do not hand-edit it.")+ writer.comment("It holds the model only; your views, styles and docs stay in")+ writer.comment("your own workspace.dsl. Include it from inside the workspace")+ writer.comment("block — the parser rejects an include that sits outside one:")+ writer.comment()+ writer.comment(' workspace "your name" {')+ writer.comment(f" !include {DEFAULT_FILENAME}")+ writer.comment()+ writer.comment(" views {")+ writer.comment(" ...")+ writer.comment(" }")+ writer.comment(" }")+ writer.comment()+ writer.comment("!include is resolved from disk, so this pair needs Structurizr Lite")+ writer.comment("or the Structurizr CLI. The web editor at structurizr.com cannot")+ writer.comment("follow it — export with --standalone for a file to paste there.")writer.comment()diff --git a/packages/server/src/repowise/server/services/c4_builder/structurizr/metadata.py b/packages/server/src/repowise/server/services/c4_builder/structurizr/metadata.pyindex 428e9e67c..ea51807ce 100644--- a/packages/server/src/repowise/server/services/c4_builder/structurizr/metadata.py+++ b/packages/server/src/repowise/server/services/c4_builder/structurizr/metadata.py@@ -38,8 +38,16 @@ def layer_tag(name: str) -> str:string the element was never tagged with parses fine and then matchesnothing, which is harder to spot than a parse error. One function meansthey cannot drift.++ Commas are dropped because Structurizr splits the ``tags`` argument on them+ *inside* the quotes: ``tags "Layer: Docs, Rendering"`` is stored as the two+ tags ``Layer: Docs`` and ``Rendering``. The second one has lost the prefix,+ which is the exact collision the prefix exists to prevent — a layer named+ "Coupling, Tight" would put a bare ``Tight`` in the tag namespace next to+ the relationship style of that name. Layer names are curated prose, so a+ comma in one is ordinary input, not a corner case."""- return f"{_LAYER_TAG_PREFIX}{name}"+ return f"{_LAYER_TAG_PREFIX}{name.replace(',', ' ')}"def tags_for(signals: BoxSignals | None) -> list[str]:diff --git a/packages/server/src/repowise/server/services/c4_builder/structurizr/views.py b/packages/server/src/repowise/server/services/c4_builder/structurizr/views.pyindex 617f71b88..32d6f3fe6 100644--- a/packages/server/src/repowise/server/services/c4_builder/structurizr/views.py+++ b/packages/server/src/repowise/server/services/c4_builder/structurizr/views.py@@ -39,7 +39,14 @@ def write_views(system_ref = references[model.system.id]with writer.block("views"):with writer.block(f"systemContext {system_ref} {quote('SystemContext')}"):+ # `include *` alone puts every external in here. Structurizr+ # promotes a container→external edge to the system level, so all+ # ~50 npm and pypi packages land in the context view and it stops+ # being a context view — the one diagram whose whole job is to fit+ # on a slide. They are dependencies rather than systems anyone+ # integrates with, and the container view below still shows them.writer.line("include *")+ writer.line('exclude "element.tag==External"')writer.line("autolayout lr")writer.blank()@@ -80,9 +87,11 @@ def write_views(with writer.block('element "External"'):writer.line("background #999999")writer.line("color #ffffff")- # The health colours. Tag styles are applied in declaration order,- # so Hotspot before Dead means a dead hotspot reads as dead — the- # more actionable of the two.+ # The health colours. Which one wins on an element carrying both is+ # decided by the order of tags *on the element*, not the order these+ # rules are declared — `tags_for` emits Hotspot then Dead, so a dead+ # hotspot reads as dead, the more actionable of the two. Reordering+ # these blocks would change nothing.with writer.block('element "Hotspot"'):writer.line("background #b5432f")writer.line("color #ffffff")@@ -116,6 +125,10 @@ def _write_layer_views(writer: Writer, model: C4Model, references: dict[str, strfor layer in layers:writer.blank()key = _view_key("layer", keys[layer])- with writer.block(f"container {system_ref} {quote(key)}"):+ # The key is slugged for uniqueness, so it reads as+ # `layer_Ingestion_and_Reasoning_Pipeline` in the view picker. The+ # description is the third positional argument and is what Structurizr+ # actually shows a reader, so the curated name survives to the UI.+ with writer.block(f"container {system_ref} {quote(key)} {quote(layer)}"):writer.line(f"include {quote(f'element.tag=={layer_tag(layer)}')}")writer.line("autolayout lr")diff --git a/packages/server/src/repowise/server/services/c4_builder/structurizr/writer.py b/packages/server/src/repowise/server/services/c4_builder/structurizr/writer.pyindex f69036840..0b08443cb 100644--- a/packages/server/src/repowise/server/services/c4_builder/structurizr/writer.py+++ b/packages/server/src/repowise/server/services/c4_builder/structurizr/writer.py@@ -71,9 +71,28 @@ class Writer:def quote(text: str) -> str:"""Quote a value for the DSL.- Structurizr string literals are double-quoted with no escape sequence, so- an embedded quote is replaced rather than escaped, and newlines are- flattened — a literal newline inside a quoted value is a parse error.+ Newlines are flattened: a literal newline inside a quoted value is a parse+ error.++ A quote is **escaped**, not replaced. ``\\"`` is the one escape the parser+ honours, and it survives being nested inside a view filter expression+ (``include "element.tag==Layer: Data \\"Access\\""`` both parses and selects+ the element tagged that way), so the tag and the filter that selects it stay+ identical without either of them losing the character.++ A **trailing** backslash is dropped, because it cannot be expressed at all.+ ``\\\\`` is not an escape — backslashes pass through literally — so the last+ one in a value would pair with the closing quote instead, escape it, and run+ the string on into the rest of the file. Interior backslashes are left+ alone; a Windows path stays readable."""flattened = " ".join(str(text).split())- return '"' + flattened.replace('"', "'") + '"'+ # Order matters: escaping quotes introduces backslashes of its own, but only+ # ever in front of a quote, so nothing it adds can end up trailing.+ # The space goes with it: dropping the backslash off "Escape Hatch \" would+ # otherwise leave a trailing one. Structurizr trims both a tag and the+ # filter that selects it, so it would still match — but only by symmetry,+ # and layer_tag's guarantee is that the two strings are byte-identical.+ # Whitespace is already collapsed above, so nothing legitimate is stripped.+ escaped = flattened.replace('"', '\\"').rstrip("\\ ")+ return f'"{escaped}"'diff --git a/packages/ui/__tests__/c4/export-menu-structurizr.test.tsx b/packages/ui/__tests__/c4/export-menu-structurizr.test.tsxindex 15a59baab..429ee6aae 100644--- a/packages/ui/__tests__/c4/export-menu-structurizr.test.tsx+++ b/packages/ui/__tests__/c4/export-menu-structurizr.test.tsx@@ -1,22 +1,34 @@/**- * The Structurizr entry in the C4 export menu.+ * The Structurizr entries in the C4 export menu.*- * It downloads rather than copies: the DSL is a file people commit, and it- * carries a header comment that only survives as a file. The entry is hidden- * unless the host supplies a fetcher, matching how Mermaid and JSON behave.+ * They download rather than copy: the DSL is a file people commit, and it+ * carries a header comment that only survives as a file. The entries are+ * hidden unless the host supplies a fetcher, matching how Mermaid and JSON+ * behave.+ *+ * There are two of them because the two shapes are not interchangeable — a+ * fragment has no `workspace` block and will not open on its own — so the menu+ * has to let the user say which one they want rather than guessing.*/import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { render, fireEvent, waitFor } from "@testing-library/react";import { C4ExportMenu } from "../../src/c4/export/ExportMenu";-const DSL = '# Structurizr DSL model for demo\nmodel {\n sys_demo = softwareSystem "demo"\n}\n';+const FRAGMENT =+ '# Structurizr DSL model for demo\nmodel {\n sys_demo = softwareSystem "demo"\n}\n';+const WORKSPACE = `# Structurizr DSL model for demo\nworkspace "demo" {\n ${FRAGMENT}\n}\n`;++const WORKSPACE_ITEM = "Structurizr workspace";+const FRAGMENT_ITEM = "Structurizr model fragment";let createdUrls: string[] = [];let lastBlob: Blob | null = null;+let lastDownloadName: string | null = null;beforeEach(() => {createdUrls = [];lastBlob = null;+ lastDownloadName = null;// jsdom implements neither, and the exporter uses both to trigger a save.globalThis.URL.createObjectURL = vi.fn((blob: Blob) => {lastBlob = blob;@@ -25,6 +37,13 @@ beforeEach(() => {return url;}) as unknown as typeof URL.createObjectURL;globalThis.URL.revokeObjectURL = vi.fn() as unknown as typeof URL.revokeObjectURL;+ // The filename is half the point of the two entries — capture it off the+ // anchor the exporter clicks, since jsdom performs no actual download.+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (+ this: HTMLAnchorElement,+ ) {+ lastDownloadName = this.download;+ });});afterEach(() => {@@ -52,29 +71,31 @@ function itemNamed(container: HTMLElement, label: string) {}describe("C4ExportMenu — Structurizr DSL", () => {- it("hides the entry when the host provides no fetcher", () => {+ it("hides the entries when the host provides no fetcher", () => {const { container } = render(<C4ExportMenu nodes={[]} edges={[]} fileNameStem="demo" />,);open(container);- expect(itemNamed(container, "Structurizr DSL")).toBeUndefined();+ expect(itemNamed(container, WORKSPACE_ITEM)).toBeUndefined();+ expect(itemNamed(container, FRAGMENT_ITEM)).toBeUndefined();});- it("shows the entry when a fetcher is supplied", () => {+ it("offers both shapes when a fetcher is supplied", () => {const { container } = render(<C4ExportMenunodes={[]}edges={[]}fileNameStem="demo"- fetchStructurizr={async () => DSL}+ fetchStructurizr={async () => FRAGMENT}/>,);open(container);- expect(itemNamed(container, "Structurizr DSL")).toBeDefined();+ expect(itemNamed(container, WORKSPACE_ITEM)).toBeDefined();+ expect(itemNamed(container, FRAGMENT_ITEM)).toBeDefined();});- it("downloads the DSL the host returns, unchanged", async () => {- const fetchStructurizr = vi.fn(async () => DSL);+ it("asks for a standalone workspace and names the file workspace.dsl", async () => {+ const fetchStructurizr = vi.fn(async () => WORKSPACE);const { container } = render(<C4ExportMenunodes={[]}@@ -84,14 +105,69 @@ describe("C4ExportMenu — Structurizr DSL", () => {/>,);open(container);- fireEvent.click(itemNamed(container, "Structurizr DSL")!);+ fireEvent.click(itemNamed(container, WORKSPACE_ITEM)!);- await waitFor(() => expect(fetchStructurizr).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(fetchStructurizr).toHaveBeenCalledWith({ standalone: true }),+ );await waitFor(() => expect(createdUrls.length).toBe(1));- expect(lastBlob).not.toBeNull();+ expect(lastDownloadName).toBe("workspace.dsl");// The header comment is what tells a downloader what the file is, so the// bytes have to arrive exactly as the backend wrote them.- await expect(readBlob(lastBlob!)).resolves.toBe(DSL);+ await expect(readBlob(lastBlob!)).resolves.toBe(WORKSPACE);+ });++ it("asks for a fragment and names the file repowise-model.dsl", async () => {+ const fetchStructurizr = vi.fn(async () => FRAGMENT);+ const { container } = render(+ <C4ExportMenu+ nodes={[]}+ edges={[]}+ fileNameStem="demo"+ fetchStructurizr={fetchStructurizr}+ />,+ );+ open(container);+ fireEvent.click(itemNamed(container, FRAGMENT_ITEM)!);++ await waitFor(() =>+ expect(fetchStructurizr).toHaveBeenCalledWith({ standalone: false }),+ );+ await waitFor(() => expect(createdUrls.length).toBe(1));+ expect(lastDownloadName).toBe("repowise-model.dsl");+ await expect(readBlob(lastBlob!)).resolves.toBe(FRAGMENT);+ });++ it("puts the openable file first", () => {+ const { container } = render(+ <C4ExportMenu+ nodes={[]}+ edges={[]}+ fileNameStem="demo"+ fetchStructurizr={async () => WORKSPACE}+ />,+ );+ open(container);+ const labels = Array.from(container.querySelectorAll('[role="menuitem"]')).map(+ (node) => node.textContent ?? "",+ );+ const workspaceAt = labels.findIndex((l) => l.includes(WORKSPACE_ITEM));+ const fragmentAt = labels.findIndex((l) => l.includes(FRAGMENT_ITEM));+ expect(workspaceAt).toBeGreaterThan(-1);+ expect(workspaceAt).toBeLessThan(fragmentAt);+ });++ it("says what the fragment needs, so nobody downloads it by mistake", () => {+ const { container } = render(+ <C4ExportMenu+ nodes={[]}+ edges={[]}+ fileNameStem="demo"+ fetchStructurizr={async () => FRAGMENT}+ />,+ );+ open(container);+ expect(itemNamed(container, FRAGMENT_ITEM)?.textContent).toContain("workspace.dsl");});it("reports a failure instead of failing silently", async () => {@@ -106,7 +182,7 @@ describe("C4ExportMenu — Structurizr DSL", () => {/>,);open(container);- fireEvent.click(itemNamed(container, "Structurizr DSL")!);+ fireEvent.click(itemNamed(container, WORKSPACE_ITEM)!);await waitFor(() =>expect(container.textContent).toContain("Export failed"),diff --git a/packages/ui/src/c4/C4Diagram.tsx b/packages/ui/src/c4/C4Diagram.tsxindex 51b6e17bc..dda2a5ee9 100644--- a/packages/ui/src/c4/C4Diagram.tsx+++ b/packages/ui/src/c4/C4Diagram.tsx@@ -75,9 +75,10 @@ export interface C4DiagramProps {/*** Host-provided Structurizr DSL fetcher. When supplied, the export menu- * offers "Structurizr DSL". Omit to hide.+ * offers both DSL shapes — a complete workspace and a model fragment — and+ * passes `standalone` to say which one it wants. Omit to hide.*/- fetchStructurizr?: (() => Promise<string>) | undefined;+ fetchStructurizr?: ((options: { standalone: boolean }) => Promise<string>) | undefined;onLevelChange: (level: C4Level) => void;onDrillInto: (containerId: string) => void;diff --git a/packages/ui/src/c4/export/ExportMenu.tsx b/packages/ui/src/c4/export/ExportMenu.tsxindex 26006442e..7de436e7b 100644--- a/packages/ui/src/c4/export/ExportMenu.tsx+++ b/packages/ui/src/c4/export/ExportMenu.tsx@@ -30,11 +30,14 @@ export interface C4ExportMenuProps {/*** Host-provided fetcher for the Structurizr DSL. Hidden if omitted.*- * The file the host returns carries its own header comment explaining that- * it is a model fragment and how to include it, so someone who downloads it- * without reading any docs still knows what they have.+ * Called with `standalone: true` for a complete `workspace { … }` and+ * `false` for a bare `model { … }` fragment — the menu offers both, and a+ * host that ignores the flag will serve the same file for both entries.+ * Whichever comes back carries its own header comment explaining what it is+ * and how to open it, so someone who downloads it without reading any docs+ * still knows what they have.*/- fetchStructurizr?: () => Promise<string>;+ fetchStructurizr?: (options: { standalone: boolean }) => Promise<string>;/** Disabled when the diagram is empty / still loading. */disabled?: boolean;/** Architecture view data for JSON export. JSON option hidden if omitted. */@@ -113,21 +116,24 @@ export function C4ExportMenu({setOpen(false);}, [architectureView, activeFilters, activePersona, fileNameStem]);- const onStructurizr = useCallback(async () => {- if (!fetchStructurizr) return;- setStatus("working");- try {- const text = await fetchStructurizr();- triggerDownload(- new Blob([text], { type: "text/plain;charset=utf-8" }),- "repowise-model.dsl",- );- setStatus("idle");- setOpen(false);- } catch {- setStatus("error");- }- }, [fetchStructurizr]);+ const onStructurizr = useCallback(+ async (standalone: boolean) => {+ if (!fetchStructurizr) return;+ setStatus("working");+ try {+ const text = await fetchStructurizr({ standalone });+ triggerDownload(+ new Blob([text], { type: "text/plain;charset=utf-8" }),+ standalone ? "workspace.dsl" : "repowise-model.dsl",+ );+ setStatus("idle");+ setOpen(false);+ } catch {+ setStatus("error");+ }+ },+ [fetchStructurizr],+ );const onMermaidDownload = useCallback(async () => {if (!fetchMermaid) return;@@ -205,10 +211,21 @@ export function C4ExportMenu({{fetchStructurizr && (<><Divider />+ {/* Workspace first: whoever is exporting from a diagram in a+ browser is unlikely to already keep a workspace.dsl, and the+ fragment does not open on its own. The hints say which is+ which without making anyone read the file to find out. */}+ <MenuItem+ icon={<FileType2 size={12} />}+ label="Structurizr workspace (.dsl)"+ hint="Opens as-is — includes default views"+ onClick={() => void onStructurizr(true)}+ /><MenuItemicon={<FileType2 size={12} />}- label="Structurizr DSL"- onClick={onStructurizr}+ label="Structurizr model fragment"+ hint="For a workspace.dsl you already have"+ onClick={() => void onStructurizr(false)}/></>)}@@ -236,10 +253,13 @@ export function C4ExportMenu({function MenuItem({icon,label,+ hint,onClick,}: {icon: React.ReactNode;label: string;+ /** Second line, for a choice whose label cannot carry the whole distinction. */+ hint?: string;onClick: () => void;}) {return (@@ -249,7 +269,9 @@ function MenuItem({onClick={onClick}style={{display: "flex",- alignItems: "center",+ // Top rather than centre: with a hint the icon should sit on the+ // label's line, not float in the middle of a two-line block.+ alignItems: hint ? "flex-start" : "center",gap: 8,width: "100%",padding: "6px 10px",@@ -264,8 +286,25 @@ function MenuItem({onMouseEnter={(e) => (e.currentTarget.style.background = "var(--color-border-subtle)")}onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>- {icon}- {label}+ <span style={{ display: "flex", paddingTop: hint ? 2 : 0 }}>{icon}</span>+ {hint ? (+ <span style={{ display: "block" }}>+ {label}+ <span+ style={{+ display: "block",+ marginTop: 2,+ fontSize: 10,+ lineHeight: 1.35,+ color: "var(--color-text-secondary)",+ }}+ >+ {hint}+ </span>+ </span>+ ) : (+ label+ )}</button>);}diff --git a/packages/web/src/components/zoom/zoom-export-button.tsx b/packages/web/src/components/zoom/zoom-export-button.tsxindex d3e8a003b..c0c5b0ec4 100644--- a/packages/web/src/components/zoom/zoom-export-button.tsx+++ b/packages/web/src/components/zoom/zoom-export-button.tsx@@ -1,14 +1,20 @@"use client";/**- * Download this repository's architecture as a Structurizr DSL model.+ * Download this repository's architecture as Structurizr DSL.*- * The file is a model *fragment* by default — the same artefact- * `repowise export --format structurizr` writes — so it drops into a- * workspace the user already owns without clobbering their views or styles.- * It carries its own header comment explaining that and showing the- * `!include` snippet, which is what stops someone who never saw the terminal- * output from reading it as broken.+ * Two shapes, because the two audiences want opposite files:+ *+ * - **Workspace** (the default). A complete `workspace { … }` with default+ * views and styles. Someone downloading through a browser almost by+ * definition has no Structurizr workspace yet — if they had one they would+ * be running `repowise export` inside their repo. This file opens as-is in+ * Structurizr Lite or pasted into structurizr.com.+ * - **Model fragment**. Just the `model { … }` body, for the smaller group who+ * already keep a hand-written workspace.dsl and want the model regenerated+ * under their own views. Useless on its own — the parser rejects a file that+ * does not start with `workspace`, and `!include` only resolves from disk —+ * so it is the secondary item, labelled with what it needs.** Note the model is grouped by container and component (package manifests and* directories), not by the layers this page's canvas draws; layer membership@@ -16,13 +22,14 @@* "export what I am looking at".*/-import { useCallback, useRef, useState } from "react";-import { FileType2, Loader2 } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { FileType2, Loader2, ChevronDown } from "lucide-react";import { toast } from "sonner";import { getStructurizrDsl } from "@repowise-dev/api-client/c4";import { downloadTextFile } from "@/lib/utils/download";-const FILENAME = "repowise-model.dsl";+const WORKSPACE_FILENAME = "workspace.dsl";+const FRAGMENT_FILENAME = "repowise-model.dsl";export function ZoomExportButton({repoId,@@ -32,49 +39,125 @@ export function ZoomExportButton({disabled?: boolean;}) {const [working, setWorking] = useState(false);+ const [open, setOpen] = useState(false);// `working` is only true after a re-render, and `disabled` follows it, so two// clicks inside one tick both get through and both fetch. A ref is read and// set synchronously, which is the only thing that closes that window.const inFlight = useRef(false);+ const rootRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!open) return;+ const onPointer = (event: MouseEvent) => {+ if (!rootRef.current?.contains(event.target as globalThis.Node)) setOpen(false);+ };+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") setOpen(false);+ };+ window.addEventListener("mousedown", onPointer);+ window.addEventListener("keydown", onKey);+ return () => {+ window.removeEventListener("mousedown", onPointer);+ window.removeEventListener("keydown", onKey);+ };+ }, [open]);++ const download = useCallback(+ async (standalone: boolean) => {+ if (inFlight.current) return;+ inFlight.current = true;+ setWorking(true);+ setOpen(false);+ const filename = standalone ? WORKSPACE_FILENAME : FRAGMENT_FILENAME;+ try {+ const dsl = await getStructurizrDsl(repoId, { standalone });+ downloadTextFile(dsl, filename, "text/plain");+ toast.success(`Downloaded ${filename}`);+ } catch (error) {+ // The client throws with the status code, so a 404 (no such repo) and a+ // 500 (built and failed) are different problems. Keep it out of the toast+ // and in the console, where someone debugging will look.+ console.error("Structurizr DSL export failed", error);+ toast.error("Couldn't build the Structurizr DSL");+ } finally {+ inFlight.current = false;+ setWorking(false);+ }+ },+ [repoId],+ );++ return (+ // z-50 on the wrapper, not just the menu: the zoom canvas floats its+ // breadcrumb/search overlay at z-10 from a *later* DOM subtree, so at equal+ // z-index that overlay paints over this menu. Raising the whole wrapper+ // puts the menu's stacking context above the canvas chrome outright.+ <div ref={rootRef} className="relative z-50">- const onClick = useCallback(async () => {- if (inFlight.current) return;- inFlight.current = true;- setWorking(true);- try {- const dsl = await getStructurizrDsl(repoId);- downloadTextFile(dsl, FILENAME, "text/plain");- toast.success(`Downloaded ${FILENAME}`);- } catch (error) {- // The client throws with the status code, so a 404 (no such repo) and a- // 500 (built and failed) are different problems. Keep it out of the toast- // and in the console, where someone debugging will look.- console.error("Structurizr DSL export failed", error);- toast.error("Couldn't build the Structurizr DSL");- } finally {- inFlight.current = false;- setWorking(false);- }- }, [repoId]);+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ disabled={disabled || working}+ aria-busy={working}+ aria-haspopup="menu"+ aria-expanded={open}+ title="Download this repository's architecture as Structurizr DSL"+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-50"+ >+ {working ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <FileType2 className="h-3.5 w-3.5" />+ )}+ {/* The label carries the state, not just the icon: lucide marks its+ glyphs aria-hidden, so a spinner alone tells a screen-reader user+ nothing happened. */}+ {working ? "Building…" : "Structurizr DSL"}+ {!working && <ChevronDown className="h-3 w-3" />}+ </button>+ {open && (+ <div+ role="menu"+ className="absolute right-0 top-[calc(100%+4px)] z-10 w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-1 shadow-lg"+ >+ <ExportOption+ label="Workspace (workspace.dsl)"+ hint="Complete file with default views. Opens as-is in Structurizr."+ onClick={() => void download(true)}+ />+ <ExportOption+ label="Model fragment (repowise-model.dsl)"+ hint="Model block only, to !include from a workspace.dsl you already have."+ onClick={() => void download(false)}+ />+ </div>+ )}+ </div>+ );+}+function ExportOption({+ label,+ hint,+ onClick,+}: {+ label: string;+ hint: string;+ onClick: () => void;+}) {return (<buttontype="button"- onClick={() => void onClick()}- disabled={disabled || working}- aria-busy={working}- title="Download this repository's architecture as a Structurizr DSL model fragment"- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-50"+ role="menuitem"+ onClick={onClick}+ className="block w-full rounded-md px-2.5 py-2 text-left transition-colors hover:bg-[var(--color-border-subtle)]">- {working ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <FileType2 className="h-3.5 w-3.5" />- )}- {/* The label carries the state, not just the icon: lucide marks its- glyphs aria-hidden, so a spinner alone tells a screen-reader user- nothing happened. */}- {working ? "Building…" : "Structurizr DSL"}+ <span className="block text-xs font-medium text-[var(--color-text-primary)]">+ {label}+ </span>+ <span className="mt-0.5 block text-[11px] leading-snug text-[var(--color-text-secondary)]">+ {hint}+ </span></button>);}diff --git a/tests/unit/cli/test_export_structurizr.py b/tests/unit/cli/test_export_structurizr.pyindex 26be4ead4..46e4868cf 100644--- a/tests/unit/cli/test_export_structurizr.py+++ b/tests/unit/cli/test_export_structurizr.py@@ -140,6 +140,74 @@ def test_standalone_writes_a_whole_workspace(tmp_path: Path, patched) -> None:assert "views {" in written+def test_a_hand_written_workspace_is_never_overwritten(tmp_path: Path, patched, capsys) -> None:+ """--standalone targets workspace.dsl, which is what a Structurizr user's+ own hand-written workspace is already called. Clobbering it would destroy+ views, styles and docs that live nowhere else."""+ mine = tmp_path / STANDALONE_FILENAME+ mine.write_text('workspace "mine" {\n # my views\n}\n', encoding="utf-8")++ code = export_structurizr(+ tmp_path,+ output=None,+ standalone=True,+ include_components=False,+ include_externals=True,+ )+ assert code == 1+ assert mine.read_text(encoding="utf-8").startswith('workspace "mine"')+ out = capsys.readouterr().out+ # Both ways out are named: include the fragment, or overwrite deliberately.+ assert "--force" in out+ assert FRAGMENT_FILENAME in out+++def test_force_overwrites_a_file_that_is_not_ours(tmp_path: Path, patched) -> None:+ mine = tmp_path / STANDALONE_FILENAME+ mine.write_text('workspace "mine" {}\n', encoding="utf-8")++ code = export_structurizr(+ tmp_path,+ output=None,+ standalone=True,+ include_components=False,+ include_externals=True,+ force=True,+ )+ assert code == 0+ assert "generated by Repowise" in mine.read_text(encoding="utf-8")+++def test_our_own_output_is_replaced_without_asking(tmp_path: Path, patched) -> None:+ """Re-exporting is the normal workflow; a prompt every time would be noise."""+ for _ in range(2):+ code = export_structurizr(+ tmp_path,+ output=None,+ standalone=False,+ include_components=False,+ include_externals=True,+ )+ assert code == 0+ assert (tmp_path / FRAGMENT_FILENAME).exists()+++def test_a_binary_file_at_the_destination_is_treated_as_not_ours(tmp_path: Path, patched) -> None:+ """An undecodable file must fail closed — it is certainly not our text."""+ target = tmp_path / "arch.dsl"+ target.write_bytes(b"\xff\xfe\x00binary")++ code = export_structurizr(+ tmp_path,+ output=str(target),+ standalone=False,+ include_components=False,+ include_externals=True,+ )+ assert code == 1+ assert target.read_bytes() == b"\xff\xfe\x00binary"++def test_a_missing_parent_directory_is_created(tmp_path: Path, patched) -> None:target = tmp_path / "nested" / "deeper" / "arch.dsl"code = export_structurizr(@@ -199,6 +267,22 @@ def test_the_standalone_hint_only_appears_when_there_is_no_workspace(assert "--standalone" not in capsys.readouterr().out+def test_the_standalone_message_leads_with_the_zero_install_route(+ tmp_path: Path, patched, capsys+) -> None:+ """A docker command is not an answer for someone without docker."""+ export_structurizr(+ tmp_path,+ output=None,+ standalone=True,+ include_components=False,+ include_externals=True,+ )+ out = capsys.readouterr().out+ assert "structurizr.com" in out+ assert out.index("structurizr.com") < out.index("docker run")++def test_counts_are_reported_so_an_empty_index_is_obvious() -> None:summary = _counts(_model(), include_components=True, include_externals=True)assert "1 containers" in summarydiff --git a/tests/unit/server/test_structurizr_export.py b/tests/unit/server/test_structurizr_export.pyindex 696081548..32eb33095 100644--- a/tests/unit/server/test_structurizr_export.py+++ b/tests/unit/server/test_structurizr_export.py@@ -191,6 +191,27 @@ def test_fragment_explains_how_to_use_itself() -> None:assert 'workspace "your name" {' in dsl+def test_the_fragment_header_warns_the_web_editor_cannot_resolve_an_include() -> None:+ """The failure it prevents: paste both files into structurizr.com, get an+ unresolved include and no diagram."""+ dsl = to_dsl(_model())+ assert "structurizr.com" in dsl+ assert "--standalone" in dsl+++def test_the_standalone_header_hands_the_file_over_rather_than_locking_it() -> None:+ """Opposite advice from the fragment on purpose: this one is a starting+ point the user is meant to edit, so 'do not hand-edit' would be wrong."""+ dsl = to_dsl(_model(), standalone=True)+ assert "do not hand-edit" not in dsl+ assert "yours" in dsl+ # And it names the escape hatch once they have made it their own.+ assert "repowise export --format structurizr" in dsl+ # The include snippet belongs to the fragment; a complete workspace that+ # tells you to !include itself is nonsense.+ assert "!include" not in dsl++def test_there_is_no_timestamp_in_the_output() -> None:"""A timestamp would make every regeneration a diff."""dsl = to_dsl(_model(), standalone=True, include_components=True)@@ -386,7 +407,12 @@ def test_quoting_survives_a_name_with_quotes_and_newlines() -> None:dsl = to_dsl(model)system_line = next(line for line in dsl.splitlines() if "softwareSystem" in line)assert "\n" not in system_line- assert system_line.count('"') % 2 == 0+ # Escaped quotes are content, not delimiters, so only the unescaped ones+ # have to pair up.+ assert _unescaped_quotes(system_line) % 2 == 0+ # And the quote survives rather than being rewritten: `\"` is the one escape+ # the parser honours, at both this level and inside a filter expression.+ assert 'we\\"rd' in system_linedef test_the_system_identifier_does_not_depend_on_the_local_repo_id() -> None:@@ -643,9 +669,28 @@ def test_a_system_name_with_a_newline_cannot_break_the_header() -> None:assert not line or line.startswith("#"), line+#: One DSL string literal: quoted, with ``\"`` allowed inside it.+_STRING = re.compile(r'"((?:[^"\\]|\\.)*)"')+++def _dsl_strings(line: str) -> list[str]:+ """Every string literal on *line*, decoded the way the parser reads them.++ Splitting on ``"`` is what these helpers used to do, and it stops working+ the moment a value legitimately contains an escaped quote — which is how+ the emitter now spells one, because the parser supports it.+ """+ return [match.replace('\\"', '"') for match in _STRING.findall(line)]+++def _unescaped_quotes(line: str) -> int:+ """How many quotes actually open or close a string on *line*."""+ return len(re.findall(r'(?<!\\)"', line))++def _layer_view_keys(dsl: str) -> list[str]:return [- line.split('"')[1]+ _dsl_strings(line)[0]for line in dsl.splitlines()if line.strip().startswith("container ") and '"layer_' in line]@@ -653,9 +698,11 @@ def _layer_view_keys(dsl: str) -> list[str]:def _layer_filters(dsl: str) -> list[str]:return [- line.strip().split("element.tag==", 1)[1].rstrip('"')+ value.split("element.tag==", 1)[1]for line in dsl.splitlines()if "element.tag==" in line+ for value in _dsl_strings(line)+ if value.startswith("element.tag==")]@@ -664,7 +711,7 @@ def _emitted_tags(dsl: str) -> set[str]:for line in dsl.splitlines():stripped = line.strip()if stripped.startswith("tags "):- tags.update(re.findall(r'"([^"]*)"', stripped))+ tags.update(_dsl_strings(stripped))return tags@@ -689,14 +736,80 @@ def test_two_layer_names_that_slug_alike_get_different_view_keys() -> None:def test_a_layer_name_with_a_quote_cannot_break_the_filter() -> None:- """The filter is a string literal, so an unescaped quote ends it early."""+ """The filter is a string literal, so an *unescaped* quote ends it early.++ The tag inside it is a string within a string, and the escape survives both+ levels — verified against the parser — so the quote is kept rather than+ substituted away.+ """dsl = to_dsl(_signals_model(box_signals={"pkg:packages/core": BoxSignals(layers=('Data "Access"',))}),standalone=True,)- filter_lines = [line for line in dsl.splitlines() if "element.tag==" in line]+ # Scoped to `include`: the SystemContext view carries an `exclude` filter+ # of its own, which is not what this is about.+ filter_lines = [+ line for line in dsl.splitlines() if line.strip().startswith('include "element.tag==')+ ]assert len(filter_lines) == 1- assert filter_lines[0].count('"') == 2, filter_lines[0]+ assert _unescaped_quotes(filter_lines[0]) == 2, filter_lines[0]+ assert 'Data \\"Access\\"' in filter_lines[0]+++def test_a_comma_in_a_layer_name_does_not_split_it_into_two_tags() -> None:+ """Structurizr splits the `tags` argument on commas *inside* the quotes, so+ `tags "Layer: Docs, Rendering"` stores `Layer: Docs` and a bare `Rendering`+ — a tag that has escaped the namespace the prefix exists to enforce."""+ dsl = to_dsl(+ _signals_model(box_signals={"pkg:packages/core": BoxSignals(layers=("Coupling, Tight",))}),+ standalone=True,+ )+ tag_lines = [line.strip() for line in dsl.splitlines() if line.strip().startswith("tags ")]+ assert tag_lines+ for line in tag_lines:+ assert "," not in line, line+ # The layer survives as one namespaced tag rather than two, the second of+ # which would have been a bare `Tight` colliding with the coupling style.+ assert '"Layer: Coupling Tight"' in dsl+++def test_a_trailing_backslash_cannot_run_a_string_past_its_closing_quote() -> None:+ """A backslash introduces an escape, so a value ending in one would eat its+ own terminator and swallow the rest of the line."""+ dsl = to_dsl(+ _signals_model(box_signals={"pkg:packages/core": BoxSignals(layers=("Windows C:\\",))}),+ standalone=True,+ )+ # It cannot be escaped either — `\\` is not an escape, backslashes pass+ # through literally — so the only safe thing is to drop the trailing one.+ assert "Layer: Windows C:" in dsl+ assert "C:\\" not in dsl+ # Every quoted line still closes: an even number of *unescaped* quotes.+ for line in dsl.splitlines():+ if line.strip().startswith("#"):+ continue+ assert _unescaped_quotes(line) % 2 == 0, line+++def test_the_context_view_leaves_out_the_dependency_wall() -> None:+ """Structurizr promotes container→external edges to the system level, so+ `include *` alone puts every npm package in the one diagram meant to fit on+ a slide."""+ dsl = to_dsl(_model(), standalone=True)+ context = dsl.split("systemContext ")[1].split("}")[0]+ assert 'exclude "element.tag==External"' in context+++def test_a_layer_view_is_labelled_with_the_curated_name() -> None:+ """The key is slugged for uniqueness; the description is what a reader sees+ in the view picker."""+ dsl = to_dsl(+ _signals_model(+ box_signals={"pkg:packages/core": BoxSignals(layers=("Ingestion and Reasoning",))}+ ),+ standalone=True,+ )+ assert '"Ingestion and Reasoning"' in dsldef test_a_layer_filter_matches_the_tag_that_was_actually_emitted() -> None:@@ -721,7 +834,7 @@ def test_a_layer_filter_matches_the_tag_that_was_actually_emitted() -> None:def _declared(dsl: str, keyword: str) -> list[str]:"""The display names of every element declared with *keyword*."""return [- line.split(f"{keyword} ", 1)[1].split('"')[1]+ _dsl_strings(line.split(f"{keyword} ", 1)[1])[0]for line in dsl.splitlines()if f"= {keyword} " in line]