From b1deb726a0a255660f4614d199143b233107b395 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 00:32:52 +0800 Subject: [PATCH 01/16] =?UTF-8?q?feat:=20validate=20=E5=8C=BA=E5=88=86?= =?UTF-8?q?=E8=A1=8C=E5=8F=B7=E7=A7=BB=E5=8A=A8=E4=B8=8E=E8=AF=AD=E4=B9=89?= =?UTF-8?q?=E6=BC=82=E7=A7=BB=EF=BC=8C--fix=20=E7=94=9F=E6=88=90=E6=BC=82?= =?UTF-8?q?=E7=A7=BB=E5=BE=85=E5=8A=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 生成与 --fix 记录 meta.sourceFiles(逐文件 git blob 基线) - 只移动行号的出处自动对齐;改写、删调用留死方法、未覆盖的新代码、 消失的名字报为 Source drift,附前后代码与受影响元素 - --fix 写入 meta.sourceDrift 待办,未清空前校验与生成失败 - 基线缺失时提示 fetch-depth: 0 并退回原检查;旧图行为不变 - 更新 SKILL.md 刷新流程、graph-schema 说明与 7 份 README 的 CI 片段 --- README.md | 6 +- docs/readme/README.de.md | 6 +- docs/readme/README.es.md | 6 +- docs/readme/README.ja.md | 6 +- docs/readme/README.pt.md | 6 +- docs/readme/README.ru.md | 6 +- docs/readme/README.zh-CN.md | 6 +- package.json | 1 + skills/q-flow/SKILL.md | 6 +- skills/q-flow/references/graph-schema.md | 1 + skills/q-flow/scripts/generate-viewer.mjs | 4 +- skills/q-flow/scripts/source-drift.mjs | 214 ++++++++++++++++++++ skills/q-flow/scripts/source-drift.test.mjs | 116 +++++++++++ skills/q-flow/scripts/validate-graph.mjs | 108 ++++++++-- 14 files changed, 454 insertions(+), 38 deletions(-) create mode 100644 skills/q-flow/scripts/source-drift.mjs create mode 100644 skills/q-flow/scripts/source-drift.test.mjs diff --git a/README.md b/README.md index 9ba5579..00923b9 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ Open `output/jeepay/index.html`; its eleven SVGs are in the same directory. See ## Keep diagrams in sync with code -A diagram generated with a repository root records where each component is defined and the line behind each code-backed relationship (a call, a foreign key). Validating it with `--repo-root` fails when a recorded file is gone, a line range no longer fits, or a recorded symbol has left its lines, and the error names the lines where the symbol is now. Add this job to your CI; it needs no build, login or token: +A diagram generated with a repository root records where each component is defined, the line behind each code-backed relationship (a call, a foreign key) and a fingerprint of every file it points into. Validating it with `--repo-root` lets lines that only moved pass and fails when the code behind the diagram changed: a recorded line was rewritten, a call was removed, new code touches a drawn component that no relationship covers, or a name the diagram uses is gone. The error shows the old and new code and names the elements and text to update. Add this job to your CI; it needs no build, login or token, and full history (`fetch-depth: 0`) lets it compare against those fingerprints: ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ When it fails, ask the skill to refresh that diagram: $qgraphflow:q-flow CI says docs/qgraphflow/order-sequence is out of date. Refresh it. ``` -The skill moves anchors whose symbol it finds once, corrects only the anchors still reported, and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. +The skill realigns every anchor, lists each change in the graph's `meta.sourceDrift`, updates only the elements those items name and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. ## What each of the eleven diagram types answers diff --git a/docs/readme/README.de.md b/docs/readme/README.de.md index daac308..e506fee 100644 --- a/docs/readme/README.de.md +++ b/docs/readme/README.de.md @@ -234,7 +234,7 @@ node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph. ## Diagramme mit dem Code synchron halten -Ein mit Repository-Wurzel erzeugtes Diagramm hält fest, wo jede Komponente definiert ist, und die Zeile hinter jeder durch Code gestützten Beziehung (ein Aufruf, ein Fremdschlüssel). Die Prüfung mit `--repo-root` schlägt fehl, wenn eine erfasste Datei fehlt, ein Zeilenbereich nicht mehr in die Datei passt oder ein erfasstes Symbol seine Zeilen verlassen hat; die Meldung nennt die Zeilen, in denen das Symbol jetzt steht. Diesen Job in die CI aufnehmen; er braucht keinen Build, keine Anmeldung und kein Token: +Ein mit Repository-Wurzel erzeugtes Diagramm hält fest, wo jede Komponente definiert ist, die Zeile hinter jeder durch Code gestützten Beziehung (ein Aufruf, ein Fremdschlüssel) und einen Fingerabdruck jeder Datei, auf die es verweist. Die Prüfung mit `--repo-root` lässt Zeilen, die nur verschoben wurden, passieren und schlägt fehl, wenn sich der Code hinter dem Diagramm geändert hat: Eine erfasste Zeile wurde umgeschrieben, ein Aufruf entfernt, neuer Code berührt eine gezeichnete Komponente ohne passende Beziehung, oder ein im Diagramm verwendeter Name ist verschwunden. Die Meldung zeigt alten und neuen Code und nennt die Elemente und Texte, die anzupassen sind. Diesen Job in die CI aufnehmen; er braucht keinen Build, keine Anmeldung und kein Token, und die vollständige Historie (`fetch-depth: 0`) erlaubt den Vergleich mit diesen Fingerabdrücken: ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ Schlägt er fehl, den Skill bitten, dieses Diagramm zu aktualisieren: $qgraphflow:q-flow Laut CI ist docs/qgraphflow/order-sequence veraltet. Bitte aktualisieren. ``` -Der Skill verschiebt Anker, deren Symbol er genau einmal in der Datei findet, korrigiert nur die weiterhin gemeldeten Anker und erzeugt Seite und SVGs neu, wobei bearbeitete Positionen und Texte erhalten bleiben. Er zeichnet das Diagramm nicht neu. +Der Skill richtet alle Anker am aktuellen Code aus, listet jede Änderung in `meta.sourceDrift` des Graphen, aktualisiert nur die dort genannten Elemente und erzeugt Seite und SVGs neu, wobei bearbeitete Positionen und Texte erhalten bleiben. Er zeichnet das Diagramm nicht neu. ## Welche Fragen die elf Diagrammarten beantworten diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index 0ee215c..77958e0 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -234,7 +234,7 @@ Abre `output/jeepay/index.html`; sus once SVG están en el mismo directorio. Con ## Mantener los diagramas sincronizados con el código -Un diagrama generado con la raíz del repositorio registra dónde se define cada componente y la línea detrás de cada relación respaldada por código (una llamada, una clave foránea). La validación con `--repo-root` falla cuando falta un archivo registrado, un rango de líneas ya no cabe en el archivo o un símbolo registrado salió de sus líneas, y el error indica en qué líneas está ahora el símbolo. Añadir este trabajo a la CI; no necesita compilación, inicio de sesión ni token: +Un diagrama generado con la raíz del repositorio registra dónde se define cada componente, la línea detrás de cada relación respaldada por código (una llamada, una clave foránea) y una huella de cada archivo al que apunta. La validación con `--repo-root` deja pasar las líneas que solo se desplazaron y falla cuando cambió el código detrás del diagrama: se reescribió una línea registrada, se eliminó una llamada, código nuevo toca un componente dibujado sin una relación que lo cubra, o desapareció un nombre que usa el diagrama. El error muestra el código anterior y el nuevo e indica los elementos y textos que hay que actualizar. Añadir este trabajo a la CI; no necesita compilación, inicio de sesión ni token, y el historial completo (`fetch-depth: 0`) permite compararlo con esas huellas: ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ Si falla, pedir a la habilidad que actualice ese diagrama: $qgraphflow:q-flow La CI dice que docs/qgraphflow/order-sequence está desactualizado. Actualízalo. ``` -La habilidad mueve los anclajes cuyo símbolo encuentra una sola vez en el archivo, corrige solo los que siguen fallando y vuelve a generar la página y los SVG conservando las posiciones y los textos editados. No redibuja el diagrama. +La habilidad realinea todos los anclajes, enumera cada cambio en `meta.sourceDrift` del grafo, actualiza solo lo que esas entradas señalan y vuelve a generar la página y los SVG conservando las posiciones y los textos editados. No redibuja el diagrama. ## Qué responde cada uno de los once tipos de diagramas diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index b122259..9cfc8f2 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.md @@ -234,7 +234,7 @@ node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph. ## 図とコードを同期させる -リポジトリのルートを指定して生成した図には、各コンポーネントの定義位置と、コードで裏付けられた各関係を成立させている行(呼び出し、外部キーなど)が記録されます。`--repo-root` 付きで検証すると、記録したファイルがない、行範囲がファイルに収まらない、記録したシンボルが元の行範囲から外れた、のいずれかで失敗し、エラーにはシンボルの現在の行が示されます。次のジョブを CI に追加してください。ビルド、ログイン、トークンは不要です。 +リポジトリのルートを指定して生成した図には、各コンポーネントの定義位置、コードで裏付けられた各関係を成立させている行(呼び出し、外部キーなど)、そして参照している各ファイルの内容の指紋が記録されます。`--repo-root` 付きで検証すると、位置が移動しただけの行は自動で追従して通過し、図の裏にあるコードが実際に変わったときだけ失敗します。記録した行が書き換えられた、呼び出しが削除された、図に描かれたコンポーネントに触れる新しいコードに対応する関係がない、図で使っている名前がなくなった、のいずれかです。エラーには変更前後のコードと、更新すべき要素と文字が示されます。次のジョブを CI に追加してください。ビルド、ログイン、トークンは不要です。指紋と比較するため、完全な履歴(`fetch-depth: 0`)を取得します。 ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ jobs: $qgraphflow:q-flow CI で docs/qgraphflow/order-sequence の図が古いと出ました。更新してください。 ``` -スキルは、ファイル内で 1 か所だけ見つかったシンボルのアンカーを移し、なお失敗するアンカーだけを修正し、編集した位置と文字を保ったままページと SVG を再生成します。図を描き直すことはしません。 +スキルはすべてのアンカーを現在のコードに合わせ、各変更をグラフの `meta.sourceDrift` に列挙し、その項目が示す要素だけを更新して、編集した位置と文字を保ったままページと SVG を再生成します。図を描き直すことはしません。 ## 11 種類の図がそれぞれ答えること diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md index 1bc62a6..fbb9909 100644 --- a/docs/readme/README.pt.md +++ b/docs/readme/README.pt.md @@ -234,7 +234,7 @@ Abra `output/jeepay/index.html`; os onze SVG estão no mesmo diretório. Consult ## Mantenha os diagramas em sincronia com o código -Um diagrama gerado com a raiz do repositório registra onde cada componente é definido e a linha por trás de cada relação sustentada pelo código (uma chamada, uma chave estrangeira). A validação com `--repo-root` falha quando um arquivo registrado sumiu, um intervalo de linhas não cabe mais no arquivo ou um símbolo registrado saiu das suas linhas, e o erro indica as linhas em que o símbolo está agora. Adicione este job ao seu CI; ele não precisa de build, login nem token: +Um diagrama gerado com a raiz do repositório registra onde cada componente é definido, a linha por trás de cada relação sustentada pelo código (uma chamada, uma chave estrangeira) e uma impressão digital de cada arquivo para o qual aponta. A validação com `--repo-root` deixa passar as linhas que apenas mudaram de lugar e falha quando o código por trás do diagrama mudou: uma linha registrada foi reescrita, uma chamada foi removida, código novo toca um componente desenhado sem relação que o cubra, ou um nome usado pelo diagrama desapareceu. O erro mostra o código antigo e o novo e indica os elementos e textos a atualizar. Adicione este job ao seu CI; ele não precisa de build, login nem token, e o histórico completo (`fetch-depth: 0`) permite comparar com essas impressões digitais: ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ Quando falhar, peça à habilidade para atualizar o diagrama: $qgraphflow:q-flow O CI diz que docs/qgraphflow/order-sequence está desatualizado. Atualize-o. ``` -A habilidade move as âncoras cujo símbolo aparece uma única vez no arquivo, corrige apenas as âncoras que ainda falham e gera de novo a página e os SVG, mantendo as posições e os textos que você editou. Ela não redesenha o diagrama. +A habilidade realinha todas as âncoras, lista cada mudança em `meta.sourceDrift` do grafo, atualiza apenas os elementos que esses itens indicam e gera de novo a página e os SVG, mantendo as posições e os textos que você editou. Ela não redesenha o diagrama. ## O que cada um dos onze tipos de diagrama responde diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index 39c7a23..16ae68f 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -234,7 +234,7 @@ node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph. ## Синхронизация диаграмм с кодом -Диаграмма, созданная с указанием корня репозитория, запоминает, где определён каждый компонент, и строку за каждой связью, подтверждённой кодом (вызов, внешний ключ). Проверка с `--repo-root` завершается ошибкой, если записанного файла больше нет, диапазон строк не помещается в файл или записанный символ ушёл из своих строк; в сообщении указано, в каких строках символ находится теперь. Добавьте эту задачу в CI — ей не нужны сборка, вход или токен: +Диаграмма, созданная с указанием корня репозитория, запоминает, где определён каждый компонент, строку за каждой связью, подтверждённой кодом (вызов, внешний ключ), и отпечаток каждого файла, на который она ссылается. Проверка с `--repo-root` пропускает строки, которые только сдвинулись, и завершается ошибкой, когда изменился сам код за диаграммой: записанная строка переписана, вызов удалён, новый код затрагивает нарисованный компонент, но не покрыт ни одной связью, или имя, которое использует диаграмма, исчезло. В сообщении показаны старый и новый код и названы элементы и тексты, которые нужно обновить. Добавьте эту задачу в CI — ей не нужны сборка, вход или токен; полная история (`fetch-depth: 0`) нужна, чтобы сравнить код с отпечатками: ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ jobs: $qgraphflow:q-flow CI сообщает, что диаграмма docs/qgraphflow/order-sequence устарела. Обнови её. ``` -Навык переносит якоря, символ которых встречается в файле один раз, исправляет только якоря с оставшимися ошибками и пересоздаёт страницу и SVG, сохраняя ваши позиции и тексты. Заново диаграмму он не рисует. +Навык выравнивает все якоря по текущему коду, записывает каждое изменение в `meta.sourceDrift` графа, обновляет только названные там элементы и пересоздаёт страницу и SVG, сохраняя ваши позиции и тексты. Заново диаграмму он не рисует. ## На какие вопросы отвечает каждый из одиннадцати типов диаграмм diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index 4367651..e9b99de 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -234,7 +234,7 @@ Open `output/jeepay/index.html`; its eleven SVGs are in the same directory. See ## 让图和代码保持同步 -带仓库根目录生成的图会记下每个组件定义在哪里,以及每条有代码支撑的关系所在的那一行(调用、外键等)。用 `--repo-root` 校验时,记录的文件不在了、行号超出文件,或记录的符号离开了原来的行范围,校验都会失败,并在错误里写出这个符号现在所在的行。把下面这个任务加进 CI,不需要构建、登录或令牌: +带仓库根目录生成的图会记下每个组件定义在哪里、每条有代码支撑的关系所在的那一行(调用、外键等),以及它指向的每个文件的内容指纹。用 `--repo-root` 校验时,只是挪了位置的行会自动对上、照常通过;只有图背后的代码真的变了才会失败:记录的那一行被改写、某个调用被删掉、新代码碰到了图里画的组件却没有对应的关系,或者图里用到的名字已经不存在。错误里会给出改动前后的代码,并指出要更新的元素和文字。把下面这个任务加进 CI,不需要构建、登录或令牌;拉取完整历史(`fetch-depth: 0`)才能和这些指纹比对: ```yaml name: Diagrams @@ -244,6 +244,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -260,7 +262,7 @@ jobs: $qgraphflow:q-flow CI 提示 docs/qgraphflow/order-sequence 的图过时了,刷新一下。 ``` -技能会把在文件里只找到一处的符号重新定位,只修改仍然报错的锚点,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 +技能会把所有锚点对齐到当前代码,把每处改动列进图的 `meta.sourceDrift`,只更新这些条目指出的元素,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 ## 十一类图各自回答什么 diff --git a/package.json b/package.json index 2266bcf..51f4788 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "skills/q-flow/references/", "skills/q-flow/scripts/generate-viewer.mjs", "skills/q-flow/scripts/validate-graph.mjs", + "skills/q-flow/scripts/source-drift.mjs", "skills/q-flow/assets/viewer-dist/index.html", "skills/q-flow/assets/viewer/package.json", "skills/q-flow/assets/viewer/src/diagrams/", diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index 17f28f6..d37f7ec 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -46,10 +46,10 @@ node scripts/validate-graph.mjs "/graph.json" --repo- ``` - Execute the scripts; do not read them, the bundled HTML, the Viewer source or tests. `--help` lists every option. Failures report elements, rule, measurement and remediation; `--verbose` prints the receipt. -- On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and unique source/site symbols, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. +- On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and moved anchors, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. - Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: apply the common contract's view-splitting rules while preserving requested detail and graph count. A failing collection names every failing view. - If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. Generation defaults to `--layout auto`; `--layout preserve` keeps existing geometry under the same gate. -- For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local UTF-8 files (existence, line range, symbol, no path escape) and report `sourceEvidence` with its `relations` coverage. This checks the working tree, not the commit in `sourceRef` or whether code proves a relationship. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. +- For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local files (existence, line range, symbol) and report `sourceEvidence` with `relations` coverage. Generation records `meta.sourceFiles`: moved lines pass, changed code fails as drift. Neither proves a claim. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. - Outputs are `index.html`, `graph.json` and one SVG per view (`diagram.svg`, or `diagram--.svg` in a collection), built from the prebuilt viewer; no rebuild or install. Use `--force` only with approval to replace the named outputs. All collection views must pass before replacing output. - Reply with artifact paths, types, granularity and coverage (`meta.scope`), semantic/geometry/source-relation results, `meta.notes`, unresolved evidence boundaries, and `Browser acceptance: not performed` unless the next section ran. Never paste full HTML or graph JSON. @@ -68,7 +68,7 @@ node scripts/validate-graph.mjs "/graph.json" --input-only --fix --repo-roo node scripts/generate-viewer.mjs "/graph.json" "" --layout preserve --force --repo-root "" ``` -Between the two, fix only anchors still reported: read just their files, edit just those `source` / `site` anchors or facts, and report a symbol you cannot place. Then validate the output as above. `preserve` keeps the user's moved positions and edited text; if it fails the gate, report the nodes and ask before `--layout auto`. Reply with the changed anchors and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. +Between the two, work only what `--fix` left: update just the elements each `meta.sourceDrift` item names (relate uncovered new code), then delete the item; fix anchors still reported and report a symbol you cannot place. Validate the output as above. `preserve` keeps moved positions and text; if it fails the gate, report the nodes and ask before `--layout auto`. Reply with the changed elements and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. ## Viewer maintenance diff --git a/skills/q-flow/references/graph-schema.md b/skills/q-flow/references/graph-schema.md index 2a9896b..0269baf 100644 --- a/skills/q-flow/references/graph-schema.md +++ b/skills/q-flow/references/graph-schema.md @@ -98,6 +98,7 @@ The abbreviated graphs above show only the wrapper; every graph still follows th - Optional node `source.kind` uses the same evidence values. `source.file` and `source.lineStart` identify the exact anchor. - Optional edge `site` (`file`, `lineStart`, optional `lineEnd` and `symbol`) records the line that makes the relationship hold: the call, write, foreign key, `extends` clause or state assignment. It has the same shape and checks as a node `source` but no `kind`: the edge's own `evidence` names the kind. An edge needs one when its `evidence` is `source`, `code`, `config`, `schema` or `test` and it is not a sequence `return` (`needsSite()`); the field is optional everywhere, so graphs written without it stay valid. - With `--repo-root `, validation and generation read every node's `source.file` and every edge's `site.file` as repository-relative UTF-8 text and check the inclusive line range. Absolute paths, parent traversal, directories, binary files and symlinks escaping the root are rejected. Repeated references share one file read. When `source.symbol` is present, its last segment (split on every character other than a letter, digit, `_` or `$`) must occur as a whole word within the range; write the name as it appears at the definition, not a description. A failure names the lines where the word does occur in the file, and the receipt counts symbol checks in `sourceEvidence.symbols` and relationship coverage in `sourceEvidence.relations` (`sited` of `eligible`, computed with or without the root). A site failure is named `diagrams[i].edges[j].site`. `--fix --repo-root` moves a node `source` or edge `site` `lineStart` to the only such line in the file and shifts `lineEnd` with it, clamped to the last line; anchors with several or no matches stay for the author (`edge .site` in the messages). Without the root, receipts explicitly mark existing source anchors `skipped`; without anchors they report `not-applicable`. These checks cover the local working tree, not `sourceRef` revision identity, definition parsing or claim correctness: a mention of the name left inside the range still passes. +- Source drift. With `--repo-root` inside a git work tree, generation and `validate --fix` record `meta.sourceFiles` on every view: each anchored file mapped to the git blob hash of the content its anchors point at (computed with `git hash-object`, nothing written to the repository). Later validation diffs each file against that blob: an anchor on a line that only moved follows it (in memory; `--fix` and generation write the new numbers) and passes, while changed code fails as source drift, grouped per changed hunk with the old and new lines, the anchored elements and the text that names what changed. Drift is reported when (1) an anchored line was rewritten, with any text still stating a number the rewrite changed; (2) a removed call leaves a method with no caller in the repository, naming the anchors inside it and the text that names what only it used; (3) added code that mentions an anchored symbol or calls a receiver named like an anchored file sits on no anchor; (4) an identifier gone from the anchored files is still written in the graph. `validate --fix --repo-root` realigns every anchor, renews `meta.sourceFiles` and appends one `meta.sourceDrift` item per change to each view it touches (`file`, `line`, `change`, `removed`, `added`, `anchors`, `mentions`); validation and generation fail while any item remains, so the author updates the named elements and deletes each item. A baseline blob missing from the repository (a shallow CI clone: use `fetch-depth: 0`) is reported and that file falls back to the working-tree check above; graphs without `meta.sourceFiles` keep that check unchanged. The rules are C-family text heuristics, not a parser: a call split across lines or an overloaded name can be missed. - To emphasize the business center, use the existing `business` kind where supported, or include `core` or `business` in `tags` (matched case-insensitively). Keep the diagram's legal node kind; `core` is not a new kind or schema field. In a state diagram the `core` state is the goal and a `failure` tag marks a failed state; both only feed the Viewer's derived state colors. - Composition review (`reviewComposition()` in `graph-validation.js`, printed in full by `validate-graph.mjs --input-only` as `Composition warning () : …`, counted as `warnings: n` in every receipt) is advisory: warnings never fail validation or generation, and a collection with no `module` anywhere gets none. Rules: `module.missing` (an ordinary node without `module` once the collection uses modules; `initial` / `final` and the outsider kinds `external`, `actor`, `device` are exempt), `module.inconsistent` (the same node label carries a module in one view and none or another in a second view), `module.single-tone` (a flowchart or data flow of ≥ 6 washed nodes all in one module — a prompt to check, legitimate when the flow lives in one subsystem), `flowchart.process-branch` (a non-decision with more than one outgoing edge), `edge.site-missing` (an edge that needs a `site` while at least one other edge of the same graph records one; a graph with no site anywhere stays quiet). One rule needs the laid-out graph: `view.oversized` (`overviewWarnings()`, printed by `generate-viewer.mjs` once and only counted by output validation) fires when a view's bounds need more than `MAX_SCREENS` (4) reading rectangles of `OVERVIEW_AREA` (1392×688, a 1440×900 window with both panels closed) at `READABLE_ZOOM` (.75); a graph without positions reports nothing. The receipt carries `warnings: ` only when there are any. - The cool-neutral visual system is a Viewer presentation rule. Color, typography, and core styling require no new graph fields. The order-fulfillment preview model is example content, not a default dataset or evidence source. diff --git a/skills/q-flow/scripts/generate-viewer.mjs b/skills/q-flow/scripts/generate-viewer.mjs index cff9e2a..dcd069d 100644 --- a/skills/q-flow/scripts/generate-viewer.mjs +++ b/skills/q-flow/scripts/generate-viewer.mjs @@ -6,7 +6,7 @@ import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { isDeepStrictEqual, parseArgs } from 'node:util'; -import { diagramTypeOf, graphsOf, printCompositionReview, printViewReview, readAndValidateGraph, verifySourceEvidence, layoutComposition } from './validate-graph.mjs'; +import { diagramTypeOf, graphsOf, printCompositionReview, printViewReview, readAndValidateGraph, stampSourceFiles, verifySourceEvidence, layoutComposition } from './validate-graph.mjs'; import { compileGraphLayout } from './compile-layout.mjs'; import { requireDiagramQuality } from '../assets/viewer/src/layout-quality.js'; import { pageWithGraph } from '../assets/viewer/src/session-graph.js'; @@ -104,6 +104,8 @@ async function main() { for (let i = 0; i < views.length; i++) if (selected.size && !selected.has(viewIdOf(views[i])) && !isDeepStrictEqual(compiled[i].graph, views[i])) throw new Error(`Unselected view ${viewIdOf(views[i])} requires migration; update it explicitly before changing this collection`); const quality = compiled.map(item => requireDiagramQuality(item.graph)); const graph = Array.isArray(input.diagrams) ? { ...input, diagrams: compiled.map(item => item.graph) } : compiled[0].graph; + // Record what the anchors point at now, so validate can later tell moved lines from changed code. + if (values['repo-root'] !== undefined) stampSourceFiles(graph, values['repo-root']); const oversized = printViewReview(graph, { print: true }); // geometry exists only now; the input review could not see it const contents = { 'index.html': pageWithGraph(shell, graph), 'graph.json': `${JSON.stringify(graph, null, 2)}\n` }; for (const { name, svg } of diagramSvgFiles(graph)) contents[name] = svg; diff --git a/skills/q-flow/scripts/source-drift.mjs b/skills/q-flow/scripts/source-drift.mjs new file mode 100644 index 0000000..5b77067 --- /dev/null +++ b/skills/q-flow/scripts/source-drift.mjs @@ -0,0 +1,214 @@ +// Source drift: compares each anchored file with the content the diagram was made from (meta.sourceFiles, git blob +// hashes) and separates harmless line moves from changes a reader of the diagram must see. +// ponytail: C-family regex heuristics (calls, method spans, comments), not a parser; per-language parsing would cut +// the remaining misses (a call split across lines, overloaded names). +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const git = (root, args, input) => spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 64 << 20, input }); +const KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'synchronized', 'super', 'this', 'else', 'throw']); +const isCode = line => line.trim() && !/^\s*(\/\/|\/\*|\*|#)/.test(line); +const callsIn = line => [...line.matchAll(/([A-Za-z_$][\w$]*)\s*\(/g)].map(match => match[1]).filter(name => !KEYWORDS.has(name)); +const word = term => new RegExp(`(? new RegExp(`(? value && typeof value === 'object' && typeof value.file === 'string' && Number.isInteger(value.lineStart); +// Geometry, the drift bookkeeping itself, and fields that hold ids or enum values rather than prose. +const SKIP = new Set(['layout', 'route', 'position', 'size', 'sourceFiles', 'sourceDrift', 'id', 'source', 'target', 'replyTo', 'edgeId', 'edgeIds', + 'participantId', 'parentId', 'groupId', 'module', 'kind', 'evidence', 'viewId', 'diagramType', 'architectureView', 'locale', 'direction', 'at', 'sourceRef']); + +// Blob hashes of the given repository-relative files as they are now, or null outside a git work tree. +export function fingerprintFiles(repoRoot, files) { + if (!files.length || git(repoRoot, ['rev-parse', '--is-inside-work-tree']).status !== 0) return null; + const result = git(repoRoot, ['hash-object', '--', ...files]); + if (result.status !== 0) return null; + const hashes = result.stdout.trim().split('\n'); + return Object.fromEntries(files.map((file, i) => [file, hashes[i]])); +} + +// Hunks of a zero-context unified diff, in old-line order. +export function parseHunks(text) { + const hunks = []; + let hunk; + for (const line of text.split('\n')) { + const header = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + if (header) { hunk = { oldStart: +header[1], oldCount: header[2] === undefined ? 1 : +header[2], newStart: +header[3], newCount: header[4] === undefined ? 1 : +header[4], removed: [], added: [] }; hunks.push(hunk); } + else if (hunk && line.startsWith('-') && !line.startsWith('---')) hunk.removed.push(line.slice(1)); + else if (hunk && line.startsWith('+') && !line.startsWith('+++')) hunk.added.push(line.slice(1)); + } + return hunks; +} + +// An old line's new number, or the hunk that rewrote it. +export function mapLine(hunks, line) { + let delta = 0; + for (const hunk of hunks) { + if (hunk.oldCount === 0) { if (hunk.oldStart < line) delta += hunk.newCount; continue; } + if (line < hunk.oldStart) break; + if (line < hunk.oldStart + hunk.oldCount) return { hunk }; + delta += hunk.newCount - hunk.oldCount; + } + return { line: line + delta }; +} + +function fileDiff(repoRoot, blob, file) { + const old = git(repoRoot, ['cat-file', 'blob', blob]); + if (old.status !== 0) return null; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qgraphflow-drift-')); + try { + const before = path.join(dir, 'before'); + fs.writeFileSync(before, old.stdout); + const result = spawnSync('git', ['diff', '--no-index', '--no-color', '--no-ext-diff', '-U0', before, path.resolve(repoRoot, file)], { encoding: 'utf8', maxBuffer: 64 << 20 }); + if (result.status !== 0 && result.status !== 1) return null; + return { hunks: parseHunks(result.stdout), before: old.stdout }; + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +} + +// Every human-readable string of a view with the element that carries it; anchors and geometry are skipped. +function textsOf(graph, view) { + const texts = []; + const walk = (value, element, key) => { + if (Array.isArray(value)) return value.forEach(item => walk(item, element, key)); + if (value && typeof value === 'object') { + if (isAnchor(value)) return; + const here = typeof value.id === 'string' ? `${view} ${value.id}` : element; + for (const [name, item] of Object.entries(value)) if (!SKIP.has(name)) walk(item, here, name); + } else if (typeof value === 'string' && /\p{L}/u.test(value)) texts.push({ element, key, text: value }); + }; + walk(graph, `${view} meta`, ''); + return texts; +} + +function methodSpan(lines, name) { + const definition = new RegExp(`^\\s*(public|private|protected|static|final|\\s)*[\\w<>\\[\\],.? ]+\\s+${name}\\s*\\([^;]*$`); + const start = lines.findIndex(line => definition.test(line) && !/^\s*(return|new)\b/.test(line)); + if (start < 0) return null; + let depth = 0, opened = false; + for (let i = start; i < lines.length; i++) { + for (const char of lines[i]) { if (char === '{') { depth++; opened = true; } else if (char === '}') depth--; } + if (opened && depth === 0) return [start + 1, i + 1]; + } + return null; +} + +/** + * graphs: the views; anchors: [{ source, label, graphIndex, element }] for every node/edge/section/badge anchor; + * read(file) -> current lines; term(symbol) -> the word an anchor's symbol is checked by. + * Returns null when no view has a baseline, else { files, realigned, alarms, moves, unchecked }. + * moves maps an anchor object to its new { lineStart, lineEnd }; alarms are grouped per changed hunk. + */ +export function detectDrift(graphs, { repoRoot, anchors, read, term }) { + const based = anchors.filter(({ source, graphIndex }) => typeof graphs[graphIndex]?.meta?.sourceFiles?.[source.file] === 'string'); + if (!based.length || git(repoRoot, ['rev-parse', '--is-inside-work-tree']).status !== 0) return null; + const current = fingerprintFiles(repoRoot, [...new Set(based.map(({ source }) => source.file))]) ?? {}; + const diffs = new Map(), unchecked = new Set(); + const diffOf = (graphIndex, file) => { + const blob = graphs[graphIndex].meta.sourceFiles[file]; + if (blob === current[file]) return { hunks: [], before: null }; + const key = `${blob}:${file}`; + if (!diffs.has(key)) diffs.set(key, fileDiff(repoRoot, blob, file)); + if (!diffs.get(key)) unchecked.add(`${file} (${blob.slice(0, 7)})`); + return diffs.get(key); + }; + const views = graphs.map((graph, i) => graph?.meta?.viewId ?? graph?.meta?.diagramType ?? `view ${i + 1}`); + const texts = graphs.flatMap((graph, i) => textsOf(graph, views[i])); + const scope = [...new Set(anchors.map(({ source }) => source.file))]; + const scopeText = new Map(), scopeOf = file => { if (!scopeText.has(file)) { try { scopeText.set(file, read(file).join('\n')); } catch { scopeText.set(file, ''); } } return scopeText.get(file); }; + const terms = new Set(anchors.map(({ source }) => term(source.symbol ?? '')).filter(name => name && (name.length >= 6 || /[A-Z_]/.test(name.slice(1))))); + const receivers = new Set(scope.map(file => path.basename(file).replace(/\.\w+$/, '').toLowerCase())); + const alarms = new Map(), moves = new Map(), held = new Map(), reported = new Set(); + const alarm = (file, hunk, kind) => { + const key = `${file}#${hunk.oldStart}`; + if (!alarms.has(key)) alarms.set(key, { file, oldLine: hunk.oldStart, newLine: hunk.newStart, kinds: new Set(), removed: hunk.removed.filter(isCode).map(line => line.trim()), added: hunk.added.filter(isCode).map(line => line.trim()), anchors: new Set(), mentions: new Set() }); + const item = alarms.get(key); item.kinds.add(kind); return item; + }; + const mention = (item, test) => { for (const t of texts) if (test(t.text) && !reported.has(t)) { reported.add(t); item.mentions.add(`${t.element}${t.key ? ` ${t.key}` : ''}: "${[...t.text].slice(0, 80).join('')}"`); } }; + let realigned = 0; + + // Rules 1-2: carry every anchor to its new lines; an anchor whose own line was rewritten is a change to report. + for (const anchor of based) { + const { source } = anchor, diff = diffOf(anchor.graphIndex, source.file); + if (!diff) continue; + const end = source.lineEnd ?? source.lineStart, container = end - source.lineStart > 3; + const start = mapLine(diff.hunks, source.lineStart), last = mapLine(diff.hunks, end); + const rewritten = !container && Array.from({ length: end - source.lineStart + 1 }, (_, i) => mapLine(diff.hunks, source.lineStart + i)).find(result => result.hunk); + if (rewritten) { + const { hunk } = rewritten, item = alarm(source.file, hunk, 'anchored line rewritten'); + item.anchors.add(`${anchor.element}${source.symbol ? ` (${source.symbol})` : ''}`); + const added = hunk.added.join('\n'); + for (const value of new Set(hunk.removed.join('\n').match(/(? numberIn(value).test(text)); + const lineStart = Math.max(1, hunk.newStart + Math.min(source.lineStart - hunk.oldStart, Math.max(0, hunk.newCount - 1))); + moves.set(source, { lineStart, lineEnd: source.lineEnd === undefined ? undefined : lineStart + end - source.lineStart }); + continue; + } + const lineStart = start.line ?? start.hunk.newStart, lineEnd = source.lineEnd === undefined ? undefined : container ? (last.line ?? last.hunk.newStart + last.hunk.newCount - 1) : lineStart + end - source.lineStart; + if (lineStart !== source.lineStart) realigned++; + moves.set(source, { lineStart, lineEnd }); + if (!container) { const lines = held.get(source.file) ?? new Set(); for (let line = lineStart; line <= (lineEnd ?? lineStart); line++) lines.add(line); held.set(source.file, lines); } + } + + const seen = new Set(); + for (const anchor of based) { + const file = anchor.source.file, diff = diffOf(anchor.graphIndex, file), key = `${graphs[anchor.graphIndex].meta.sourceFiles[file]}:${file}`; + if (!diff?.hunks.length || seen.has(key)) continue; + seen.add(key); + let lines; try { lines = read(file); } catch { continue; } + for (const hunk of diff.hunks) { + // Rule 3: a removed (not renamed) call leaves its target with no caller in the repository. + const addedCalls = new Set(hunk.added.flatMap(callsIn)); + for (const name of new Set(hunk.removed.filter(isCode).flatMap(callsIn))) { + if (addedCalls.has(name) || name.length < 6) continue; + const span = methodSpan(lines, name); + if (!span) continue; + const found = git(repoRoot, ['grep', '-n', '-w', '-F', name]); + const callers = (found.status === 0 ? found.stdout.split('\n') : []).filter(line => word(name).test(line) && new RegExp(`${name}\\s*\\(`).test(line) && !new RegExp(`(public|private|protected)\\b[^;=]*\\b${name}\\s*\\(`).test(line)); + if (callers.length) continue; + const item = alarm(file, hunk, `call removed: ${name}() has no remaining caller`); + for (const other of based) if (other.source.file === file && (other.source.lineEnd ?? other.source.lineStart) - other.source.lineStart <= 3) { + const line = moves.get(other.source)?.lineStart; + if (line >= span[0] && line <= span[1]) item.anchors.add(`${other.element}${other.source.symbol ? ` (${other.source.symbol})` : ''}`); + } + // Names only this method uses (outside it and the imports they never appear) describe what it did. + const body = lines.slice(span[0] - 1, span[1]).join('\n'); + const rest = [...lines.slice(0, span[0] - 1), ...lines.slice(span[1])].filter(line => !/^\s*import\b/.test(line)).join('\n'); + const described = [...new Set([...(body.match(/\b[A-Z][a-z][\w$]{6,}\b/g) ?? []), ...(body.match(/\b[A-Z]{2,}(?:_[A-Z0-9]+)+\b/g) ?? [])])].filter(name2 => !word(name2).test(rest)); + for (const name2 of described) mention(item, text => word(name2).test(text)); + } + // Rule 4: added code that touches what the diagram draws, on lines no anchor covers. + const covered = held.get(file) ?? new Set(); + const touching = hunk.added.map((line, i) => ({ line, number: hunk.newStart + i })).filter(({ line, number }) => isCode(line) && !covered.has(number) + && ([...terms].some(name => word(name).test(line)) || [...line.matchAll(/\b([a-z][\w$]*)\s*\.\s*[\w$]+\s*\(/g)].some(match => receivers.has(match[1].toLowerCase())))); + if (touching.length && !alarms.has(`${file}#${hunk.oldStart}`)) { + const item = alarm(file, hunk, 'new code not covered by the diagram'); + const fresh = new Set(touching.flatMap(({ line }) => line.match(/\b[A-Z]{2,}(?:_[A-Z0-9]+)+\b|\b[a-z][\w$]*[A-Z][\w$]{3,}\b/g) ?? []).filter(name => !word(name).test(diff.before ?? ''))); + for (const name of fresh) mention(item, text => word(name).test(text)); + } + // Rule 5: names gone from the code this diagram covers but still written in it. + const addedText = hunk.added.join('\n'); + for (const name of new Set(hunk.removed.filter(isCode).flatMap(line => line.match(/\b[a-z][\w$]*[A-Z][\w$]*\b/g) ?? []).filter(name => name.length >= 6 && !word(name).test(addedText)))) { + if (scope.some(other => word(name).test(scopeOf(other)))) continue; + const item = alarm(file, hunk, `name no longer in the code: ${name}`); + mention(item, text => word(name).test(text)); + } + } + } + const list = [...alarms.values()].filter(item => item.anchors.size || item.mentions.size || [...item.kinds].some(kind => kind.startsWith('new code') || kind.startsWith('call removed'))) + .map(item => ({ ...item, kinds: [...item.kinds], anchors: [...item.anchors], mentions: [...item.mentions] })); + return { files: new Set(based.map(({ source }) => source.file)).size, realigned, alarms: list, moves, unchecked: [...unchecked] }; +} + +export function formatDrift(alarms) { + return alarms.map(item => [ + `■ ${item.file} line ${item.oldLine} → ${item.newLine}: ${item.kinds.join('; ')}`, + ...item.removed.slice(0, 6).map(line => ` - ${line}`), ...item.added.slice(0, 6).map(line => ` + ${line}`), + ...item.anchors.map(anchor => ` → ${anchor}`), ...item.mentions.map(text => ` → ${text}`) + ].join('\n')).join('\n'); +} + +// The compact form kept in meta.sourceDrift until the author has updated the listed elements. +export const driftItems = alarms => alarms.map(item => ({ + file: item.file, line: item.newLine, change: item.kinds.join('; '), + ...(item.removed.length ? { removed: item.removed.slice(0, 6) } : {}), ...(item.added.length ? { added: item.added.slice(0, 6) } : {}), + ...(item.anchors.length ? { anchors: item.anchors } : {}), ...(item.mentions.length ? { mentions: item.mentions } : {}) +})); diff --git a/skills/q-flow/scripts/source-drift.test.mjs b/skills/q-flow/scripts/source-drift.test.mjs new file mode 100644 index 0000000..c1aa645 --- /dev/null +++ b/skills/q-flow/scripts/source-drift.test.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { collection, repoRoot, source } from '../../../tests/jeepay.mjs'; +import { mapLine, parseHunks } from './source-drift.mjs'; +import { fixGraphFile, stampSourceFiles, verifySourceEvidence } from './validate-graph.mjs'; + +const git = (dir, ...args) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8' }); + +// The Jeepay source files in a fresh repository, and the whole collection stamped against them. +function baseline(t, prepare) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qgraphflow-drift-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + for (const file of Object.keys(source.files)) { const target = path.join(dir, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.copyFileSync(path.join(repoRoot, file), target); } + const graph = structuredClone(collection); + prepare?.(dir, graph); + git(dir, 'init', '-q'); git(dir, 'add', '-A'); git(dir, '-c', 'user.name=drift', '-c', 'user.email=drift@example.invalid', 'commit', '-qm', 'baseline'); + assert.ok(stampSourceFiles(graph, dir).length); + return { dir, graph }; +} +const view = (graph, id) => graph.diagrams.find(item => item.meta.viewId === `jeepay-${id}`); +const site = (graph, id, edgeId) => view(graph, id).edges.find(edge => edge.id === edgeId).site; +const editLine = (dir, file, line, change) => { const p = path.join(dir, file), lines = fs.readFileSync(p, 'utf8').split('\n'); lines[line - 1] = change(lines[line - 1]); fs.writeFileSync(p, lines.join('\n')); }; +const insertAfter = (dir, file, line, text) => { const p = path.join(dir, file), lines = fs.readFileSync(p, 'utf8').split('\n'); lines.splice(line, 0, text); fs.writeFileSync(p, lines.join('\n')); }; + +test('line mapping follows insertions and deletions and stops at rewritten lines', () => { + const hunks = parseHunks('@@ -10,0 +11,3 @@\n+a\n+b\n+c\n@@ -20 +23 @@\n-x\n+y\n@@ -30,2 +33,0 @@\n-p\n-q\n'); + assert.deepEqual(mapLine(hunks, 5), { line: 5 }); + assert.deepEqual(mapLine(hunks, 15), { line: 18 }); + assert.equal(mapLine(hunks, 20).hunk.newStart, 23); + assert.deepEqual(mapLine(hunks, 25), { line: 28 }); + assert.ok(mapLine(hunks, 31).hunk); + assert.deepEqual(mapLine(hunks, 40), { line: 41 }); +}); + +test('a stamped Jeepay collection passes unchanged and records every anchored file', t => { + const { dir, graph } = baseline(t); + for (const item of graph.diagrams) for (const blob of Object.values(item.meta.sourceFiles)) assert.match(blob, /^[0-9a-f]{40}$/); + const evidence = verifySourceEvidence(graph, dir); + assert.equal(evidence.status, 'passed'); + assert.deepEqual(evidence.drift, { files: evidence.drift.files, realigned: 0, alarms: 0 }); +}); + +test('lines that only moved pass and their anchors follow them', t => { + const { dir, graph } = baseline(t), anchor = site(graph, 'sequence', 'm3'), old = anchor.lineStart; + insertAfter(dir, anchor.file, 70, ' // housekeeping comment\n // with no behaviour change\n'); + const evidence = verifySourceEvidence(graph, dir); + assert.equal(evidence.status, 'passed'); + assert.ok(evidence.drift.realigned > 0); + assert.equal(anchor.lineStart, old + 3); +}); + +test('a rewritten anchored line is reported with the elements it carries', t => { + const { dir, graph } = baseline(t), anchor = site(graph, 'sequence', 'm3'); + editLine(dir, anchor.file, anchor.lineStart, line => line.replace('payOrderService.save(', 'payOrderService.saveOrder(')); + assert.throws(() => verifySourceEvidence(graph, dir), error => /Source drift: 1 change/.test(error.message) && /anchored line rewritten/.test(error.message) && /jeepay-sequence m3/.test(error.message) && /\+ payOrderService\.saveOrder\(payOrder\);/.test(error.message)); +}); + +test('a changed number on an anchored line points at the text that still states the old value', t => { + const { dir, graph } = baseline(t, (dir, graph) => { + const anchor = site(graph, 'sequence', 'm4'); + editLine(dir, anchor.file, anchor.lineStart, line => `${line} // channel timeout 30`); + view(graph, 'sequence').edges.find(edge => edge.id === 'm4').label += ' (timeout 30s)'; + }); + const anchor = site(graph, 'sequence', 'm4'); + editLine(dir, anchor.file, anchor.lineStart, line => line.replace('timeout 30', 'timeout 60')); + assert.throws(() => verifySourceEvidence(graph, dir), error => /jeepay-sequence m4 label: ".*timeout 30s/.test(error.message)); +}); + +test('removing the only call to a method reports it as unreachable', t => { + const { dir, graph } = baseline(t), file = 'jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java'; + const lines = fs.readFileSync(path.join(dir, file), 'utf8').split('\n'), call = lines.findIndex(line => line.includes('this.updatePayOrderAutoDivision(payOrder);')); + assert.ok(call > 0); + lines.splice(call, 1); fs.writeFileSync(path.join(dir, file), lines.join('\n')); + assert.throws(() => verifySourceEvidence(graph, dir), /call removed: updatePayOrderAutoDivision\(\) has no remaining caller/); +}); + +test('new code that touches a drawn component is reported when no anchor covers it', t => { + const { dir, graph } = baseline(t), anchor = site(graph, 'sequence', 'm3'); + insertAfter(dir, anchor.file, anchor.lineStart, ' payOrderService.updateIng2Cancel(payOrder.getPayOrderId());'); + assert.throws(() => verifySourceEvidence(graph, dir), /new code not covered by the diagram[\s\S]*updateIng2Cancel/); +}); + +test('--fix realigns, renews the baseline and keeps the change as a worklist until the author clears it', t => { + const { dir, graph } = baseline(t), anchor = site(graph, 'sequence', 'm3'); + insertAfter(dir, anchor.file, 70, ' // housekeeping comment'); + editLine(dir, anchor.file, anchor.lineStart + 1, line => line.replace('payOrderService.save(', 'payOrderService.saveOrder(')); + const file = path.join(dir, 'graph.json'); fs.writeFileSync(file, JSON.stringify(graph)); + const result = fixGraphFile(file, { inputOnly: true, repoRoot: dir }); + assert.deepEqual(result.errors, []); assert.equal(result.written, true); assert.equal(result.drift.length, 1); + const fixed = JSON.parse(fs.readFileSync(file, 'utf8')), sequence = view(fixed, 'sequence'); + assert.equal(sequence.edges.find(edge => edge.id === 'm3').site.lineStart, anchor.lineStart + 1); + assert.equal(sequence.meta.sourceDrift[0].file, anchor.file); + assert.equal(sequence.meta.sourceFiles[anchor.file], git(dir, 'hash-object', anchor.file).trim()); + assert.throws(() => verifySourceEvidence(fixed, dir), /Unresolved source drift/); + for (const item of fixed.diagrams) delete item.meta.sourceDrift; + assert.equal(verifySourceEvidence(fixed, dir).status, 'passed'); +}); + +test('graphs without a baseline keep the working-tree check unchanged', t => { + const { dir } = baseline(t), graph = structuredClone(collection); + const evidence = verifySourceEvidence(graph, dir); + assert.equal(evidence.status, 'passed'); assert.equal(evidence.drift, undefined); +}); + +test('a baseline missing from the repository falls back to the working-tree check with a warning', t => { + const { dir, graph } = baseline(t), warn = t.mock.method(console, 'warn', () => {}); + for (const item of graph.diagrams) for (const file of Object.keys(item.meta.sourceFiles)) item.meta.sourceFiles[file] = '0'.repeat(40); + const anchor = site(graph, 'sequence', 'm3'); + insertAfter(dir, anchor.file, 70, ' // housekeeping comment'); + assert.equal(verifySourceEvidence(graph, dir).status, 'passed'); + assert.ok(warn.mock.calls.some(call => /fetch-depth: 0/.test(call.arguments[0]))); +}); diff --git a/skills/q-flow/scripts/validate-graph.mjs b/skills/q-flow/scripts/validate-graph.mjs index b8f5dc0..506626a 100644 --- a/skills/q-flow/scripts/validate-graph.mjs +++ b/skills/q-flow/scripts/validate-graph.mjs @@ -12,16 +12,18 @@ import { graphsOf, needsSite, overviewWarnings, reviewComposition, validateGraph import { requireDiagramQuality, qualityFailure } from '../assets/viewer/src/layout-quality.js'; import { operandScopes } from '../assets/viewer/src/sequence-fragments.js'; import { callsMissingExecutions } from '../assets/viewer/src/sequence-executions.js'; +import { detectDrift, driftItems, fingerprintFiles, formatDrift } from './source-drift.mjs'; export { DIAGRAM_TYPES, diagramTypeOf } from '../assets/viewer/src/diagrams/registry.js'; export { graphsOf, reviewComposition, validateGraph, validateGraphInput } from '../assets/viewer/src/graph-validation.js'; const USAGE = `Usage: node validate-graph.mjs [options] --input-only check semantics only (no geometry); use before generating - --repo-root verify every node source and edge site (file, line range, symbol) against this working tree + --repo-root verify every node source and edge site (file, line range, symbol) against this working tree; + with meta.sourceFiles, lines that only moved pass and changed code is reported as source drift --fix repair mechanical errors in place (sequence order numbering, opt/loop/par operand ids, unambiguous replyTo, the callee activation bar of each answered sync call; with --repo-root, - anchor line re-anchoring to a symbol found once in its file); prints each change; writes back - only when the graph then passes + anchors follow moved lines, source drift is listed in meta.sourceDrift and meta.sourceFiles is + renewed); prints each change; writes back only when the graph then passes --verbose print the full receipt (layout composition, diagnostics) instead of one summary line -h, --help this text Success prints one JSON line; failure prints the failing elements with rule, measurement and remediation. @@ -141,7 +143,7 @@ export function fixGraphFile(inputPath, { repoRoot, ...options } = {}) { const absolute = path.resolve(inputPath); const original = fs.readFileSync(absolute, 'utf8'); const graph = JSON.parse(original); - const mechanical = applyMechanicalFixes(graph), anchors = repoRoot === undefined ? { changes: [], blocked: [] } : applyAnchorFixes(graph, repoRoot); + const mechanical = applyMechanicalFixes(graph), anchors = repoRoot === undefined ? { changes: [], blocked: [], drift: [], exempt: new Set() } : applyAnchorFixes(graph, repoRoot); const changes = [...mechanical.changes, ...anchors.changes], blocked = [...mechanical.blocked, ...anchors.blocked]; let errors = validateGraphInput(graph, { ...options, inputOnly: true }); if (!errors.length && !options.inputOnly) errors = validateGraphInput(graph, options); @@ -149,25 +151,82 @@ export function fixGraphFile(inputPath, { repoRoot, ...options } = {}) { const prefix = Object.hasOwn(graph, 'diagrams') ? `diagrams[${index}].` : ''; try { requireDiagramQuality(item); } catch (error) { errors.push(...error.message.split('\n- ').slice(1).map(message => prefix + message)); } } + // The listed drift is the author's work, not a reason to keep the realigned anchors and fresh baseline unwritten. if (!errors.length && repoRoot !== undefined) { - try { verifySourceEvidence(graph, repoRoot); } catch (error) { errors = error.message.split('\n- ').slice(1); } + try { verifySourceEvidence(graph, repoRoot, { pendingDrift: 'allow', exempt: anchors.exempt }); } catch (error) { errors = error.message.split('\n- ').slice(1); } } - if (errors.length) return { changes, blocked, errors, written: false }; + if (errors.length) return { changes, blocked, errors, written: false, drift: anchors.drift }; + if (repoRoot !== undefined) changes.push(...stampSourceFiles(graph, repoRoot)); const text = `${JSON.stringify(graph, null, 2)}\n`; const written = changes.length > 0 && text !== original; if (written) fs.writeFileSync(absolute, text); - return { changes, blocked, errors: [], written }; + return { changes, blocked, errors: [], written, drift: anchors.drift }; } -// Re-anchors a drifted node source or edge site whose symbol occurs exactly once in its file; the range moves with it and keeps its span. -// Several matches need a judgement about which one is the definition, so they are only reported. +// Every node, edge, overview-section and badge anchor, with the view and element that own it. +export function sourceAnchors(input) { + return graphsOf(input).flatMap((graph, graphIndex) => { + const view = graph?.meta?.viewId ?? graph?.meta?.diagramType ?? `view ${graphIndex + 1}`; + return [ + ...overviewSections(graph).flatMap(section => section.source ? [{ source: section.source, label: `diagrams[${graphIndex}].sections.${section.id}.source`, graphIndex, element: `${view} ${section.id}` }] : []), + ...graph.nodes.flatMap((node, nodeIndex) => (node.badges ?? []).flatMap((badge, i) => badge.source ? [{ source: badge.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].badges[${i}].source`, graphIndex, element: `${view} ${node.id} badge` }] : [])), + ...graph.nodes.flatMap((node, nodeIndex) => node.source ? [{ source: node.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].source`, graphIndex, element: `${view} ${node.id}` }] : []), + ...(graph.edges ?? []).flatMap((edge, edgeIndex) => edge.site ? [{ source: edge.site, label: `diagrams[${graphIndex}].edges[${edgeIndex}].site`, graphIndex, element: `${view} ${edge.id}` }] : [])]; + }); +} + +// Records the content each view's anchors now point at (git blob hashes, nothing written to the repository), so a +// later check can tell lines that moved from code that changed. Outside a git work tree nothing is recorded. +export function stampSourceFiles(input, repoRoot) { + const changes = []; + graphsOf(input).forEach((graph, graphIndex) => { + const files = [...new Set(sourceAnchors(graph).map(({ source }) => source.file))].sort(); + const stamp = fingerprintFiles(repoRoot, files); + if (!stamp || JSON.stringify(stamp) === JSON.stringify(graph.meta.sourceFiles)) return; + graph.meta.sourceFiles = stamp; + changes.push(`${Object.hasOwn(input, 'diagrams') ? `diagrams[${graphIndex}].` : ''}meta.sourceFiles → ${files.length} file${files.length === 1 ? '' : 's'}`); + }); + return changes; +} + +// With a baseline (meta.sourceFiles) anchors follow the diff to their new lines and every change the diagram must +// reflect goes to meta.sourceDrift; the rewritten anchors it names are exempt until the author updates them. +// Without one, a drifted node source or edge site whose symbol occurs exactly once in its file is re-anchored; the +// range moves with it and keeps its span. Several matches need a judgement about which one is the definition, so they are only reported. export function applyAnchorFixes(input, repoRoot) { - const changes = [], blocked = [], { read } = sourceReader(repoRoot); - for (const [index, graph] of graphsOf(input).entries()) { + const changes = [], blocked = [], { read } = sourceReader(repoRoot), graphs = graphsOf(input), all = sourceAnchors(input); + const drift = detectDrift(graphs, { repoRoot, anchors: all, read, term: symbolTerm }); + const moved = new Set(), exempt = new Set(); + if (drift) { + for (const { source, label } of all) { + const to = drift.moves.get(source); + if (!to) continue; + moved.add(source); + if (to.lineStart === source.lineStart && (to.lineEnd ?? source.lineEnd) === source.lineEnd) continue; + changes.push(`${label}.lineStart ${source.lineStart} → ${to.lineStart}${to.lineEnd === undefined ? '' : `, lineEnd ${source.lineEnd} → ${to.lineEnd}`}`); + source.lineStart = to.lineStart; + if (to.lineEnd !== undefined) source.lineEnd = to.lineEnd; + } + for (const item of drift.alarms) for (const anchor of all) if (item.anchors.some(text => text === anchor.element || text.startsWith(`${anchor.element} (`))) exempt.add(anchor.label); + if (drift.alarms.length) { + // Each view keeps the items that name one of its elements, or that touch a file it anchors. + const items = driftItems(drift.alarms); + graphs.forEach((graph, graphIndex) => { + const view = graph.meta.viewId ?? graph.meta.diagramType ?? `view ${graphIndex + 1}`; + const files = new Set(all.filter(anchor => anchor.graphIndex === graphIndex).map(({ source }) => source.file)); + const own = items.filter(item => [...(item.anchors ?? []), ...(item.mentions ?? [])].some(text => text.startsWith(`${view} `)) || files.has(item.file)); + if (!own.length) return; + graph.meta.sourceDrift = [...(graph.meta.sourceDrift ?? []), ...own]; + changes.push(`${Object.hasOwn(input, 'diagrams') ? `diagrams[${graphIndex}].` : ''}meta.sourceDrift + ${own.length} item${own.length === 1 ? '' : 's'}`); + }); + } + for (const file of drift.unchecked) blocked.push(`source drift not checked for ${file}: baseline not in this repository (fetch full history, e.g. fetch-depth: 0)`); + } + for (const [index, graph] of graphs.entries()) { const prefix = Object.hasOwn(input, 'diagrams') ? `diagrams[${index}].` : ''; for (const [kind, key, items] of [['node', 'source', graph?.nodes], ['edge', 'site', graph?.edges]]) for (const item of Array.isArray(items) ? items : []) { const anchor = item?.[key]; - if (typeof anchor?.symbol !== 'string' || !Number.isInteger(anchor.lineStart)) continue; + if (typeof anchor?.symbol !== 'string' || !Number.isInteger(anchor.lineStart) || moved.has(anchor)) continue; let lines; try { lines = read(anchor.file); } catch { continue; } // reported by the source evidence check const term = symbolTerm(anchor.symbol), found = term ? symbolLines(lines, term) : []; @@ -179,7 +238,7 @@ export function applyAnchorFixes(input, repoRoot) { if (lineEnd !== undefined) anchor.lineEnd = lineEnd; } } - return { changes, blocked }; + return { changes, blocked, drift: drift?.alarms ?? [], exempt }; } // ponytail: a whole-word text match on the symbol's last segment, not a definition parser. A mention left inside the @@ -219,13 +278,13 @@ function sourceReader(repoRoot) { // Checks the explicitly selected working tree, not the revision named in sourceRef or the meaning of a claim. // `relations` counts the edges that should record a site, so a delivery can say how much of the diagram is traceable. -export function verifySourceEvidence(input, repoRoot) { +// With meta.sourceFiles, anchors first follow the lines they moved with (in memory; generation writes them out) and +// changed code fails as source drift; unresolved meta.sourceDrift items fail until the author removes them. +export function verifySourceEvidence(input, repoRoot, { pendingDrift = 'fail', exempt = new Set() } = {}) { const graphs = graphsOf(input), edges = graphs.flatMap(graph => graph.edges ?? []); - const anchors = graphs.flatMap((graph, graphIndex) => [ - ...overviewSections(graph).flatMap(section => section.source ? [{ source: section.source, label: `diagrams[${graphIndex}].sections.${section.id}.source` }] : []), - ...graph.nodes.flatMap((node, nodeIndex) => (node.badges ?? []).flatMap((badge, i) => badge.source ? [{ source: badge.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].badges[${i}].source` }] : [])), - ...graph.nodes.flatMap((node, nodeIndex) => node.source ? [{ source: node.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].source` }] : []), - ...(graph.edges ?? []).flatMap((edge, edgeIndex) => edge.site ? [{ source: edge.site, label: `diagrams[${graphIndex}].edges[${edgeIndex}].site` }] : [])]); + const anchors = sourceAnchors(input); + const pending = graphs.flatMap((graph, index) => (Array.isArray(graph.meta?.sourceDrift) ? graph.meta.sourceDrift : []).map(item => `diagrams[${index}].meta.sourceDrift: ${item?.file ?? '?'} line ${item?.line ?? '?'} — ${item?.change ?? ''}`)); + if (pending.length && pendingDrift === 'fail') throw new Error(`Unresolved source drift: update the elements each item names to match the current code, then delete the item:\n- ${pending.join('\n- ')}`); const summary = { scope: 'working-tree', references: anchors.length, checked: 0, files: 0, relations: { sited: edges.filter(edge => needsSite(edge) && edge.site).length, eligible: edges.filter(needsSite).length } }; if (repoRoot === undefined) { @@ -233,8 +292,15 @@ export function verifySourceEvidence(input, repoRoot) { return { ...summary, status: anchors.length ? 'skipped' : 'not-applicable', ...(anchors.length ? { reason: 'repository-root-not-provided' } : {}) }; } const { read, files } = sourceReader(repoRoot), errors = []; + const drift = pendingDrift === 'fail' ? detectDrift(graphs, { repoRoot, anchors, read, term: symbolTerm }) : null; + if (drift) { + for (const file of drift.unchecked) console.warn(`Source drift not checked for ${file}: its baseline is not in this repository (fetch full history, e.g. actions/checkout fetch-depth: 0); checking the working tree only.`); + if (drift.alarms.length) throw new Error(`Source drift: ${drift.alarms.length} change${drift.alarms.length === 1 ? '' : 's'} since this diagram's meta.sourceFiles baseline${drift.realigned ? ` (${drift.realigned} anchors only moved and follow their lines)` : ''}. Run validate --fix --repo-root to realign and list them in meta.sourceDrift, then update the named elements.\n${formatDrift(drift.alarms)}`); + for (const { source } of anchors) { const to = drift.moves.get(source); if (to) { source.lineStart = to.lineStart; if (to.lineEnd !== undefined) source.lineEnd = to.lineEnd; } } + } let symbols = 0; for (const { source, label } of anchors) { + if (exempt.has(label)) continue; try { const lines = read(source.file), end = source.lineEnd ?? source.lineStart; if (end > lines.length) throw new Error(`line ${end} exceeds file length (${lines.length} lines)`); @@ -249,7 +315,8 @@ export function verifySourceEvidence(input, repoRoot) { } catch (error) { errors.push(`${label} (${source.file}): ${error.code === 'ENOENT' ? 'file does not exist' : error.message}`); } } if (errors.length) throw new Error(`Invalid source evidence:\n- ${errors.join('\n- ')}`); - return { ...summary, status: anchors.length ? 'passed' : 'not-applicable', checked: anchors.length, files: files.size, symbols }; + return { ...summary, status: anchors.length ? 'passed' : 'not-applicable', checked: anchors.length, files: files.size, symbols, + ...(drift ? { drift: { files: drift.files, realigned: drift.realigned, alarms: 0 } } : {}) }; } if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) { @@ -261,6 +328,7 @@ if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process const result = fixGraphFile(positionals[0], { inputOnly: values['input-only'], repoRoot: values['repo-root'] }); for (const change of result.changes) console.error(`fixed: ${change}`); for (const item of result.blocked) console.error(`not fixed: ${item}`); + if (result.drift.length) console.error(`source drift listed in meta.sourceDrift (update these elements, then delete each item):\n${formatDrift(result.drift)}`); if (result.errors.length) throw new Error(`Invalid graph after mechanical fixes (file left unchanged):\n- ${result.errors.join('\n- ')}`); const file = path.resolve(positionals[0]), directory = path.dirname(file); if (result.written) console.error(`wrote ${file} (${result.changes.length} change${result.changes.length === 1 ? '' : 's'})`); From c039264b9aa442957dcb9edda63219f1da44bec8 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 02:11:42 +0800 Subject: [PATCH 02/16] =?UTF-8?q?feat:=20=E6=9E=84=E5=9B=BE=E4=BA=A4?= =?UTF-8?q?=E7=BB=99=E6=A8=A1=E5=9E=8B=E2=80=94=E2=80=94=E5=90=8C=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E5=A4=9A=E8=A7=86=E5=9B=BE=E3=80=81=E5=85=B3=E7=B3=BB?= =?UTF-8?q?=E8=A7=86=E5=9B=BE=E5=B0=8F=E6=A0=87=E7=AD=BE=E4=B8=8E=E6=8A=98?= =?UTF-8?q?=E5=8F=A0=E5=85=AC=E5=85=B1=E4=BE=9D=E8=B5=96=E3=80=81rank=20?= =?UTF-8?q?=E5=88=86=E6=A0=8F=EF=BC=8C=E4=BF=AE=E5=A4=8D=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E5=9B=BE=E8=87=AA=E8=BD=AC=E7=A7=BB=E5=B8=83=E5=B1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 合集里任意类型可重复,重复视图须写唯一 meta.viewId,时序图可在同一合集按阶段拆分 - 关系与部署卡片在源码行下显示 badges;只有 badges 不再变成概览卡 - layout.sharedDependencies:指向共享依赖的边不画线,改为调用方卡片上的"→ 名称"标签; 边、出处与漂移检查保留,详情栏可点开;Node 与浏览器排版先排展示图再还原 - 自转移标签计入模板列距且不受 240 上限;带长自转移的状态按标签加高 - 文档:rank 配合 direction right 可做阅读分栏;技能说明提示拆同类型视图或折叠公共依赖 - 新增 5 个测试;重建 viewer-dist;界面新增"公共依赖"文案(8 种语言) --- skills/q-flow/SKILL.md | 2 +- skills/q-flow/assets/viewer-dist/index.html | 24 +++---- .../assets/viewer/src/DiagramCanvas.jsx | 6 +- .../q-flow/assets/viewer/src/TextEditor.jsx | 2 +- .../q-flow/assets/viewer/src/ViewerShell.jsx | 2 + .../viewer/src/architecture-overview.js | 3 +- .../q-flow/assets/viewer/src/diagrams/card.js | 6 +- .../assets/viewer/src/graph-validation.js | 17 +++-- .../assets/viewer/src/i18n-messages.json | 24 ++++--- .../viewer/src/layout-browser-worker.js | 7 ++- .../assets/viewer/src/layout-templates.js | 25 ++++++-- .../assets/viewer/src/presentation-graph.js | 37 ++++++++++- .../q-flow/assets/viewer/src/session-graph.js | 5 +- skills/q-flow/assets/viewer/src/styles.css | 2 + .../q-flow/assets/viewer/src/text-layout.js | 22 ++++++- .../q-flow/assets/viewer/src/view-identity.js | 2 +- .../q-flow/assets/viewer/src/visual-style.js | 2 +- skills/q-flow/references/graph-common.md | 4 +- skills/q-flow/references/graph-schema.md | 4 +- skills/q-flow/references/guided-intake.md | 2 +- .../q-flow/references/types/architecture.md | 4 +- skills/q-flow/scripts/compile-layout.mjs | 12 +++- .../scripts/composition-review.test.mjs | 62 +++++++++++++++++++ skills/q-flow/scripts/state-notation.test.mjs | 13 ++++ 24 files changed, 233 insertions(+), 56 deletions(-) diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index d37f7ec..e713e1f 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -47,7 +47,7 @@ node scripts/validate-graph.mjs "/graph.json" --repo- - Execute the scripts; do not read them, the bundled HTML, the Viewer source or tests. `--help` lists every option. Failures report elements, rule, measurement and remediation; `--verbose` prints the receipt. - On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and moved anchors, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. -- Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: apply the common contract's view-splitting rules while preserving requested detail and graph count. A failing collection names every failing view. +- Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: split into same-type views or fold shared dependencies; keep requested detail and graph count. A failing collection names every failing view. - If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. Generation defaults to `--layout auto`; `--layout preserve` keeps existing geometry under the same gate. - For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local files (existence, line range, symbol) and report `sourceEvidence` with `relations` coverage. Generation records `meta.sourceFiles`: moved lines pass, changed code fails as drift. Neither proves a claim. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. - Outputs are `index.html`, `graph.json` and one SVG per view (`diagram.svg`, or `diagram--.svg` in a collection), built from the prebuilt viewer; no rebuild or install. Use `--force` only with approval to replace the named outputs. All collection views must pass before replacing output. diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index ef919be..1173dfa 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -227,14 +227,14 @@ `);for(i=r=0;ri||c[r]!==l[i]){var u=` `+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{me=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?pe(n):``}function ge(e,t){switch(e.tag){case 26:case 27:case 5:return pe(e.type);case 16:return pe(`Lazy`);case 13:return e.child!==t&&t!==null?pe(`Suspense Fallback`):pe(`Suspense`);case 19:return pe(`SuspenseList`);case 0:case 15:return he(e.type,!1);case 11:return he(e.type.render,!1);case 1:return he(e.type,!0);case 31:return pe(`Activity`);default:return``}}function _e(e){try{var t=``,n=null;do t+=ge(e,n),n=e,e=e.return;while(e);return t}catch(e){return` Error generating stack: `+e.message+` -`+e.stack}}var ve=Object.prototype.hasOwnProperty,ye=t.unstable_scheduleCallback,be=t.unstable_cancelCallback,xe=t.unstable_shouldYield,Se=t.unstable_requestPaint,Ce=t.unstable_now,we=t.unstable_getCurrentPriorityLevel,Te=t.unstable_ImmediatePriority,Ee=t.unstable_UserBlockingPriority,De=t.unstable_NormalPriority,Oe=t.unstable_LowPriority,ke=t.unstable_IdlePriority,Ae=t.log,je=t.unstable_setDisableYieldValue,Me=null,Ne=null;function Pe(e){if(typeof Ae==`function`&&je(e),Ne&&typeof Ne.setStrictMode==`function`)try{Ne.setStrictMode(Me,e)}catch{}}var Fe=Math.clz32?Math.clz32:Re,Ie=Math.log,Le=Math.LN2;function Re(e){return e>>>=0,e===0?32:31-(Ie(e)/Le|0)|0}var ze=256,Be=262144,Ve=4194304;function He(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ue(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=He(n))):i=He(o):i=He(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=He(n))):i=He(o)):i=He(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function We(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ge(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ke(){var e=Ve;return Ve<<=1,!(Ve&62914560)&&(Ve=4194304),e}function qe(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Je(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ye(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),cn=!1;if(sn)try{var ln={};Object.defineProperty(ln,"passive",{get:function(){cn=!0}}),window.addEventListener(`test`,ln,ln),window.removeEventListener(`test`,ln,ln)}catch{cn=!1}var un=null,dn=null,fn=null;function pn(){if(fn)return fn;var e,t=dn,n=t.length,r,i=`value`in un?un.value:un.textContent,a=i.length;for(e=0;e=Gn),Jn=` `,Yn=!1;function Xn(e,t){switch(e){case`keyup`:return Un.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Zn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Qn=!1;function $n(e,t){switch(e){case`compositionend`:return Zn(t);case`keypress`:return t.which===32?(Yn=!0,Jn):null;case`textInput`:return e=t.data,e===Jn&&Yn?null:e;default:return null}}function er(e,t){if(Qn)return e===`compositionend`||!Wn&&Xn(e,t)?(e=pn(),fn=dn=un=null,Qn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Sr(n)}}function wr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Tr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Pt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Pt(e.document)}return t}function Er(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Dr=sn&&`documentMode`in document&&11>=document.documentMode,Or=null,kr=null,Ar=null,jr=!1;function Mr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;jr||Or==null||Or!==Pt(r)||(r=Or,`selectionStart`in r&&Er(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ar&&xr(Ar,r)||(Ar=r,r=Ad(kr,`onSelect`),0>=o,i-=o,wi=1<<32-Fe(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),V&&Ei(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),V&&Ei(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return V&&Ei(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),V&&Ei(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&Ea(l)===r.type){n(e,r.sibling),c=a(r,o.props),Ma(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=di(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ui(o.type,o.key,o.props,null,e.mode,c),Ma(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=mi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=Ea(o),b(e,r,o,c)}if(ee(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,ja(o),c);if(o.$$typeof===C)return b(e,r,ea(e,o),c);Na(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=fi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Aa=0;var i=b(e,t,n,r);return ka=null,i}catch(t){if(t===ba||t===Sa)throw t;var a=oi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Fa=Pa(!0),Ia=Pa(!1),La=!1;function Ra(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function za(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ba(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Va(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,zl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ri(e),ni(e,null,n),t}return $r(e,r,t,n),ri(e)}function Ha(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}function Ua(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Wa=!1;function Ga(){if(Wa){var e=da;if(e!==null)throw e}}function Ka(e,t,n,r){Wa=!1;var i=e.updateQueue;La=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(q&f)===f:(r&f)===f){f!==0&&f===ua&&(Wa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:La=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Jl|=o,e.lanes=o,e.memoizedState=d}}function qa(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Ja(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=F.T,s={};F.T=s,Ns(e,!1,t,n);try{var c=i(),l=F.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ms(e,t,ma(c,r),gu(e)):Ms(e,t,r,gu(e))}catch(n){Ms(e,t,{then:function(){},status:`rejected`,reason:n},gu())}finally{I.p=a,o!==null&&s.types!==null&&(o.types=s.types),F.T=o}}function Ss(){}function Cs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=ws(e).queue;xs(e,a,t,te,n===null?Ss:function(){return Ts(e),n(r)})}function ws(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:te,baseState:te,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:te},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ts(e){var t=ws(e);t.next===null&&(t=e.alternate.memoizedState),Ms(e,t.next.queue,{},gu())}function Es(){return $i(tp)}function Ds(){return ko().memoizedState}function Os(){return ko().memoizedState}function ks(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=gu();e=Ba(n);var r=Va(t,e,n);r!==null&&(vu(r,t,n),Ha(r,t,n)),t={cache:oa()},e.payload=t;return}t=t.return}}function As(e,t,n){var r=gu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ps(e)?Fs(t,n):(n=ei(e,t,n,r),n!==null&&(vu(n,e,r),Is(n,t,r)))}function js(e,t,n){Ms(e,t,n,gu())}function Ms(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ps(e))Fs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,br(s,o))return $r(e,t,i,0),Bl===null&&Qr(),!1}catch{}if(n=ei(e,t,i,r),n!==null)return vu(n,e,r),Is(n,t,r),!0}return!1}function Ns(e,t,n,r){if(r={lane:2,revertLane:hd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ps(e)){if(t)throw Error(i(479))}else t=ei(e,n,r,2),t!==null&&vu(t,e,2)}function Ps(e){var t=e.alternate;return e===U||t!==null&&t===U}function Fs(e,t){po=fo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Is(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}var Ls={readContext:$i,use:Mo,useCallback:yo,useContext:yo,useEffect:yo,useImperativeHandle:yo,useLayoutEffect:yo,useInsertionEffect:yo,useMemo:yo,useReducer:yo,useRef:yo,useState:yo,useDebugValue:yo,useDeferredValue:yo,useTransition:yo,useSyncExternalStore:yo,useId:yo,useHostTransitionStatus:yo,useFormState:yo,useActionState:yo,useOptimistic:yo,useMemoCache:yo,useCacheRefresh:yo};Ls.useEffectEvent=yo;var Rs={readContext:$i,use:Mo,useCallback:function(e,t){return Oo().memoizedState=[e,t===void 0?null:t],e},useContext:$i,useEffect:cs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),os(4194308,4,ms.bind(null,t,e),n)},useLayoutEffect:function(e,t){return os(4194308,4,e,t)},useInsertionEffect:function(e,t){os(4,2,e,t)},useMemo:function(e,t){var n=Oo();t=t===void 0?null:t;var r=e();if(mo){Pe(!0);try{e()}finally{Pe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Oo();if(n!==void 0){var i=n(t);if(mo){Pe(!0);try{n(t)}finally{Pe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=As.bind(null,U,e),[r.memoizedState,e]},useRef:function(e){var t=Oo();return e={current:e},t.memoizedState=e},useState:function(e){e=Wo(e);var t=e.queue,n=js.bind(null,U,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:gs,useDeferredValue:function(e,t){return ys(Oo(),e,t)},useTransition:function(){var e=Wo(!1);return e=xs.bind(null,U,e.queue,!0,!1),Oo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=U,a=Oo();if(V){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Bl===null)throw Error(i(349));q&127||zo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,cs(Vo.bind(null,r,o,e),[e]),r.flags|=2048,is(9,{destroy:void 0},Bo.bind(null,r,o,n,t),null),n},useId:function(){var e=Oo(),t=Bl.identifierPrefix;if(V){var n=Ti,r=wi;n=(r&~(1<<32-Fe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ho++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[it]=t,o[at]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(zd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&jc(t)}}return Ic(t),Mc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&jc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ae.current,zi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=ji,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[it]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Id(e.nodeValue,n)),e||Ii(t,!0)}else e=Gd(e).createTextNode(r),e[it]=t,t.stateNode=e}return Ic(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=zi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[it]=t}else Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ic(t),e=!1}else n=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(oo(t),t):(oo(t),null);if(t.flags&128)throw Error(i(558))}return Ic(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=zi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[it]=t}else Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ic(t),a=!1}else a=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(oo(t),t):(oo(t),null)}return oo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Pc(t,t.updateQueue),Ic(t),null);case 4:return ce(),e===null&&Ed(t.stateNode.containerInfo),Ic(t),null;case 10:return qi(t.type),Ic(t),null;case 19:if(z(so),r=t.memoizedState,r===null)return Ic(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Fc(r,!1);else{if(ql!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=co(e),o!==null){for(t.flags|=128,Fc(r,!1),e=o.updateQueue,t.updateQueue=e,Pc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)li(n,e),n=n.sibling;return B(so,so.current&1|2),V&&Ei(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ce()>iu&&(t.flags|=128,a=!0,Fc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=co(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Pc(t,e),Fc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!V)return Ic(t),null}else 2*Ce()-r.renderingStartTime>iu&&n!==536870912&&(t.flags|=128,a=!0,Fc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Ic(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ce(),e.sibling=null,n=so.current,B(so,a?n&1|2:n&1),V&&Ei(t,r.treeForkCount),e);case 22:case 23:return oo(t),$a(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Ic(t),t.subtreeFlags&6&&(t.flags|=8192)):Ic(t),n=t.updateQueue,n!==null&&Pc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&z(ga),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),qi(aa),Ic(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Rc(e,t){switch(ki(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return qi(aa),ce(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return ue(t),null;case 31:if(t.memoizedState!==null){if(oo(t),t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(oo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return z(so),null;case 4:return ce(),null;case 10:return qi(t.type),null;case 22:case 23:return oo(t),$a(),e!==null&&z(ga),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return qi(aa),null;case 25:return null;default:return null}}function zc(e,t){switch(ki(t),t.tag){case 3:qi(aa),ce();break;case 26:case 27:case 5:ue(t);break;case 4:ce();break;case 31:t.memoizedState!==null&&oo(t);break;case 13:oo(t);break;case 19:z(so);break;case 10:qi(t.type);break;case 22:case 23:oo(t),$a(),e!==null&&z(ga);break;case 24:qi(aa)}}function Bc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Ju(t,t.return,e)}}function Vc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Ju(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Ju(t,t.return,e)}}function Hc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ja(t,n)}catch(t){Ju(e,e.return,t)}}}function Uc(e,t,n){n.props=Gs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Ju(e,t,n)}}function Wc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Ju(e,t,n)}}function Gc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Ju(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Ju(e,t,n)}else n.current=null}}function Kc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Ju(e,e.return,t)}}function qc(e,t,n){try{var r=e.stateNode;Bd(r,e.type,n,t),r[at]=t}catch(t){Ju(e,e.return,t)}}function Jc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&nf(e.type)||e.tag===4}function Yc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Jc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&nf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Zt));else if(r!==4&&(r===27&&nf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&nf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Zc(e,t,n),e=e.sibling;e!==null;)Zc(e,t,n),e=e.sibling}function Qc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);zd(t,r,n),t[it]=e,t[at]=n}catch(t){Ju(e,e.return,t)}}var $c=!1,el=!1,tl=!1,nl=typeof WeakSet==`function`?WeakSet:Set,rl=null;function il(e,t){if(e=e.containerInfo,Ud=up,e=Tr(e),Er(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Wd={focusedElem:e,selectionRange:n},up=!1,rl=t;rl!==null;)if(t=rl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,rl=e;else for(;rl!==null;){switch(t=rl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),zd(o,r,n),o[it]=e,_t(o),r=o;break a;case`link`:var s=Gf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Cr(s,h),v=Cr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,F.T=null,n=fu,fu=null;var o=cu,s=uu;if(su=0,lu=cu=null,uu=0,zl&6)throw Error(i(331));var c=zl;if(zl|=4,Pl(o.current),El(o,o.current,s,n),zl=c,cd(0,!1),Ne&&typeof Ne.onPostCommitFiberRoot==`function`)try{Ne.onPostCommitFiberRoot(Me,o)}catch{}return!0}finally{I.p=a,F.T=r,Wu(e,t)}}function qu(e,t,n){t=gi(n,t),t=Zs(e.stateNode,t,2),e=Va(e,t,2),e!==null&&(Je(e,2),sd(e))}function Ju(e,t,n){if(e.tag===3)qu(e,e,n);else for(;t!==null;){if(t.tag===3){qu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(ou===null||!ou.has(r))){e=gi(n,e),n=Qs(2),r=Va(t,n,2),r!==null&&($s(n,r,t,e),Je(r,2),sd(r));break}}t=t.return}}function Yu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Rl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Gl=!0,i.add(n),e=Xu.bind(null,e,t,n),t.then(e,e))}function Xu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Bl===e&&(q&n)===n&&(ql===4||ql===3&&(q&62914560)===q&&300>Ce()-nu?!(zl&2)&&Tu(e,0):Xl|=n,Ql===q&&(Ql=0)),sd(e)}function Zu(e,t){t===0&&(t=Ke()),e=ti(e,t),e!==null&&(Je(e,t),sd(e))}function Qu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zu(e,n)}function $u(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Zu(e,n)}function ed(e,t){return ye(e,t)}var td=null,nd=null,rd=!1,id=!1,ad=!1,od=0;function sd(e){e!==nd&&e.next===null&&(nd===null?td=nd=e:nd=nd.next=e),id=!0,rd||(rd=!0,md())}function cd(e,t){if(!ad&&id){ad=!0;do for(var n=!1,r=td;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Fe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,pd(r,a))}else a=q,a=Ue(r,r===Bl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||We(r,a)||(n=!0,pd(r,a))}r=r.next}while(n);ad=!1}}function ld(){ud()}function ud(){id=rd=!1;var e=0;od!==0&&Xd()&&(e=od);for(var t=Ce(),n=null,r=td;r!==null;){var i=r.next,a=dd(r,t);a===0?(r.next=null,n===null?td=i:n.next=i,i===null&&(nd=n)):(n=r,(e!==0||a&3)&&(id=!0)),r=i}su!==0&&su!==5||cd(e,!1),od!==0&&(od=0)}function dd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Vd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Ef(e,t,n){var r=Tf;if(r&&typeof t==`string`&&t){var i=It(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),bf.has(i)||(bf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),zd(t,`link`,e),_t(t),r.head.appendChild(t)))}}function Df(e){Sf.D(e),Ef(`dns-prefetch`,e,null)}function Of(e,t){Sf.C(e,t),Ef(`preconnect`,e,t)}function kf(e,t,n){Sf.L(e,t,n);var r=Tf;if(r&&e&&t){var i=`link[rel="preload"][as="`+It(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+It(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+It(n.imageSizes)+`"]`)):i+=`[href="`+It(e)+`"]`;var a=i;switch(t){case`style`:a=Ff(e);break;case`script`:a=Rf(e)}yf.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),yf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(If(a))||t===`script`&&r.querySelector(zf(a))||(t=r.createElement(`link`),zd(t,`link`,e),_t(t),r.head.appendChild(t)))}}function Af(e,t){Sf.m(e,t);var n=Tf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+It(r)+`"][href="`+It(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rf(e)}if(!yf.has(a)&&(e=h({rel:`modulepreload`,href:e},t),yf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zf(a)))return}r=n.createElement(`link`),zd(r,`link`,e),_t(r),n.head.appendChild(r)}}}function jf(e,t,n){Sf.S(e,t,n);var r=Tf;if(r&&e){var i=gt(r).hoistableStyles,a=Ff(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(If(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=yf.get(a))&&Hf(e,n);var c=o=r.createElement(`link`);_t(c),zd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Mf(e,t){Sf.X(e,t);var n=Tf;if(n&&e){var r=gt(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=h({src:e,async:!0},t),(t=yf.get(i))&&Uf(e,t),a=n.createElement(`script`),_t(a),zd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t){Sf.M(e,t);var n=Tf;if(n&&e){var r=gt(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=yf.get(i))&&Uf(e,t),a=n.createElement(`script`),_t(a),zd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Pf(e,t,n,r){var a=(a=ae.current)?xf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Ff(n.href),n=gt(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Ff(n.href);var o=gt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(If(e)))&&!o._p&&(s.instance=o,s.state.loading=5),yf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},yf.set(e,n),o||Lf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Rf(n),n=gt(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Ff(e){return`href="`+It(e)+`"`}function If(e){return`link[rel="stylesheet"][`+e+`]`}function Y(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function Lf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),zd(t,`link`,n),_t(t),e.head.appendChild(t))}function Rf(e){return`[src="`+It(e)+`"]`}function zf(e){return`script[async]`+e}function Bf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+It(n.href)+`"]`);if(r)return t.instance=r,_t(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),_t(r),zd(r,`style`,a),Vf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Ff(n.href);var o=e.querySelector(If(a));if(o)return t.state.loading|=4,t.instance=o,_t(o),o;r=Y(n),(a=yf.get(a))&&Hf(r,a),o=(e.ownerDocument||e).createElement(`link`),_t(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),zd(o,`link`,r),t.state.loading|=4,Vf(o,n.precedence,e),t.instance=o;case`script`:return o=Rf(n.src),(a=e.querySelector(zf(o)))?(t.instance=a,_t(a),a):(r=n,(a=yf.get(o))&&(r=h({},n),Uf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),_t(a),zd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vf(r,n.precedence,e));return t.instance}function Vf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function X(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function qf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Jf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Ff(r.href),a=t.querySelector(If(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Zf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,_t(a);return}a=t.ownerDocument||t,r=Y(r),(i=yf.get(i))&&Hf(r,i),a=a.createElement(`link`),_t(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),zd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Zf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Yf=0;function Xf(e,t){return e.stylesheets&&e.count===0&&$f(e,e.stylesheets),0Yf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Zf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)$f(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Qf=null;function $f(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Qf=new Map,t.forEach(ep,e),Qf=null,Zf.call(e))}function ep(e,t){if(!(t.state.loading&4)){var n=Qf.get(e);if(n)var r=n.get(null);else{n=new Map,Qf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),v=o(((e,t)=>{t.exports=_()})),y=c(u(),1),b=g(),x=v();function S(e){if(typeof e==`string`||typeof e==`number`)return``+e;let t=``;if(Array.isArray(e))for(let n=0,r;n{}};function w(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}T.prototype=w.prototype={constructor:T,on:function(e,t){var n=this._,r=E(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),k.hasOwnProperty(t)?{space:k[t],local:e}:e}function j(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function M(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function N(e){var t=A(e);return(t.local?M:j)(t)}function P(){}function ee(e){return e==null?P:function(){return this.querySelector(e)}}function F(e){typeof e!=`function`&&(e=ee(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function Te(e){e||=Ee;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function De(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Oe(){return Array.from(this)}function ke(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?Ve:typeof t==`function`?Ue:He)(e,t,n??``)):Ge(this.node(),e)}function Ge(e,t){return e.style.getPropertyValue(t)||Be(e).getComputedStyle(e,null).getPropertyValue(t)}function Ke(e){return function(){delete this[e]}}function qe(e,t){return function(){this[e]=t}}function Je(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Ye(e,t){return arguments.length>1?this.each((t==null?Ke:typeof t==`function`?Je:qe)(e,t)):this.node()[e]}function Xe(e){return e.trim().split(/^|\s+/)}function Ze(e){return e.classList||new Qe(e)}function Qe(e){this._node=e,this._names=Xe(e.getAttribute(`class`)||``)}Qe.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function $e(e,t){for(var n=Ze(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function Ot(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n()=>e;function Xt(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:a,x:o,y:s,dx:c,dy:l,dispatch:u}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:u}})}Xt.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Zt(e){return!e.ctrlKey&&!e.button}function Qt(){return this.parentNode}function $t(e,t){return t??{x:e.x,y:e.y}}function en(){return navigator.maxTouchPoints||`ontouchstart`in this}function tn(){var e=Zt,t=Qt,n=$t,r=en,i={},a=w(`start`,`drag`,`end`),o=0,s,c,l,u,d=0;function f(e){e.on(`mousedown.drag`,p).filter(r).on(`touchstart.drag`,g).on(`touchmove.drag`,_,Ut).on(`touchend.drag touchcancel.drag`,v).style(`touch-action`,`none`).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}function p(n,r){if(!(u||!e.call(this,n,r))){var i=y(this,t.call(this,n,r),n,r,`mouse`);i&&(Bt(n.view).on(`mousemove.drag`,m,Wt).on(`mouseup.drag`,h,Wt),qt(n.view),Gt(n),l=!1,s=n.clientX,c=n.clientY,i(`start`,n))}}function m(e){if(Kt(e),!l){var t=e.clientX-s,n=e.clientY-c;l=t*t+n*n>d}i.mouse(`drag`,e)}function h(e){Bt(e.view).on(`mousemove.drag mouseup.drag`,null),Jt(e.view,l),Kt(e),i.mouse(`end`,e)}function g(n,r){if(e.call(this,n,r)){var i=n.changedTouches,a=t.call(this,n,r),o=i.length,s,c;for(s=0;s>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Tn(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Tn(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=fn.exec(e))?new On(t[1],t[2],t[3],1):(t=pn.exec(e))?new On(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=mn.exec(e))?Tn(t[1],t[2],t[3],t[4]):(t=hn.exec(e))?Tn(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=gn.exec(e))?Fn(t[1],t[2]/100,t[3]/100,1):(t=_n.exec(e))?Fn(t[1],t[2]/100,t[3]/100,t[4]):vn.hasOwnProperty(e)?wn(vn[e]):e===`transparent`?new On(NaN,NaN,NaN,0):null}function wn(e){return new On(e>>16&255,e>>8&255,e&255,1)}function Tn(e,t,n,r){return r<=0&&(e=t=n=NaN),new On(e,t,n,r)}function En(e){return e instanceof an||(e=Cn(e)),e?(e=e.rgb(),new On(e.r,e.g,e.b,e.opacity)):new On}function Dn(e,t,n,r){return arguments.length===1?En(e):new On(e,t,n,r??1)}function On(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}nn(On,Dn,rn(an,{brighter(e){return e=e==null?sn:sn**+e,new On(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?on:on**+e,new On(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new On(Nn(this.r),Nn(this.g),Nn(this.b),Mn(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:kn,formatHex:kn,formatHex8:An,formatRgb:jn,toString:jn}));function kn(){return`#${Pn(this.r)}${Pn(this.g)}${Pn(this.b)}`}function An(){return`#${Pn(this.r)}${Pn(this.g)}${Pn(this.b)}${Pn((isNaN(this.opacity)?1:this.opacity)*255)}`}function jn(){let e=Mn(this.opacity);return`${e===1?`rgb(`:`rgba(`}${Nn(this.r)}, ${Nn(this.g)}, ${Nn(this.b)}${e===1?`)`:`, ${e})`}`}function Mn(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Nn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Pn(e){return e=Nn(e),(e<16?`0`:``)+e.toString(16)}function Fn(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Rn(e,t,n,r)}function In(e){if(e instanceof Rn)return new Rn(e.h,e.s,e.l,e.opacity);if(e instanceof an||(e=Cn(e)),!e)return new Rn;if(e instanceof Rn)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new Rn(o,s,c,e.opacity)}function Ln(e,t,n,r){return arguments.length===1?In(e):new Rn(e,t,n,r??1)}function Rn(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}nn(Rn,Ln,rn(an,{brighter(e){return e=e==null?sn:sn**+e,new Rn(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?on:on**+e,new Rn(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new On(Vn(e>=240?e-240:e+120,i,r),Vn(e,i,r),Vn(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Rn(zn(this.h),Bn(this.s),Bn(this.l),Mn(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=Mn(this.opacity);return`${e===1?`hsl(`:`hsla(`}${zn(this.h)}, ${Bn(this.s)*100}%, ${Bn(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function zn(e){return e=(e||0)%360,e<0?e+360:e}function Bn(e){return Math.max(0,Math.min(1,e||0))}function Vn(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var Hn=e=>()=>e;function Un(e,t){return function(n){return e+n*t}}function Wn(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function Gn(e){return(e=+e)==1?Kn:function(t,n){return n-t?Wn(t,n,e):Hn(isNaN(t)?n:t)}}function Kn(e,t){var n=t-e;return n?Un(e,n):Hn(isNaN(e)?t:e)}var qn=(function e(t){var n=Gn(t);function r(e,t){var r=n((e=Dn(e)).r,(t=Dn(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=Kn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function Jn(e,t){t||=[];var n=e?Math.min(t.length,e.length):0,r=t.slice(),i;return function(a){for(i=0;in&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:Qn(r,i)})),n=tr.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:Qn(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:Qn(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:Qn(e,n)},{i:s-2,x:Qn(t,r)})}else(n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--br}function Ir(){Dr=(Er=kr.now())+Or,br=xr=0;try{Fr()}finally{br=0,Rr(),Dr=0}}function Lr(){var e=kr.now(),t=e-Er;t>Cr&&(Or-=t,Er=e)}function Rr(){for(var e,t=wr,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:wr=n);Tr=e,zr(r)}function zr(e){br||(xr&&=clearTimeout(xr),e-Dr>24?(e<1/0&&(xr=setTimeout(Ir,e-kr.now()-Or)),Sr&&=clearInterval(Sr)):(Sr||=(Er=kr.now(),setInterval(Lr,Cr)),br=1,Ar(Ir)))}function Br(e,t,n){var r=new Nr;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var Vr=w(`start`,`end`,`cancel`,`interrupt`),Hr=[];function Ur(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;qr(e,n,{name:t,index:r,group:i,on:Vr,tween:Hr,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function Wr(e,t){var n=Kr(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function Gr(e,t){var n=Kr(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function Kr(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function qr(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=Pr(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return Br(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function Yr(e){return this.each(function(){Jr(this,e)})}function Xr(e,t){var n,r;return function(){var i=Gr(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function Ei(e,t,n){var r,i,a=Ti(t)?Wr:Gr;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function Di(e,t){var n=this._id;return arguments.length<2?Kr(this.node(),n).on.on(e):this.each(Ei(n,e,t))}function Oi(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function ki(){return this.on(`end.remove`,Oi(this._id))}function Ai(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=ee(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;o()=>e;function aa(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function oa(e,t,n){this.k=e,this.x=t,this.y=n}oa.prototype={constructor:oa,scale:function(e){return e===1?this:new oa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new oa(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return`translate(`+this.x+`,`+this.y+`) scale(`+this.k+`)`}};var sa=new oa(1,0,0);ca.prototype=oa.prototype;function ca(e){for(;!e.__zoom;)if(!(e=e.parentNode))return sa;return e.__zoom}function la(e){e.stopImmediatePropagation()}function ua(e){e.preventDefault(),e.stopImmediatePropagation()}function da(e){return(!e.ctrlKey||e.type===`wheel`)&&!e.button}function fa(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute(`viewBox`)?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function pa(){return this.__zoom||sa}function ma(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function ha(){return navigator.maxTouchPoints||`ontouchstart`in this}function ga(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],o=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function _a(){var e=da,t=fa,n=ga,r=ma,i=ha,a=[0,1/0],o=[[-1/0,-1/0],[1/0,1/0]],s=250,c=yr,l=w(`start`,`zoom`,`end`),u,d,f,p=500,m=150,h=0,g=10;function _(e){e.property(`__zoom`,pa).on(`wheel.zoom`,T,{passive:!1}).on(`mousedown.zoom`,E).on(`dblclick.zoom`,D).filter(i).on(`touchstart.zoom`,O).on(`touchmove.zoom`,k).on(`touchend.zoom touchcancel.zoom`,A).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}_.transform=function(e,t,n,r){var i=e.selection?e.selection():e;i.property(`__zoom`,pa),e===i?i.interrupt().each(function(){S(this,arguments).event(r).start().zoom(null,typeof t==`function`?t.apply(this,arguments):t).end()}):x(e,t,n,r)},_.scaleBy=function(e,t,n,r){_.scaleTo(e,function(){return this.__zoom.k*(typeof t==`function`?t.apply(this,arguments):t)},n,r)},_.scaleTo=function(e,r,i,a){_.transform(e,function(){var e=t.apply(this,arguments),a=this.__zoom,s=i==null?b(e):typeof i==`function`?i.apply(this,arguments):i,c=a.invert(s),l=typeof r==`function`?r.apply(this,arguments):r;return n(y(v(a,l),s,c),e,o)},i,a)},_.translateBy=function(e,r,i,a){_.transform(e,function(){return n(this.__zoom.translate(typeof r==`function`?r.apply(this,arguments):r,typeof i==`function`?i.apply(this,arguments):i),t.apply(this,arguments),o)},null,a)},_.translateTo=function(e,r,i,a,s){_.transform(e,function(){var e=t.apply(this,arguments),s=this.__zoom,c=a==null?b(e):typeof a==`function`?a.apply(this,arguments):a;return n(sa.translate(c[0],c[1]).scale(s.k).translate(typeof r==`function`?-r.apply(this,arguments):-r,typeof i==`function`?-i.apply(this,arguments):-i),e,o)},a,s)};function v(e,t){return t=Math.max(a[0],Math.min(a[1],t)),t===e.k?e:new oa(t,e.x,e.y)}function y(e,t,n){var r=t[0]-n[0]*e.k,i=t[1]-n[1]*e.k;return r===e.x&&i===e.y?e:new oa(e.k,r,i)}function b(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function x(e,n,r,i){e.on(`start.zoom`,function(){S(this,arguments).event(i).start()}).on(`interrupt.zoom end.zoom`,function(){S(this,arguments).event(i).end()}).tween(`zoom`,function(){var e=this,a=arguments,o=S(e,a).event(i),s=t.apply(e,a),l=r==null?b(s):typeof r==`function`?r.apply(e,a):r,u=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),d=e.__zoom,f=typeof n==`function`?n.apply(e,a):n,p=c(d.invert(l).concat(u/d.k),f.invert(l).concat(u/f.k));return function(e){if(e===1)e=f;else{var t=p(e),n=u/t[2];e=new oa(n,l[0]-t[0]*n,l[1]-t[1]*n)}o.zoom(null,e)}})}function S(e,t,n){return!n&&e.__zooming||new C(e,t)}function C(e,n){this.that=e,this.args=n,this.active=0,this.sourceEvent=null,this.extent=t.apply(e,n),this.taps=0}C.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit(`start`)),this},zoom:function(e,t){return this.mouse&&e!==`mouse`&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&e!==`touch`&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&e!==`touch`&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit(`zoom`),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit(`end`)),this},emit:function(e){var t=Bt(this.that).datum();l.call(e,this.that,new aa(e,{sourceEvent:this.sourceEvent,target:_,type:e,transform:this.that.__zoom,dispatch:l}),t)}};function T(t,...i){if(!e.apply(this,arguments))return;var s=S(this,i).event(t),c=this.__zoom,l=Math.max(a[0],Math.min(a[1],c.k*2**r.apply(this,arguments))),u=Ht(t);if(s.wheel)(s.mouse[0][0]!==u[0]||s.mouse[0][1]!==u[1])&&(s.mouse[1]=c.invert(s.mouse[0]=u)),clearTimeout(s.wheel);else if(c.k===l)return;else s.mouse=[u,c.invert(u)],Jr(this),s.start();ua(t),s.wheel=setTimeout(d,m),s.zoom(`mouse`,n(y(v(c,l),s.mouse[0],s.mouse[1]),s.extent,o));function d(){s.wheel=null,s.end()}}function E(t,...r){if(f||!e.apply(this,arguments))return;var i=t.currentTarget,a=S(this,r,!0).event(t),s=Bt(t.view).on(`mousemove.zoom`,d,!0).on(`mouseup.zoom`,p,!0),c=Ht(t,i),l=t.clientX,u=t.clientY;qt(t.view),la(t),a.mouse=[c,this.__zoom.invert(c)],Jr(this),a.start();function d(e){if(ua(e),!a.moved){var t=e.clientX-l,r=e.clientY-u;a.moved=t*t+r*r>h}a.event(e).zoom(`mouse`,n(y(a.that.__zoom,a.mouse[0]=Ht(e,i),a.mouse[1]),a.extent,o))}function p(e){s.on(`mousemove.zoom mouseup.zoom`,null),Jt(e.view,a.moved),ua(e),a.event(e).end()}}function D(r,...i){if(e.apply(this,arguments)){var a=this.__zoom,c=Ht(r.changedTouches?r.changedTouches[0]:r,this),l=a.invert(c),u=a.k*(r.shiftKey?.5:2),d=n(y(v(a,u),c,l),t.apply(this,i),o);ua(r),s>0?Bt(this).transition().duration(s).call(x,d,c,r):Bt(this).call(_.transform,d,c,r)}}function O(t,...n){if(e.apply(this,arguments)){var r=t.touches,i=r.length,a=S(this,n,t.changedTouches.length===i).event(t),o,s,c,l;for(la(t),s=0;s`Seems like you have not used ${e===`svelte`?`SvelteFlowProvider`:`ReactFlowProvider`} as an ancestor. Help: https://${e}flow.dev/error#001`,error002:()=>`It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.`,error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>`The parent container needs a width and a height to render the graph.`,error005:()=>`Only child nodes can use a parent extent.`,error006:()=>`Can't create edge. An edge needs a source and a target.`,error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e===`source`?n:r}", edge id: ${t}.`,error010:()=>`Handle: No node id found. Make sure to only use a Handle inside a custom Node.`,error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e=`react`)=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>`useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.`,error015:()=>`It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs.`,error016:e=>`Edge with id "${e}" does not exist, it may have been removed. This can happen when an edge is deleted before the "onEdgeClick" handler is called.`},ya=[[-1/0,-1/0],[1/0,1/0]],ba=[`Enter`,` `,`Escape`],xa={"node.a11yDescription.default":`Press enter or space to select a node. Press delete to remove it and escape to cancel.`,"node.a11yDescription.keyboardDisabled":`Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.`,"node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":`Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.`,"controls.ariaLabel":`Control Panel`,"controls.zoomIn.ariaLabel":`Zoom In`,"controls.zoomOut.ariaLabel":`Zoom Out`,"controls.fitView.ariaLabel":`Fit View`,"controls.interactive.ariaLabel":`Toggle Interactivity`,"minimap.ariaLabel":`Mini Map`,"handle.ariaLabel":`Handle`},Sa;(function(e){e.Strict=`strict`,e.Loose=`loose`})(Sa||={});var Ca;(function(e){e.Free=`free`,e.Vertical=`vertical`,e.Horizontal=`horizontal`})(Ca||={});var wa;(function(e){e.Partial=`partial`,e.Full=`full`})(wa||={});var Ta={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null},Ea;(function(e){e.Bezier=`default`,e.Straight=`straight`,e.Step=`step`,e.SmoothStep=`smoothstep`,e.SimpleBezier=`simplebezier`})(Ea||={});var Da;(function(e){e.Arrow=`arrow`,e.ArrowClosed=`arrowclosed`})(Da||={});var H;(function(e){e.Left=`left`,e.Top=`top`,e.Right=`right`,e.Bottom=`bottom`})(H||={});var Oa={[H.Left]:H.Right,[H.Right]:H.Left,[H.Top]:H.Bottom,[H.Bottom]:H.Top},ka=e=>!!e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e,Aa=e=>!!e&&typeof e==`object`&&`id`in e&&`position`in e&&!(`source`in e)&&!(`target`in e),ja=e=>!!e&&typeof e==`object`&&`id`in e&&`internals`in e&&!(`source`in e)&&!(`target`in e),Ma=(e,t=[0,0])=>{let{width:n,height:r}=uo(e),i=e.origin??t,a=n*i[0],o=r*i[1];return{x:e.position.x-a,y:e.position.y-o}},Na=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};let n=!1,r=e.reduce((e,r)=>{let i=typeof r==`string`,a=!t.nodeLookup&&!i?r:void 0;return t.nodeLookup&&(a=i?t.nodeLookup.get(r):ja(r)?r:t.nodeLookup.get(r.id)),a?(n=!0,Ka(e,Xa(a,t.nodeOrigin))):e},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return n?Ja(r):{x:0,y:0,width:0,height:0}},Pa=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(e=>{(t.filter===void 0||t.filter(e))&&(n=Ka(n,Xa(e)),r=!0)}),r?Ja(n):{x:0,y:0,width:0,height:0}},Fa=(e,t,[n,r,i]=[0,0,1],a=!1,o=!1)=>{let s=(t.x-n)/i,c=(t.y-r)/i,l=t.width/i,u=t.height/i,d=[];for(let t of e.values()){let{measured:e,selectable:n=!0,hidden:r=!1}=t;if(o&&!n||r)continue;let i=e.width??t.width??t.initialWidth??0,f=e.height??t.height??t.initialHeight??0,{x:p,y:m}=t.internals.positionAbsolute,h=Qa(s,c,l,u,p,m,i,f),g=i*f,_=a&&h>0;(!t.internals.handleBounds||_||h>=g||t.dragging)&&d.push(t)}return d},Ia=(e,t)=>{let n=new Set;return e.forEach(e=>{n.add(e.id)}),t.filter(e=>n.has(e.source)||n.has(e.target))};function La(e,t){let n=new Map,r=t?.nodes?new Set(t.nodes.map(e=>e.id)):null;return e.forEach(e=>{let i;if(t?.includeHiddenNodes){let{width:t,height:n}=uo(e);i=t>0&&n>0}else i=!!(e.measured.width&&e.measured.height&&!e.hidden);i&&(!r||r.has(e.id))&&n.set(e.id,e)}),n}async function Ra({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:a},o){if(e.size===0)return!0;let s=lo(Pa(La(e,o)),t,n,o?.minZoom??i,o?.maxZoom??a,o?.padding??.1);return await r.setViewport(s,{duration:o?.duration,ease:o?.ease,interpolate:o?.interpolate}),!0}function za({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:a}){let o=n.get(e),s=o.parentId?n.get(o.parentId):void 0,{x:c,y:l}=s?s.internals.positionAbsolute:{x:0,y:0},u=o.origin??r,d=o.extent||i;if(o.extent===`parent`&&!o.expandParent){if(!s)a?.(`005`,va.error005());else{let{width:e,height:t}=uo(s);e&&t&&(d=[[c,l],[c+e,l+t]])}}else s&&W(o.extent)&&(d=[[o.extent[0][0]+c,o.extent[0][1]+l],[o.extent[1][0]+c,o.extent[1][1]+l]]);let f=W(d)?Ha(t,d,o.measured):t;return(o.measured.width===void 0||o.measured.height===void 0)&&a?.(`015`,va.error015()),{position:{x:f.x-c+(o.measured.width??0)*u[0],y:f.y-l+(o.measured.height??0)*u[1]},positionAbsolute:f}}async function Ba({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){let a=new Set(e.map(e=>e.id)),o=[];for(let e of n){if(e.deletable===!1)continue;let t=a.has(e.id),n=!t&&e.parentId&&o.find(t=>t.id===e.parentId);(t||n)&&o.push(e)}let s=new Set(t.map(e=>e.id)),c=r.filter(e=>e.deletable!==!1),l=Ia(o,c);for(let e of c)s.has(e.id)&&!l.find(t=>t.id===e.id)&&l.push(e);if(!i)return{edges:l,nodes:o};let u=await i({nodes:o,edges:l});return typeof u==`boolean`?u?{edges:l,nodes:o}:{edges:[],nodes:[]}:u}var Va=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Ha=(e={x:0,y:0},t,n)=>({x:Va(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Va(e.y,t[0][1],t[1][1]-(n?.height??0))});function Ua(e,t,n){let{width:r,height:i}=uo(n),{x:a,y:o}=n.internals.positionAbsolute;return Ha(e,[[a,o],[a+r,o+i]],t)}var Wa=(e,t,n)=>en?-Va(Math.abs(e-n),1,t)/t:0,Ga=(e,t,n=15,r=40)=>[Wa(e.x,r,t.width-r)*n,Wa(e.y,r,t.height-r)*n],Ka=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),qa=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Ja=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Ya=(e,t=[0,0])=>{let{x:n,y:r}=ja(e)?e.internals.positionAbsolute:Ma(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Xa=(e,t=[0,0])=>{let{x:n,y:r}=ja(e)?e.internals.positionAbsolute:Ma(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},Za=(e,t)=>Ja(Ka(qa(e),qa(t))),Qa=(e,t,n,r,i,a,o,s)=>{let c=Math.max(0,Math.min(e+n,i+o)-Math.max(e,i)),l=Math.max(0,Math.min(t+r,a+s)-Math.max(t,a));return Math.ceil(c*l)},$a=(e,t)=>Qa(e.x,e.y,e.width,e.height,t.x,t.y,t.width,t.height),eo=e=>to(e.width)&&to(e.height)&&to(e.x)&&to(e.y),to=e=>!isNaN(e)&&isFinite(e),no=(e,t)=>(e,t)=>{},ro=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),io=({x:e,y:t},[n,r,i],a=!1,o=[1,1])=>{let s={x:(e-n)/i,y:(t-r)/i};return a?ro(s,o):s},ao=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function oo(e,t){if(typeof e==`number`)return Math.floor((t-t/(1+e))*.5);if(typeof e==`string`&&e.endsWith(`px`)){let t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if(typeof e==`string`&&e.endsWith(`%`)){let n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function so(e,t,n){if(typeof e==`string`||typeof e==`number`){let r=oo(e,n),i=oo(e,t);return{top:r,right:i,bottom:r,left:i,x:i*2,y:r*2}}if(typeof e==`object`){let r=oo(e.top??e.y??0,n),i=oo(e.bottom??e.y??0,n),a=oo(e.left??e.x??0,t),o=oo(e.right??e.x??0,t);return{top:r,right:o,bottom:i,left:a,x:a+o,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function co(e,t,n,r,i,a){let{x:o,y:s}=ao(e,[t,n,r]),{x:c,y:l}=ao({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=i-c,d=a-l;return{left:Math.floor(o),top:Math.floor(s),right:Math.floor(u),bottom:Math.floor(d)}}var lo=(e,t,n,r,i,a)=>{let o=so(a,t,n),s=(t-o.x)/e.width,c=(n-o.y)/e.height,l=Va(Math.min(s,c),r,i),u=e.x+e.width/2,d=e.y+e.height/2,f=t/2-u*l,p=n/2-d*l,m=co(e,f,p,l,t,n),h={left:Math.min(m.left-o.left,0),top:Math.min(m.top-o.top,0),right:Math.min(m.right-o.right,0),bottom:Math.min(m.bottom-o.bottom,0)};return{x:f-h.left+h.right,y:p-h.top+h.bottom,zoom:l}},U=()=>typeof navigator<`u`&&navigator?.userAgent?.indexOf(`Mac`)>=0;function W(e){return e!=null&&e!==`parent`}function uo(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function fo(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function po(e,t={width:0,height:0},n,r,i){let a={...e},o=r.get(n);if(o){let e=o.origin||i;a.x+=o.internals.positionAbsolute.x-(t.width??0)*e[0],a.y+=o.internals.positionAbsolute.y-(t.height??0)*e[1]}return a}function mo(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ho(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function go(e){return{...xa,...e||{}}}function _o(e){return e===null?null:e?`valid`:`invalid`}function vo(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){let{x:a,y:o}=wo(e),s=io({x:a-(i?.left??0),y:o-(i?.top??0)},r),{x:c,y:l}=n?ro(s,t):s;return{xSnapped:c,ySnapped:l,...s}}var yo=e=>({width:e.offsetWidth,height:e.offsetHeight}),bo=e=>e?.getRootNode?.()||window?.document,xo=[`INPUT`,`SELECT`,`TEXTAREA`];function So(e){let t=e.composedPath?.()?.[0]||e.target;return t?.nodeType===1?xo.includes(t.nodeName)||t.hasAttribute(`contenteditable`)||!!t.closest(`.nokey`):!1}var Co=e=>`clientX`in e,wo=(e,t)=>{let n=Co(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},To=(e,t,n,r,i)=>{let a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...yo(t)}})};function Eo({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:a,targetControlX:o,targetControlY:s}){let c=e*.125+i*.375+o*.375+n*.125,l=t*.125+a*.375+s*.375+r*.125;return[c,l,Math.abs(c-e),Math.abs(l-t)]}function Do(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Oo({pos:e,x1:t,y1:n,x2:r,y2:i,c:a}){switch(e){case H.Left:return[t-Do(t-r,a),n];case H.Right:return[t+Do(r-t,a),n];case H.Top:return[t,n-Do(n-i,a)];case H.Bottom:return[t,n+Do(i-n,a)]}}function ko({sourceX:e,sourceY:t,sourcePosition:n=H.Bottom,targetX:r,targetY:i,targetPosition:a=H.Top,curvature:o=.25}){let[s,c]=Oo({pos:n,x1:e,y1:t,x2:r,y2:i,c:o}),[l,u]=Oo({pos:a,x1:r,y1:i,x2:e,y2:t,c:o}),[d,f,p,m]=Eo({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:s,sourceControlY:c,targetControlX:l,targetControlY:u});return[`M${e},${t} C${s},${c} ${l},${u} ${r},${i}`,d,f,p,m]}function Ao({sourceX:e,sourceY:t,targetX:n,targetY:r}){let i=Math.abs(n-e)/2,a=n0}var No=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||``}-${n}${r||``}`,Po=(e,t)=>t.some(t=>t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle)),Fo=(e,t,n={})=>{if(!e.source||!e.target)return n.onError?.(`006`,va.error006()),t;let r=n.getEdgeId||No,i;return i=ka(e)?{...e}:{...e,id:r(e)},Po(i,t)?t:(i.sourceHandle===null&&delete i.sourceHandle,i.targetHandle===null&&delete i.targetHandle,t.concat(i))};function Io({sourceX:e,sourceY:t,targetX:n,targetY:r}){let[i,a,o,s]=Ao({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,a,o,s]}var Lo={[H.Left]:{x:-1,y:0},[H.Right]:{x:1,y:0},[H.Top]:{x:0,y:-1},[H.Bottom]:{x:0,y:1}},Ro=({source:e,sourcePosition:t=H.Bottom,target:n})=>t===H.Left||t===H.Right?e.xMath.sqrt((t.x-e.x)**2+(t.y-e.y)**2);function Bo({source:e,sourcePosition:t=H.Bottom,target:n,targetPosition:r=H.Top,center:i,offset:a,stepPosition:o}){let s=Lo[t],c=Lo[r],l={x:e.x+s.x*a,y:e.y+s.y*a},u={x:n.x+c.x*a,y:n.y+c.y*a},d=Ro({source:l,sourcePosition:t,target:u}),f=d.x===0?`y`:`x`,p=d[f],m=[],h,g,_={x:0,y:0},v={x:0,y:0},[,,y,b]=Ao({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(s[f]*c[f]===-1){f===`x`?(h=i.x??l.x+(u.x-l.x)*o,g=i.y??(l.y+u.y)/2):(h=i.x??(l.x+u.x)/2,g=i.y??l.y+(u.y-l.y)*o);let e=[{x:h,y:l.y},{x:h,y:u.y}],t=[{x:l.x,y:g},{x:u.x,y:g}];m=s[f]===p?f===`x`?e:t:f===`x`?t:e}else{let i=[{x:l.x,y:u.y}],o=[{x:u.x,y:l.y}];if(m=f===`x`?s.x===p?o:i:s.y===p?i:o,t===r){let t=Math.abs(e[f]-n[f]);if(t<=a){let r=Math.min(a-1,a-t);s[f]===p?_[f]=(l[f]>e[f]?-1:1)*r:v[f]=(u[f]>n[f]?-1:1)*r}}if(t!==r){let e=f===`x`?`y`:`x`,t=s[f]===c[e],n=l[e]>u[e],r=l[e]=Math.max(Math.abs(d.y-m[0].y),Math.abs(y.y-m[0].y))?(h=(d.x+y.x)/2,g=m[0].y):(h=m[0].x,g=(d.y+y.y)/2)}let x={x:l.x+_.x,y:l.y+_.y},S={x:u.x+v.x,y:u.y+v.y};return[[e,...x.x!==m[0].x||x.y!==m[0].y?[x]:[],...m,...S.x!==m[m.length-1].x||S.y!==m[m.length-1].y?[S]:[],n],h,g,y,b]}function Vo(e,t,n,r){let i=Math.min(zo(e,t)/2,zo(t,n)/2,r),{x:a,y:o}=t;if(e.x===a&&a===n.x||e.y===o&&o===n.y)return`L${a} ${o}`;if(e.y===o){let t=e.xe.id===t):e[0])||null}function Jo(e,t){return e?typeof e==`string`?e:`${t?`${t}__`:``}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join(`&`)}`:``}function Yo(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){let a=new Set;return e.reduce((e,o)=>([o.markerStart||r,o.markerEnd||i].forEach(r=>{if(r&&typeof r==`object`){let i=Jo(r,t);a.has(i)||(e.push({id:i,color:r.color||n,...r}),a.add(i))}}),e),[]).sort((e,t)=>e.id.localeCompare(t.id))}var Xo=1e3,Zo=10,Qo={nodeOrigin:[0,0],nodeExtent:ya,elevateNodesOnSelect:!0,zIndexMode:`basic`,defaults:{}},$o={...Qo,checkEquality:!0};function es(e,t){let n={...e};for(let e in t)t[e]!==void 0&&(n[e]=t[e]);return n}function ts(e,t,n){let r=es(Qo,n);for(let n of e.values())if(n.parentId)os(n,e,t,r);else{let e=Ha(Ma(n,r.nodeOrigin),W(n.extent)?n.extent:r.nodeExtent,uo(n));n.internals.positionAbsolute=e}}function ns(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;let n=[],r=[];for(let t of e.handles){let i={id:t.id,width:t.width??1,height:t.height??1,nodeId:e.id,x:t.x,y:t.y,position:t.position,type:t.type};t.type===`source`?n.push(i):t.type===`target`&&r.push(i)}return{source:n,target:r}}function rs(e){return e===`manual`}function is(e,t,n,r={}){let i=es($o,r),a={i:0},o=new Map(t),s=i?.elevateNodesOnSelect&&!rs(i.zIndexMode)?Xo:0,c=e.length>0,l=!1;t.clear(),n.clear();for(let u of e){let e=o.get(u.id);if(i.checkEquality&&u===e?.internals.userNode)t.set(u.id,e);else{let n=Ha(Ma(u,i.nodeOrigin),W(u.extent)?u.extent:i.nodeExtent,uo(u));e={...i.defaults,...u,measured:{width:u.measured?.width,height:u.measured?.height},internals:{positionAbsolute:n,handleBounds:ns(u,e),z:ss(u,s,i.zIndexMode),userNode:u}},t.set(u.id,e)}(e.measured===void 0||e.measured.width===void 0||e.measured.height===void 0)&&!e.hidden&&(c=!1),u.parentId&&os(e,t,n,r,a),l||=u.selected??!1}return{nodesInitialized:c,hasSelectedNodes:l}}function as(e,t){if(!e.parentId)return;let n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function os(e,t,n,r,i){let{elevateNodesOnSelect:a,nodeOrigin:o,nodeExtent:s,zIndexMode:c}=es(Qo,r),l=e.parentId,u=t.get(l);if(!u){console.warn(`Parent node ${l} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}as(e,n),i&&!u.parentId&&u.internals.rootParentIndex===void 0&&c===`auto`&&(u.internals.rootParentIndex=++i.i,u.internals.z=u.internals.z+i.i*Zo),i&&u.internals.rootParentIndex!==void 0&&(i.i=u.internals.rootParentIndex);let{x:d,y:f,z:p}=cs(e,u,o,s,a&&!rs(c)?Xo:0,c),{positionAbsolute:m}=e.internals,h=d!==m.x||f!==m.y;(h||p!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:h?{x:d,y:f}:m,z:p}})}function ss(e,t,n){let r=to(e.zIndex)?e.zIndex:0;return rs(n)?r:r+(e.selected?t:0)}function cs(e,t,n,r,i,a){let{x:o,y:s}=t.internals.positionAbsolute,c=uo(e),l=Ma(e,n),u=W(e.extent)?Ha(l,e.extent,c):l,d=Ha({x:o+u.x,y:s+u.y},r,c);e.extent===`parent`&&(d=Ua(d,c,t));let f=ss(e,i,a),p=t.internals.z??0;return{x:d.x,y:d.y,z:p>=f?p+1:f}}function ls(e,t,n,r=[0,0]){let i=[],a=new Map;for(let n of e){let e=t.get(n.parentId);if(!e)continue;let r=Za(a.get(n.parentId)?.expandedRect??Ya(e),n.rect);a.set(n.parentId,{expandedRect:r,parent:e})}return a.size>0&&a.forEach(({expandedRect:t,parent:a},o)=>{let s=a.internals.positionAbsolute,c=uo(a),l=a.origin??r,u=t.x0||d>0||m||h)&&(i.push({id:o,type:`position`,position:{x:a.position.x-u+m,y:a.position.y-d+h}}),n.get(o)?.forEach(t=>{e.some(e=>e.id===t.id)||i.push({id:t.id,type:`position`,position:{x:t.position.x+u,y:t.position.y+d}})})),(c.width0){let e=ls(f,t,n,i);l.push(...e)}return{changes:l,updatedInternals:c}}async function ds({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:a}){if(!t||!e.x&&!e.y)return!1;let o=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,a]],r);return!!o&&(o.x!==n[0]||o.y!==n[1]||o.k!==n[2])}function fs(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function ps(e,t,n){e.clear(),t.clear();for(let r of n){let{source:n,target:i,sourceHandle:a=null,targetHandle:o=null}=r,s={edgeId:r.id,source:n,target:i,sourceHandle:a,targetHandle:o},c=`${n}-${a}--${i}-${o}`;fs(`source`,s,`${i}-${o}--${n}-${a}`,e,n,a),fs(`target`,s,c,e,i,o),t.set(r.id,r)}}function ms(e,t){if(!e.parentId)return!1;let n=t.get(e.parentId);return n?n.selected?!0:ms(n,t):!1}function hs(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function gs(e,t,n,r){let i=new Map;for(let[a,o]of e)if((o.selected||o.id===r)&&(!o.parentId||!ms(o,e))&&(o.draggable||t&&o.draggable===void 0)){let t=e.get(a);t&&i.set(a,{id:a,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return i}function _s({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){let i=[];for(let[e,a]of t){let t=n.get(e)?.internals.userNode;t&&i.push({...t,position:a.position,dragging:r})}if(!e)return[i[0],i];let a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:i[0],i]}function vs({dragItems:e,snapGrid:t,x:n,y:r}){let i=e.values().next().value;if(!i)return null;let a={x:n-i.distance.x,y:r-i.distance.y},o=ro(a,t);return{x:o.x-a.x,y:o.y-a.y}}function ys({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let a={x:null,y:null},o=0,s=new Map,c=!1,l={x:0,y:0},u=null,d=!1,f=null,p=!1,m=!1,h=null;function g({noDragClassName:g,handleSelector:_,domNode:v,isSelectable:y,nodeId:b,nodeClickDistance:x=0}){f=Bt(v);function S({x:e,y:n}){let{nodeLookup:i,nodeExtent:o,snapGrid:c,snapToGrid:l,nodeOrigin:u,onNodeDrag:d,onSelectionDrag:f,onError:p,updateNodePositions:g}=t();a={x:e,y:n};let _=!1,v=s.size>1,y=v&&o?qa(Pa(s)):null,x=v&&l?vs({dragItems:s,snapGrid:c,x:e,y:n}):null;for(let[t,r]of s){if(!i.has(t))continue;let a={x:e-r.distance.x,y:n-r.distance.y};l&&(a=x?{x:Math.round(a.x+x.x),y:Math.round(a.y+x.y)}:ro(a,c));let s=null;if(v&&o&&!r.extent&&y){let{positionAbsolute:e}=r.internals,t=e.x-y.x+o[0][0],n=e.x+r.measured.width-y.x2+o[1][0],i=e.y-y.y+o[0][1],a=e.y+r.measured.height-y.y2+o[1][1];s=[[t,i],[n,a]]}let{position:d,positionAbsolute:f}=za({nodeId:t,nextPosition:a,nodeLookup:i,nodeExtent:s||o,nodeOrigin:u,onError:p});_=_||r.position.x!==d.x||r.position.y!==d.y,r.position=d,r.internals.positionAbsolute=f}if(m||=_,_&&(g(s,!0),h&&(r||d||!b&&f))){let[e,t]=_s({nodeId:b,dragItems:s,nodeLookup:i});r?.(h,s,e,t),d?.(h,e,t),b||f?.(h,t)}}async function C(){if(!u)return;let{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:i}=t();if(!i){c=!1,cancelAnimationFrame(o);return}let[s,d]=Ga(l,u,r);(s!==0||d!==0)&&(a.x=(a.x??0)-s/e[2],a.y=(a.y??0)-d/e[2],await n({x:s,y:d})&&S(a)),o=requestAnimationFrame(C)}function w(r){let{nodeLookup:i,multiSelectionActive:o,nodesDraggable:c,transform:l,snapGrid:f,snapToGrid:p,selectNodesOnDrag:m,onNodeDragStart:h,onSelectionDragStart:g,unselectNodesAndEdges:_}=t();d=!0,(!m||!y)&&!o&&b&&(i.get(b)?.selected||_()),y&&m&&b&&e?.(b);let v=vo(r.sourceEvent,{transform:l,snapGrid:f,snapToGrid:p,containerBounds:u});if(a=v,s=gs(i,c,v,b),s.size>0&&(n||h||!b&&g)){let[e,t]=_s({nodeId:b,dragItems:s,nodeLookup:i});n?.(r.sourceEvent,s,e,t),h?.(r.sourceEvent,e,t),b||g?.(r.sourceEvent,t)}}let T=tn().clickDistance(x).on(`start`,e=>{let{domNode:n,nodeDragThreshold:r,transform:i,snapGrid:o,snapToGrid:s}=t();u=n?.getBoundingClientRect()||null,p=!1,m=!1,h=e.sourceEvent,r===0&&w(e),a=vo(e.sourceEvent,{transform:i,snapGrid:o,snapToGrid:s,containerBounds:u}),l=wo(e.sourceEvent,u)}).on(`drag`,e=>{let{autoPanOnNodeDrag:n,transform:r,snapGrid:i,snapToGrid:o,nodeDragThreshold:f,nodeLookup:m}=t(),g=vo(e.sourceEvent,{transform:r,snapGrid:i,snapToGrid:o,containerBounds:u});if(h=e.sourceEvent,(e.sourceEvent.type===`touchmove`&&e.sourceEvent.touches.length>1||b&&!m.has(b))&&(p=!0),!p){if(!c&&n&&d&&(c=!0,C()),!d){let t=wo(e.sourceEvent,u),n=t.x-l.x,r=t.y-l.y;Math.sqrt(n*n+r*r)>f&&w(e)}(a.x!==g.xSnapped||a.y!==g.ySnapped)&&s&&d&&(l=wo(e.sourceEvent,u),S(g))}}).on(`end`,e=>{if(!d||p){p&&s.size>0&&t().updateNodePositions(s,!1);return}if(c=!1,d=!1,cancelAnimationFrame(o),s.size>0){let{nodeLookup:n,updateNodePositions:r,onNodeDragStop:a,onSelectionDragStop:o}=t();if(m&&=(r(s,!1),!1),i||a||!b&&o){let[t,r]=_s({nodeId:b,dragItems:s,nodeLookup:n,dragging:!1});i?.(e.sourceEvent,s,t,r),a?.(e.sourceEvent,t,r),b||o?.(e.sourceEvent,r)}}}).filter(e=>{let t=e.target;return!e.button&&(!g||!hs(t,`.${g}`,v))&&(!_||hs(t,_,v))});f.call(T)}function _(){f?.on(`.drag`,null)}return{update:g,destroy:_}}function bs(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())$a(i,Ya(e))>0&&r.push(e);return r}var xs=250;function Ss(e,t,n,r){let i=[],a=1/0,o=bs(e,n,t+xs);for(let n of o){let o=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=Ko(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function Cs(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===`strict`?o.internals.handleBounds?.[t]:[...o.internals.handleBounds?.source??[],...o.internals.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...Ko(o,c,c.position,!0)}:c}function ws(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function Ts(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}var Es=()=>!0;function Ds(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:a,isTarget:o,domNode:s,nodeLookup:c,lib:l,autoPanOnConnect:u,flowId:d,panBy:f,cancelConnection:p,onConnectStart:m,onConnect:h,onConnectEnd:g,isValidConnection:_=Es,onReconnectEnd:v,updateConnection:y,getTransform:b,getFromHandle:x,autoPanSpeed:S,dragThreshold:C=1,handleDomNode:w}){let T=bo(e.target),E=0,D,{x:O,y:k}=wo(e),A=ws(a,w),j=s?.getBoundingClientRect(),M=!1;if(!j||!A)return;let N=Cs(i,A,r,c,t);if(!N)return;let P=wo(e,j),ee=!1,F=null,I=!1,te=null;function ne(){if(!u||!j)return;let[e,t]=Ga(P,j,S);f({x:e,y:t}),E=requestAnimationFrame(ne)}let L={...N,nodeId:i,type:A,position:N.position},R=c.get(i),z={inProgress:!0,isValid:null,from:Ko(R,L,H.Left,!0),fromHandle:L,fromPosition:L.position,fromNode:R,to:P,toHandle:null,toPosition:Oa[L.position],toNode:null,pointer:P};function B(){M=!0,y(z),m?.(e,{nodeId:i,handleId:r,handleType:A})}C===0&&B();function re(e){if(!M){let{x:t,y:n}=wo(e),r=t-O,i=n-k;if(!(r*r+i*i>C*C))return;B()}if(!x()||!L){ie(e);return}let a=b();P=wo(e,j),D=Ss(io(P,a,!1,[1,1]),n,c,L),ee||=(ne(),!0);let s=Os(e,{handle:D,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:o?`target`:`source`,isValidConnection:_,doc:T,lib:l,flowId:d,nodeLookup:c});te=s.handleDomNode,F=s.connection,I=Ts(!!D,s.isValid);let u=c.get(i),f=u?Ko(u,L,H.Left,!0):z.from,p={...z,from:f,isValid:I,to:s.toHandle&&I?ao({x:s.toHandle.x,y:s.toHandle.y},a):P,toHandle:s.toHandle,toPosition:I&&s.toHandle?s.toHandle.position:Oa[L.position],toNode:s.toHandle?c.get(s.toHandle.nodeId):null,pointer:P};y(p),z=p}function ie(e){if(!(`touches`in e&&e.touches.length>0)){if(M){(D||te)&&F&&I&&h?.(F);let{inProgress:t,...n}=z,r={...n,toPosition:z.toHandle?z.toPosition:null};g?.(e,r),a&&v?.(e,r)}p(),cancelAnimationFrame(E),ee=!1,I=!1,F=null,te=null,T.removeEventListener(`mousemove`,re),T.removeEventListener(`mouseup`,ie),T.removeEventListener(`touchmove`,re),T.removeEventListener(`touchend`,ie)}}T.addEventListener(`mousemove`,re),T.addEventListener(`mouseup`,ie),T.addEventListener(`touchmove`,re),T.addEventListener(`touchend`,ie)}function Os(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=Es,nodeLookup:u}){let d=a===`target`,f=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=wo(e),h=o.elementFromPoint(p,m),g=h?.classList.contains(`${s}-flow__handle`)?h:f,_={handleDomNode:g,isValid:!1,connection:null,toHandle:null};if(g){let e=ws(void 0,g),t=g.getAttribute(`data-nodeid`),a=g.getAttribute(`data-handleid`),o=g.classList.contains(`connectable`),s=g.classList.contains(`connectableend`);if(!t||!e)return _;let c={source:d?t:r,sourceHandle:d?a:i,target:d?r:t,targetHandle:d?i:a};_.connection=c,_.isValid=o&&s&&(n===Sa.Strict?d&&e===`source`||!d&&e===`target`:t!==r||a!==i)&&l(c),_.toHandle=Cs(t,e,a,u,n,!0)}return _}var ks={onPointerDown:Ds,isValid:Os};function As({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){let i=Bt(e);function a({translateExtent:e,width:a,height:o,zoomStep:s=1,pannable:c=!0,zoomable:l=!0,inversePan:u=!1}){let d=e=>{if(e.sourceEvent.type!==`wheel`||!t)return;let r=n(),i=e.sourceEvent.ctrlKey&&U()?10:1,a=-e.sourceEvent.deltaY*(e.sourceEvent.deltaMode===1?.05:e.sourceEvent.deltaMode?1:.002)*s,o=r[2]*2**(a*i);t.scaleTo(o)},f=[0,0],p=_a().on(`start`,e=>{(e.sourceEvent.type===`mousedown`||e.sourceEvent.type===`touchstart`)&&(f=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])}).on(`zoom`,c?i=>{let s=n();if(i.sourceEvent.type!==`mousemove`&&i.sourceEvent.type!==`touchmove`||!t)return;let c=[i.sourceEvent.clientX??i.sourceEvent.touches[0].clientX,i.sourceEvent.clientY??i.sourceEvent.touches[0].clientY],l=[c[0]-f[0],c[1]-f[1]];f=c;let d=r()*Math.max(s[2],Math.log(s[2]))*(u?-1:1),p={x:s[0]-l[0]*d,y:s[1]-l[1]*d},m=[[0,0],[a,o]];t.setViewportConstrained({x:p.x,y:p.y,zoom:s[2]},m,e)}:null).on(`zoom.wheel`,l?d:null);i.call(p,{})}function o(){i.on(`zoom`,null)}return{update:a,destroy:o,pointer:Ht}}var js=e=>({x:e.x,y:e.y,zoom:e.k}),Ms=({x:e,y:t,zoom:n})=>sa.translate(e,t).scale(n),Ns=(e,t)=>e.target.closest(`.${t}`),Ps=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Fs=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Is=(e,t=0,n=Fs,r=()=>{})=>{let i=typeof t==`number`&&t>0;return i||r(),i?e.transition().duration(t).ease(n).on(`end`,r):e},Ls=e=>{let t=e.ctrlKey&&U()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Rs({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:a,zoomOnPinch:o,onPanZoomStart:s,onPanZoom:c,onPanZoomEnd:l}){return u=>{if(Ns(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();let d=n.property(`__zoom`).k||1;if(u.ctrlKey&&o){let e=Ht(u),t=d*2**Ls(u);r.scaleTo(n,t,e,u);return}let f=u.deltaMode===1?20:1,p=i===Ca.Vertical?0:u.deltaX*f,m=i===Ca.Horizontal?0:u.deltaY*f;!U()&&u.shiftKey&&i!==Ca.Vertical&&(p=u.deltaY*f,m=0),r.translateBy(n,-(p/d)*a,-(m/d)*a,{internal:!0});let h=js(n.property(`__zoom`));clearTimeout(e.panScrollTimeout),e.isPanScrolling?c?.(u,h):(e.isPanScrolling=!0,s?.(u,h)),e.panScrollTimeout=setTimeout(()=>{l?.(u,h),e.isPanScrolling=!1},150)}}function zs({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){let a=r.type===`wheel`,o=!t&&a&&!r.ctrlKey,s=Ns(r,e);if(r.ctrlKey&&a&&s&&r.preventDefault(),o||s)return null;r.preventDefault(),n.call(this,r,i)}}function Bs({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;let i=js(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,r.sourceEvent?.type===`mousedown`&&t(!0),n&&n?.(r.sourceEvent,i)}}function Vs({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return a=>{e.usedRightMouseButton=!!(n&&Ps(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),i&&!a.sourceEvent?.internal&&i?.(a.sourceEvent,js(a.transform))}}function Hs({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:a}){return o=>{if(!o.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&Ps(t,e.mouseButton??0)&&!e.usedRightMouseButton&&o.sourceEvent&&a(o.sourceEvent),e.usedRightMouseButton=!1,r(!1),i)){let t=js(o.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{i?.(o.sourceEvent,t)},n?150:0)}}}function Us({panActivationKeyPressed:e,zoomActivationKeyPressed:t,zoomOnScroll:n,zoomOnPinch:r,panOnDrag:i,panOnScroll:a,zoomOnDoubleClick:o,userSelectionActive:s,noWheelClassName:c,noPanClassName:l,lib:u,connectionInProgress:d}){return f=>{let p=t||n,m=r&&f.ctrlKey,h=f.type===`wheel`;if(f.button===1&&f.type===`mousedown`&&(Ns(f,`${u}-flow__node`)||Ns(f,`${u}-flow__edge`)||Ns(f,`${u}-flow__selection`)||Ns(f,`${u}-flow__nodesselection`)))return!0;if(!i&&!p&&!a&&!o&&!r||s||d&&!h||Ns(f,c)&&h||Ns(f,l)&&(!h||a&&h&&!t)||!r&&f.ctrlKey&&h)return!1;if(!r&&f.type===`touchstart`&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!a&&!m&&h||!i&&(f.type===`mousedown`||f.type===`touchstart`)||Array.isArray(i)&&!i.includes(f.button)&&f.type===`mousedown`)return!1;let g=Array.isArray(i)&&i.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||h||e)&&g}}function Ws({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:i,onPanZoom:a,onPanZoomStart:o,onPanZoomEnd:s,onDraggingChange:c}){let l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect(),d=[[0,0],[u.width,u.height]];(typeof ResizeObserver<`u`?new ResizeObserver(e=>{let t=e[0];t&&(d=[[0,0],[t.contentRect.width,t.contentRect.height]])}):null)?.observe(e);let f=_a().extent(()=>d).scaleExtent([t,n]).translateExtent(r),p=Bt(e).call(f);y({x:i.x,y:i.y,zoom:Va(i.zoom,t,n)},[[0,0],[u.width,u.height]],r);let m=p.on(`wheel.zoom`),h=p.on(`dblclick.zoom`);f.wheelDelta(Ls);async function g(e,t){return p?new Promise(n=>{f?.interpolate(t?.interpolate===`linear`?ar:yr).transform(Is(p,t?.duration,t?.ease,()=>n(!0)),e)}):!1}function _({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:i,panOnDrag:u,panOnScrollMode:d,panOnScrollSpeed:g,preventScrolling:_,zoomOnPinch:y,zoomOnScroll:b,zoomOnDoubleClick:x,panActivationKeyPressed:S=!1,zoomActivationKeyPressed:C,lib:w,onTransformChange:T,connectionInProgress:E,paneClickDistance:D,selectionOnDrag:O}){r&&!l.isZoomingOrPanning&&v();let k=i&&!C&&!r;f.clickDistance(O?1/0:!to(D)||D<0?0:D);let A=k?Rs({zoomPanValues:l,noWheelClassName:e,d3Selection:p,d3Zoom:f,panOnScrollMode:d,panOnScrollSpeed:g,zoomOnPinch:y,onPanZoomStart:o,onPanZoom:a,onPanZoomEnd:s}):zs({noWheelClassName:e,preventScrolling:_,d3ZoomHandler:m});p.on(`wheel.zoom`,A,{passive:!1});let j=Bs({zoomPanValues:l,onDraggingChange:c,onPanZoomStart:o});f.on(`start`,j);let M=Vs({zoomPanValues:l,panOnDrag:u,onPaneContextMenu:!!n,onPanZoom:a,onTransformChange:T});f.on(`zoom`,M);let N=Hs({zoomPanValues:l,panOnDrag:u,panOnScroll:i,onPaneContextMenu:n,onPanZoomEnd:s,onDraggingChange:c});f.on(`end`,N);let P=Us({panActivationKeyPressed:S,zoomActivationKeyPressed:C,panOnDrag:u,zoomOnScroll:b,panOnScroll:i,zoomOnDoubleClick:x,zoomOnPinch:y,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:w,connectionInProgress:E});f.filter(P),x?p.on(`dblclick.zoom`,h):p.on(`dblclick.zoom`,null)}function v(){f.on(`zoom`,null)}async function y(e,t,n){let r=Ms(e),i=f?.constrain()(r,t,n);return i&&await g(i),i}async function b(e,t){let n=Ms(e);return await g(n,t),n}function x(e){if(p){let t=Ms(e),n=p.property(`__zoom`);(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&f?.transform(p,t,null,{sync:!0})}}function S(){let e=p?ca(p.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}}async function C(e,t){return p?new Promise(n=>{f?.interpolate(t?.interpolate===`linear`?ar:yr).scaleTo(Is(p,t?.duration,t?.ease,()=>n(!0)),e)}):!1}async function w(e,t){return p?new Promise(n=>{f?.interpolate(t?.interpolate===`linear`?ar:yr).scaleBy(Is(p,t?.duration,t?.ease,()=>n(!0)),e)}):!1}function T(e){f?.scaleExtent(e)}function E(e){f?.translateExtent(e)}function D(e){let t=!to(e)||e<0?0:e;f?.clickDistance(t)}return{update:_,destroy:v,setViewport:b,setViewportConstrained:y,getViewport:S,scaleTo:C,scaleBy:w,setScaleExtent:T,setTranslateExtent:E,syncViewport:x,setClickDistance:D}}var Gs;(function(e){e.Line=`line`,e.Handle=`handle`})(Gs||={});function Ks({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:a}){let o=e-t,s=n-r,c=[o>0?1:o<0?-1:0,s>0?1:s<0?-1:0];return o&&i&&(c[0]*=-1),s&&a&&(c[1]*=-1),c}function qs(e){return{isHorizontal:e.includes(`right`)||e.includes(`left`),isVertical:e.includes(`bottom`)||e.includes(`top`),affectsX:e.includes(`left`),affectsY:e.includes(`top`)}}function Js(e,t){return Math.max(0,t-e)}function Ys(e,t){return Math.max(0,e-t)}function Xs(e,t,n){return Math.max(0,t-e,e-n)}function Zs(e,t){return e?!t:t}function Qs(e,t,n,r,i,a,o,s){let{affectsX:c,affectsY:l}=t,{isHorizontal:u,isVertical:d}=t,f=u&&d,{xSnapped:p,ySnapped:m}=n,{minWidth:h,maxWidth:g,minHeight:_,maxHeight:v}=r,{x:y,y:b,width:x,height:S,aspectRatio:C}=e,w=Math.floor(u?p-e.pointerX:0),T=Math.floor(d?m-e.pointerY:0),E=x+(c?-w:w),D=S+(l?-T:T),O=-a[0]*x,k=-a[1]*S,A=Xs(E,h,g),j=Xs(D,_,v);if(o){let e=0,t=0;c&&w<0?e=Js(y+w+O,o[0][0]):!c&&w>0&&(e=Ys(y+E+O,o[1][0])),l&&T<0?t=Js(b+T+k,o[0][1]):!l&&T>0&&(t=Ys(b+D+k,o[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(s){let e=0,t=0;c&&w>0?e=Ys(y+w,s[0][0]):!c&&w<0&&(e=Js(y+E,s[1][0])),l&&T>0?t=Ys(b+T,s[0][1]):!l&&T<0&&(t=Js(b+D,s[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(i){if(u){let e=Xs(E/C,_,v)*C;if(A=Math.max(A,e),o){let e=0;e=!c&&!l||c&&!l&&f?Ys(b+k+E/C,o[1][1])*C:Js(b+k+(c?w:-w)/C,o[0][1])*C,A=Math.max(A,e)}if(s){let e=0;e=!c&&!l||c&&!l&&f?Js(b+E/C,s[1][1])*C:Ys(b+(c?w:-w)/C,s[0][1])*C,A=Math.max(A,e)}}if(d){let e=Xs(D*C,h,g)/C;if(j=Math.max(j,e),o){let e=0;e=!c&&!l||l&&!c&&f?Ys(y+D*C+O,o[1][0])/C:Js(y+(l?T:-T)*C+O,o[0][0])/C,j=Math.max(j,e)}if(s){let e=0;e=!c&&!l||l&&!c&&f?Js(y+D*C,s[1][0])/C:Ys(y+(l?T:-T)*C,s[0][0])/C,j=Math.max(j,e)}}}T+=T<0?j:-j,w+=w<0?A:-A,i&&(f?E>D*C?T=(Zs(c,l)?-w:w)/C:w=(Zs(c,l)?-T:T)*C:u?(T=w/C,l=c):(w=T*C,c=l));let M=c?y+w:y,N=l?b+T:b;return{width:x+(c?-w:w),height:S+(l?-T:T),x:a[0]*w*(c?-1:1)+M,y:a[1]*T*(l?-1:1)+N}}var $s={width:0,height:0,x:0,y:0},ec={...$s,pointerX:0,pointerY:0,aspectRatio:1};function tc(e,t,n){let r=t.position.x+e.position.x,i=t.position.y+e.position.y,a=e.measured.width??0,o=e.measured.height??0,s=n[0]*a,c=n[1]*o;return[[r-s,i-c],[r+a-s,i+o-c]]}function nc({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){let a=Bt(e),o={controlDirection:qs(`bottom-right`),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function s({controlPosition:e,boundaries:s,keepAspectRatio:c,resizeDirection:l,onResizeStart:u,onResize:d,onResizeEnd:f,shouldResize:p}){let m={...$s},h={...ec};o={boundaries:s,resizeDirection:l,keepAspectRatio:c,controlDirection:qs(e)};let g,_=null,v=[],y,b,x,S=!1,C=tn().on(`start`,e=>{let{nodeLookup:r,transform:i,snapGrid:a,snapToGrid:o,nodeOrigin:s,paneDomNode:c}=n();if(g=r.get(t),!g)return;_=c?.getBoundingClientRect()??null;let{xSnapped:l,ySnapped:d}=vo(e.sourceEvent,{transform:i,snapGrid:a,snapToGrid:o,containerBounds:_});m={width:g.measured.width??0,height:g.measured.height??0,x:g.position.x??0,y:g.position.y??0},h={...m,pointerX:l,pointerY:d,aspectRatio:m.width/m.height},y=void 0,b=W(g.extent)?g.extent:void 0,g.parentId&&(g.extent===`parent`||g.expandParent)&&(y=r.get(g.parentId)),y&&g.extent===`parent`&&(b=[[0,0],[y.measured.width,y.measured.height]]),v=[],x=void 0;for(let[e,n]of r)if(n.parentId===t&&(v.push({id:e,position:{...n.position},extent:n.extent}),n.extent===`parent`||n.expandParent)){let e=tc(n,g,n.origin??s);x=x?[[Math.min(e[0][0],x[0][0]),Math.min(e[0][1],x[0][1])],[Math.max(e[1][0],x[1][0]),Math.max(e[1][1],x[1][1])]]:e}u?.(e,{...m})}).on(`drag`,e=>{let{transform:t,snapGrid:i,snapToGrid:a,nodeOrigin:s}=n(),c=vo(e.sourceEvent,{transform:t,snapGrid:i,snapToGrid:a,containerBounds:_}),l=[];if(!g)return;let{x:u,y:f,width:C,height:w}=m,T={},E=g.origin??s,{width:D,height:O,x:k,y:A}=Qs(h,o.controlDirection,c,o.boundaries,o.keepAspectRatio,E,b,x),j=D!==C,M=O!==w,N=k!==u&&j,P=A!==f&&M;if(!N&&!P&&!j&&!M)return;if((N||P||E[0]===1||E[1]===1)&&(T.x=N?k:m.x,T.y=P?A:m.y,m.x=T.x,m.y=T.y,v.length>0)){let e=k-u,t=A-f;for(let n of v)n.position={x:n.position.x-e+E[0]*(D-C),y:n.position.y-t+E[1]*(O-w)},l.push(n)}if((j||M)&&(T.width=j&&(!o.resizeDirection||o.resizeDirection===`horizontal`)?D:m.width,T.height=M&&(!o.resizeDirection||o.resizeDirection===`vertical`)?O:m.height,m.width=T.width,m.height=T.height),y&&g.expandParent){let e=E[0]*(T.width??0);T.x&&T.x{S&&=(f?.(e,{...m}),i?.({...m}),!1)});a.call(C)}function c(){a.on(`.drag`,null)}return{update:s,destroy:c}}var rc=o((e=>{var t=u();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),ic=o(((e,t)=>{t.exports=rc()})),ac=o((e=>{var t=u(),n=ic();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),oc=c(o(((e,t)=>{t.exports=ac()}))(),1),sc=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{n.clear()}},o=t=e(r,i,a);return a},cc=e=>e?sc(e):sc,{useDebugValue:lc}=y.default,{useSyncExternalStoreWithSelector:uc}=oc.default,dc=e=>e;function fc(e,t=dc,n){let r=uc(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return lc(r),r}var pc=(e,t)=>{let n=cc(e),r=(e,r=t)=>fc(n,e,r);return Object.assign(r,n),r},mc=(e,t)=>e?pc(e,t):pc;function hc(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var gc=m(),_c=(0,y.createContext)(null),vc=_c.Provider,yc=va.error001(`react`);function G(e,t){let n=(0,y.useContext)(_c);if(n===null)throw Error(yc);return fc(n,e,t)}function bc(){let e=(0,y.useContext)(_c);if(e===null)throw Error(yc);return(0,y.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}var xc={display:`none`},Sc={position:`absolute`,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0px, 0px, 0px, 0px)`,clipPath:`inset(100%)`},Cc=`react-flow__node-desc`,wc=`react-flow__edge-desc`,Tc=`react-flow__aria-live`,Ec=e=>e.ariaLiveMessage,Dc=e=>e.ariaLabelConfig;function Oc({rfId:e}){let t=G(Ec);return(0,x.jsx)(`div`,{id:`${Tc}-${e}`,"aria-live":`assertive`,"aria-atomic":`true`,style:Sc,children:t})}function kc({rfId:e,disableKeyboardA11y:t}){let n=G(Dc);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{id:`${Cc}-${e}`,style:xc,children:t?n[`node.a11yDescription.default`]:n[`node.a11yDescription.keyboardDisabled`]}),(0,x.jsx)(`div`,{id:`${wc}-${e}`,style:xc,children:n[`edge.a11yDescription.default`]}),!t&&(0,x.jsx)(Oc,{rfId:e})]})}var Ac=(0,y.forwardRef)(({position:e=`top-left`,children:t,className:n,style:r,...i},a)=>{let o=`${e}`.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__panel`,n,...o]),style:r,ref:a,...i,children:t})});Ac.displayName=`Panel`;var jc=`https://reactflow.dev?utm_source=attribution`;function Mc({proOptions:e,position:t=`bottom-right`}){return(0,y.useEffect)(()=>{},[]),e?.hideAttribution?null:(0,x.jsx)(Ac,{position:t,className:`react-flow__attribution`,"data-message":`Please only hide this attribution when you are subscribed to React Flow Pro: ${jc}`,children:(0,x.jsx)(`a`,{href:jc,target:`_blank`,rel:`noopener noreferrer`,"aria-label":`React Flow attribution`,children:`React Flow`})})}var Nc=e=>{let t=[],n=[];for(let[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(let[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},Pc=e=>e.id;function Fc(e,t){return hc(e.selectedNodes.map(Pc),t.selectedNodes.map(Pc))&&hc(e.selectedEdges.map(Pc),t.selectedEdges.map(Pc))}function Ic({onSelectionChange:e}){let t=bc(),{selectedNodes:n,selectedEdges:r}=G(Nc,Fc);return(0,y.useEffect)(()=>{let i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach(e=>e(i))},[n,r,e]),null}var Lc=e=>!!e.onSelectionChangeHandlers;function Rc({onSelectionChange:e}){let t=G(Lc);return e||t?(0,x.jsx)(Ic,{onSelectionChange:e}):null}var zc=[0,0],Bc={x:0,y:0,zoom:1},Vc=[...`nodes.edges.defaultNodes.defaultEdges.onConnect.onConnectStart.onConnectEnd.onClickConnectStart.onClickConnectEnd.nodesDraggable.autoPanOnNodeFocus.nodesConnectable.nodesFocusable.edgesFocusable.edgesReconnectable.elevateNodesOnSelect.elevateEdgesOnSelect.minZoom.maxZoom.nodeExtent.onNodesChange.onEdgesChange.elementsSelectable.connectionMode.snapGrid.snapToGrid.translateExtent.connectOnClick.defaultEdgeOptions.fitView.fitViewOptions.onNodesDelete.onEdgesDelete.onDelete.onNodeDrag.onNodeDragStart.onNodeDragStop.onSelectionDrag.onSelectionDragStart.onSelectionDragStop.onMoveStart.onMove.onMoveEnd.noPanClassName.nodeOrigin.autoPanOnConnect.autoPanOnNodeDrag.onError.connectionRadius.isValidConnection.selectNodesOnDrag.nodeDragThreshold.connectionDragThreshold.onBeforeDelete.debug.autoPanSpeed.ariaLabelConfig.zIndexMode`.split(`.`),`rfId`],Hc=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),Uc={translateExtent:ya,nodeOrigin:zc,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:`nopan`,rfId:`1`};function Wc(e){let{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:a,setNodeExtent:o,reset:s,setDefaultNodesAndEdges:c}=G(Hc,hc),l=bc();(0,y.useEffect)(()=>(c(e.defaultNodes,e.defaultEdges),()=>{u.current=Uc,s()}),[]);let u=(0,y.useRef)(Uc);return(0,y.useEffect)(()=>{for(let s of Vc){let c=e[s];c!==u.current[s]&&e[s]!==void 0&&(s===`nodes`?t(c):s===`edges`?n(c):s===`minZoom`?r(c):s===`maxZoom`?i(c):s===`translateExtent`?a(c):s===`nodeExtent`?o(c):s===`ariaLabelConfig`?l.setState({ariaLabelConfig:go(c)}):s===`fitView`?l.setState({fitViewQueued:c}):s===`fitViewOptions`?l.setState({fitViewOptions:c}):l.setState({[s]:c}))}u.current=e},Vc.map(t=>e[t])),null}function Gc(){return typeof window>`u`||!window.matchMedia?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function Kc(e){let[t,n]=(0,y.useState)(e===`system`?null:e);return(0,y.useEffect)(()=>{if(e!==`system`){n(e);return}let t=Gc(),r=()=>n(t?.matches?`dark`:`light`);return r(),t?.addEventListener(`change`,r),()=>{t?.removeEventListener(`change`,r)}},[e]),t===null?Gc()?.matches?`dark`:`light`:t}var qc=typeof document<`u`?document:null;function Jc(e=null,t={target:qc,actInsideInputWithModifier:!0}){let[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(!1),a=(0,y.useRef)(new Set([])),[o,s]=(0,y.useMemo)(()=>{if(e!==null){let t=(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`).map(e=>e.replace(/\+/g,` +`+e.stack}}var ve=Object.prototype.hasOwnProperty,ye=t.unstable_scheduleCallback,be=t.unstable_cancelCallback,xe=t.unstable_shouldYield,Se=t.unstable_requestPaint,Ce=t.unstable_now,we=t.unstable_getCurrentPriorityLevel,Te=t.unstable_ImmediatePriority,Ee=t.unstable_UserBlockingPriority,De=t.unstable_NormalPriority,Oe=t.unstable_LowPriority,ke=t.unstable_IdlePriority,Ae=t.log,je=t.unstable_setDisableYieldValue,Me=null,Ne=null;function Pe(e){if(typeof Ae==`function`&&je(e),Ne&&typeof Ne.setStrictMode==`function`)try{Ne.setStrictMode(Me,e)}catch{}}var Fe=Math.clz32?Math.clz32:Re,Ie=Math.log,Le=Math.LN2;function Re(e){return e>>>=0,e===0?32:31-(Ie(e)/Le|0)|0}var ze=256,Be=262144,Ve=4194304;function He(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ue(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=He(n))):i=He(o):i=He(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=He(n))):i=He(o)):i=He(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function We(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ge(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ke(){var e=Ve;return Ve<<=1,!(Ve&62914560)&&(Ve=4194304),e}function qe(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Je(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ye(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),cn=!1;if(sn)try{var ln={};Object.defineProperty(ln,"passive",{get:function(){cn=!0}}),window.addEventListener(`test`,ln,ln),window.removeEventListener(`test`,ln,ln)}catch{cn=!1}var un=null,dn=null,fn=null;function pn(){if(fn)return fn;var e,t=dn,n=t.length,r,i=`value`in un?un.value:un.textContent,a=i.length;for(e=0;e=Gn),Jn=` `,Yn=!1;function Xn(e,t){switch(e){case`keyup`:return Un.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Zn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Qn=!1;function $n(e,t){switch(e){case`compositionend`:return Zn(t);case`keypress`:return t.which===32?(Yn=!0,Jn):null;case`textInput`:return e=t.data,e===Jn&&Yn?null:e;default:return null}}function er(e,t){if(Qn)return e===`compositionend`||!Wn&&Xn(e,t)?(e=pn(),fn=dn=un=null,Qn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Sr(n)}}function wr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Tr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Pt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Pt(e.document)}return t}function Er(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Dr=sn&&`documentMode`in document&&11>=document.documentMode,Or=null,kr=null,Ar=null,jr=!1;function Mr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;jr||Or==null||Or!==Pt(r)||(r=Or,`selectionStart`in r&&Er(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ar&&xr(Ar,r)||(Ar=r,r=Ad(kr,`onSelect`),0>=o,i-=o,wi=1<<32-Fe(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),V&&Ei(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),V&&Ei(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return V&&Ei(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),V&&Ei(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&Ea(l)===r.type){n(e,r.sibling),c=a(r,o.props),Ma(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=di(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ui(o.type,o.key,o.props,null,e.mode,c),Ma(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=mi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=Ea(o),b(e,r,o,c)}if(ee(o))return h(e,r,o,c);if(M(o)){if(l=M(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,ja(o),c);if(o.$$typeof===C)return b(e,r,ea(e,o),c);Na(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=fi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Aa=0;var i=b(e,t,n,r);return ka=null,i}catch(t){if(t===ba||t===Sa)throw t;var a=oi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Fa=Pa(!0),Ia=Pa(!1),La=!1;function Ra(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function za(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ba(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Va(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,zl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ri(e),ni(e,null,n),t}return $r(e,r,t,n),ri(e)}function Ha(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}function Ua(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Wa=!1;function Ga(){if(Wa){var e=da;if(e!==null)throw e}}function Ka(e,t,n,r){Wa=!1;var i=e.updateQueue;La=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(q&f)===f:(r&f)===f){f!==0&&f===ua&&(Wa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:La=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Jl|=o,e.lanes=o,e.memoizedState=d}}function qa(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Ja(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=F.T,s={};F.T=s,Ns(e,!1,t,n);try{var c=i(),l=F.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ms(e,t,ma(c,r),gu(e)):Ms(e,t,r,gu(e))}catch(n){Ms(e,t,{then:function(){},status:`rejected`,reason:n},gu())}finally{I.p=a,o!==null&&s.types!==null&&(o.types=s.types),F.T=o}}function Ss(){}function Cs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=ws(e).queue;xs(e,a,t,te,n===null?Ss:function(){return Ts(e),n(r)})}function ws(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:te,baseState:te,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:te},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Po,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ts(e){var t=ws(e);t.next===null&&(t=e.alternate.memoizedState),Ms(e,t.next.queue,{},gu())}function Es(){return $i(tp)}function Ds(){return ko().memoizedState}function Os(){return ko().memoizedState}function ks(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=gu();e=Ba(n);var r=Va(t,e,n);r!==null&&(vu(r,t,n),Ha(r,t,n)),t={cache:oa()},e.payload=t;return}t=t.return}}function As(e,t,n){var r=gu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ps(e)?Fs(t,n):(n=ei(e,t,n,r),n!==null&&(vu(n,e,r),Is(n,t,r)))}function js(e,t,n){Ms(e,t,n,gu())}function Ms(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ps(e))Fs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,br(s,o))return $r(e,t,i,0),Bl===null&&Qr(),!1}catch{}if(n=ei(e,t,i,r),n!==null)return vu(n,e,r),Is(n,t,r),!0}return!1}function Ns(e,t,n,r){if(r={lane:2,revertLane:hd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ps(e)){if(t)throw Error(i(479))}else t=ei(e,n,r,2),t!==null&&vu(t,e,2)}function Ps(e){var t=e.alternate;return e===U||t!==null&&t===U}function Fs(e,t){po=fo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Is(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}var Ls={readContext:$i,use:Mo,useCallback:yo,useContext:yo,useEffect:yo,useImperativeHandle:yo,useLayoutEffect:yo,useInsertionEffect:yo,useMemo:yo,useReducer:yo,useRef:yo,useState:yo,useDebugValue:yo,useDeferredValue:yo,useTransition:yo,useSyncExternalStore:yo,useId:yo,useHostTransitionStatus:yo,useFormState:yo,useActionState:yo,useOptimistic:yo,useMemoCache:yo,useCacheRefresh:yo};Ls.useEffectEvent=yo;var Rs={readContext:$i,use:Mo,useCallback:function(e,t){return Oo().memoizedState=[e,t===void 0?null:t],e},useContext:$i,useEffect:cs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),os(4194308,4,ms.bind(null,t,e),n)},useLayoutEffect:function(e,t){return os(4194308,4,e,t)},useInsertionEffect:function(e,t){os(4,2,e,t)},useMemo:function(e,t){var n=Oo();t=t===void 0?null:t;var r=e();if(mo){Pe(!0);try{e()}finally{Pe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Oo();if(n!==void 0){var i=n(t);if(mo){Pe(!0);try{n(t)}finally{Pe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=As.bind(null,U,e),[r.memoizedState,e]},useRef:function(e){var t=Oo();return e={current:e},t.memoizedState=e},useState:function(e){e=Wo(e);var t=e.queue,n=js.bind(null,U,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:gs,useDeferredValue:function(e,t){return ys(Oo(),e,t)},useTransition:function(){var e=Wo(!1);return e=xs.bind(null,U,e.queue,!0,!1),Oo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=U,a=Oo();if(V){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Bl===null)throw Error(i(349));q&127||zo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,cs(Vo.bind(null,r,o,e),[e]),r.flags|=2048,is(9,{destroy:void 0},Bo.bind(null,r,o,n,t),null),n},useId:function(){var e=Oo(),t=Bl.identifierPrefix;if(V){var n=Ti,r=wi;n=(r&~(1<<32-Fe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ho++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[it]=t,o[at]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(zd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&jc(t)}}return Ic(t),Mc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&jc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ae.current,zi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=ji,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[it]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Id(e.nodeValue,n)),e||Ii(t,!0)}else e=Gd(e).createTextNode(r),e[it]=t,t.stateNode=e}return Ic(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=zi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[it]=t}else Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ic(t),e=!1}else n=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(oo(t),t):(oo(t),null);if(t.flags&128)throw Error(i(558))}return Ic(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=zi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[it]=t}else Bi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ic(t),a=!1}else a=Vi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(oo(t),t):(oo(t),null)}return oo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Pc(t,t.updateQueue),Ic(t),null);case 4:return ce(),e===null&&Ed(t.stateNode.containerInfo),Ic(t),null;case 10:return qi(t.type),Ic(t),null;case 19:if(z(so),r=t.memoizedState,r===null)return Ic(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Fc(r,!1);else{if(ql!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=co(e),o!==null){for(t.flags|=128,Fc(r,!1),e=o.updateQueue,t.updateQueue=e,Pc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)li(n,e),n=n.sibling;return B(so,so.current&1|2),V&&Ei(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ce()>iu&&(t.flags|=128,a=!0,Fc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=co(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Pc(t,e),Fc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!V)return Ic(t),null}else 2*Ce()-r.renderingStartTime>iu&&n!==536870912&&(t.flags|=128,a=!0,Fc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Ic(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ce(),e.sibling=null,n=so.current,B(so,a?n&1|2:n&1),V&&Ei(t,r.treeForkCount),e);case 22:case 23:return oo(t),$a(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Ic(t),t.subtreeFlags&6&&(t.flags|=8192)):Ic(t),n=t.updateQueue,n!==null&&Pc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&z(ga),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),qi(aa),Ic(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Rc(e,t){switch(ki(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return qi(aa),ce(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return ue(t),null;case 31:if(t.memoizedState!==null){if(oo(t),t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(oo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Bi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return z(so),null;case 4:return ce(),null;case 10:return qi(t.type),null;case 22:case 23:return oo(t),$a(),e!==null&&z(ga),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return qi(aa),null;case 25:return null;default:return null}}function zc(e,t){switch(ki(t),t.tag){case 3:qi(aa),ce();break;case 26:case 27:case 5:ue(t);break;case 4:ce();break;case 31:t.memoizedState!==null&&oo(t);break;case 13:oo(t);break;case 19:z(so);break;case 10:qi(t.type);break;case 22:case 23:oo(t),$a(),e!==null&&z(ga);break;case 24:qi(aa)}}function Bc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Ju(t,t.return,e)}}function Vc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Ju(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Ju(t,t.return,e)}}function Hc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ja(t,n)}catch(t){Ju(e,e.return,t)}}}function Uc(e,t,n){n.props=Gs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Ju(e,t,n)}}function Wc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Ju(e,t,n)}}function Gc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Ju(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Ju(e,t,n)}else n.current=null}}function Kc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Ju(e,e.return,t)}}function qc(e,t,n){try{var r=e.stateNode;Bd(r,e.type,n,t),r[at]=t}catch(t){Ju(e,e.return,t)}}function Jc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&nf(e.type)||e.tag===4}function Yc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Jc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&nf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Zt));else if(r!==4&&(r===27&&nf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&nf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Zc(e,t,n),e=e.sibling;e!==null;)Zc(e,t,n),e=e.sibling}function Qc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);zd(t,r,n),t[it]=e,t[at]=n}catch(t){Ju(e,e.return,t)}}var $c=!1,el=!1,tl=!1,nl=typeof WeakSet==`function`?WeakSet:Set,rl=null;function il(e,t){if(e=e.containerInfo,Ud=up,e=Tr(e),Er(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Wd={focusedElem:e,selectionRange:n},up=!1,rl=t;rl!==null;)if(t=rl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,rl=e;else for(;rl!==null;){switch(t=rl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),zd(o,r,n),o[it]=e,_t(o),r=o;break a;case`link`:var s=Gf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Cr(s,h),v=Cr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,F.T=null,n=fu,fu=null;var o=cu,s=uu;if(su=0,lu=cu=null,uu=0,zl&6)throw Error(i(331));var c=zl;if(zl|=4,Pl(o.current),El(o,o.current,s,n),zl=c,cd(0,!1),Ne&&typeof Ne.onPostCommitFiberRoot==`function`)try{Ne.onPostCommitFiberRoot(Me,o)}catch{}return!0}finally{I.p=a,F.T=r,Wu(e,t)}}function qu(e,t,n){t=gi(n,t),t=Zs(e.stateNode,t,2),e=Va(e,t,2),e!==null&&(Je(e,2),sd(e))}function Ju(e,t,n){if(e.tag===3)qu(e,e,n);else for(;t!==null;){if(t.tag===3){qu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(ou===null||!ou.has(r))){e=gi(n,e),n=Qs(2),r=Va(t,n,2),r!==null&&($s(n,r,t,e),Je(r,2),sd(r));break}}t=t.return}}function Yu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Rl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Gl=!0,i.add(n),e=Xu.bind(null,e,t,n),t.then(e,e))}function Xu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Bl===e&&(q&n)===n&&(ql===4||ql===3&&(q&62914560)===q&&300>Ce()-nu?!(zl&2)&&Tu(e,0):Xl|=n,Ql===q&&(Ql=0)),sd(e)}function Zu(e,t){t===0&&(t=Ke()),e=ti(e,t),e!==null&&(Je(e,t),sd(e))}function Qu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zu(e,n)}function $u(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Zu(e,n)}function ed(e,t){return ye(e,t)}var td=null,nd=null,rd=!1,id=!1,ad=!1,od=0;function sd(e){e!==nd&&e.next===null&&(nd===null?td=nd=e:nd=nd.next=e),id=!0,rd||(rd=!0,md())}function cd(e,t){if(!ad&&id){ad=!0;do for(var n=!1,r=td;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Fe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,pd(r,a))}else a=q,a=Ue(r,r===Bl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||We(r,a)||(n=!0,pd(r,a))}r=r.next}while(n);ad=!1}}function ld(){ud()}function ud(){id=rd=!1;var e=0;od!==0&&Xd()&&(e=od);for(var t=Ce(),n=null,r=td;r!==null;){var i=r.next,a=dd(r,t);a===0?(r.next=null,n===null?td=i:n.next=i,i===null&&(nd=n)):(n=r,(e!==0||a&3)&&(id=!0)),r=i}su!==0&&su!==5||cd(e,!1),od!==0&&(od=0)}function dd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Vd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Ef(e,t,n){var r=Tf;if(r&&typeof t==`string`&&t){var i=It(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),bf.has(i)||(bf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),zd(t,`link`,e),_t(t),r.head.appendChild(t)))}}function Df(e){Sf.D(e),Ef(`dns-prefetch`,e,null)}function Of(e,t){Sf.C(e,t),Ef(`preconnect`,e,t)}function kf(e,t,n){Sf.L(e,t,n);var r=Tf;if(r&&e&&t){var i=`link[rel="preload"][as="`+It(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+It(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+It(n.imageSizes)+`"]`)):i+=`[href="`+It(e)+`"]`;var a=i;switch(t){case`style`:a=Ff(e);break;case`script`:a=Y(e)}yf.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),yf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(If(a))||t===`script`&&r.querySelector(zf(a))||(t=r.createElement(`link`),zd(t,`link`,e),_t(t),r.head.appendChild(t)))}}function Af(e,t){Sf.m(e,t);var n=Tf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+It(r)+`"][href="`+It(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Y(e)}if(!yf.has(a)&&(e=h({rel:`modulepreload`,href:e},t),yf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zf(a)))return}r=n.createElement(`link`),zd(r,`link`,e),_t(r),n.head.appendChild(r)}}}function jf(e,t,n){Sf.S(e,t,n);var r=Tf;if(r&&e){var i=gt(r).hoistableStyles,a=Ff(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(If(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=yf.get(a))&&Hf(e,n);var c=o=r.createElement(`link`);_t(c),zd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Mf(e,t){Sf.X(e,t);var n=Tf;if(n&&e){var r=gt(n).hoistableScripts,i=Y(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=h({src:e,async:!0},t),(t=yf.get(i))&&Uf(e,t),a=n.createElement(`script`),_t(a),zd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t){Sf.M(e,t);var n=Tf;if(n&&e){var r=gt(n).hoistableScripts,i=Y(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=yf.get(i))&&Uf(e,t),a=n.createElement(`script`),_t(a),zd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Pf(e,t,n,r){var a=(a=ae.current)?xf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Ff(n.href),n=gt(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Ff(n.href);var o=gt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(If(e)))&&!o._p&&(s.instance=o,s.state.loading=5),yf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},yf.set(e,n),o||Rf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Y(n),n=gt(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Ff(e){return`href="`+It(e)+`"`}function If(e){return`link[rel="stylesheet"][`+e+`]`}function Lf(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function Rf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),zd(t,`link`,n),_t(t),e.head.appendChild(t))}function Y(e){return`[src="`+It(e)+`"]`}function zf(e){return`script[async]`+e}function Bf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+It(n.href)+`"]`);if(r)return t.instance=r,_t(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),_t(r),zd(r,`style`,a),Vf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Ff(n.href);var o=e.querySelector(If(a));if(o)return t.state.loading|=4,t.instance=o,_t(o),o;r=Lf(n),(a=yf.get(a))&&Hf(r,a),o=(e.ownerDocument||e).createElement(`link`),_t(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),zd(o,`link`,r),t.state.loading|=4,Vf(o,n.precedence,e),t.instance=o;case`script`:return o=Y(n.src),(a=e.querySelector(zf(o)))?(t.instance=a,_t(a),a):(r=n,(a=yf.get(o))&&(r=h({},n),Uf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),_t(a),zd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vf(r,n.precedence,e));return t.instance}function Vf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function X(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Ff(r.href),a=t.querySelector(If(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Zf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,_t(a);return}a=t.ownerDocument||t,r=Lf(r),(i=yf.get(i))&&Hf(r,i),a=a.createElement(`link`),_t(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),zd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Zf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Yf=0;function Xf(e,t){return e.stylesheets&&e.count===0&&$f(e,e.stylesheets),0Yf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Zf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)$f(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Qf=null;function $f(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Qf=new Map,t.forEach(ep,e),Qf=null,Zf.call(e))}function ep(e,t){if(!(t.state.loading&4)){var n=Qf.get(e);if(n)var r=n.get(null);else{n=new Map,Qf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),v=o(((e,t)=>{t.exports=_()})),y=c(u(),1),b=g(),x=v();function S(e){if(typeof e==`string`||typeof e==`number`)return``+e;let t=``;if(Array.isArray(e))for(let n=0,r;n{}};function w(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}T.prototype=w.prototype={constructor:T,on:function(e,t){var n=this._,r=E(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),k.hasOwnProperty(t)?{space:k[t],local:e}:e}function j(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function M(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function N(e){var t=A(e);return(t.local?M:j)(t)}function P(){}function ee(e){return e==null?P:function(){return this.querySelector(e)}}function F(e){typeof e!=`function`&&(e=ee(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function Te(e){e||=Ee;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function De(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Oe(){return Array.from(this)}function ke(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?Ve:typeof t==`function`?Ue:He)(e,t,n??``)):Ge(this.node(),e)}function Ge(e,t){return e.style.getPropertyValue(t)||Be(e).getComputedStyle(e,null).getPropertyValue(t)}function Ke(e){return function(){delete this[e]}}function qe(e,t){return function(){this[e]=t}}function Je(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Ye(e,t){return arguments.length>1?this.each((t==null?Ke:typeof t==`function`?Je:qe)(e,t)):this.node()[e]}function Xe(e){return e.trim().split(/^|\s+/)}function Ze(e){return e.classList||new Qe(e)}function Qe(e){this._node=e,this._names=Xe(e.getAttribute(`class`)||``)}Qe.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function $e(e,t){for(var n=Ze(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function Ot(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n()=>e;function Xt(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:a,x:o,y:s,dx:c,dy:l,dispatch:u}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:u}})}Xt.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Zt(e){return!e.ctrlKey&&!e.button}function Qt(){return this.parentNode}function $t(e,t){return t??{x:e.x,y:e.y}}function en(){return navigator.maxTouchPoints||`ontouchstart`in this}function tn(){var e=Zt,t=Qt,n=$t,r=en,i={},a=w(`start`,`drag`,`end`),o=0,s,c,l,u,d=0;function f(e){e.on(`mousedown.drag`,p).filter(r).on(`touchstart.drag`,g).on(`touchmove.drag`,_,Ut).on(`touchend.drag touchcancel.drag`,v).style(`touch-action`,`none`).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}function p(n,r){if(!(u||!e.call(this,n,r))){var i=y(this,t.call(this,n,r),n,r,`mouse`);i&&(Bt(n.view).on(`mousemove.drag`,m,Wt).on(`mouseup.drag`,h,Wt),qt(n.view),Gt(n),l=!1,s=n.clientX,c=n.clientY,i(`start`,n))}}function m(e){if(Kt(e),!l){var t=e.clientX-s,n=e.clientY-c;l=t*t+n*n>d}i.mouse(`drag`,e)}function h(e){Bt(e.view).on(`mousemove.drag mouseup.drag`,null),Jt(e.view,l),Kt(e),i.mouse(`end`,e)}function g(n,r){if(e.call(this,n,r)){var i=n.changedTouches,a=t.call(this,n,r),o=i.length,s,c;for(s=0;s>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Tn(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Tn(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=fn.exec(e))?new On(t[1],t[2],t[3],1):(t=pn.exec(e))?new On(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=mn.exec(e))?Tn(t[1],t[2],t[3],t[4]):(t=hn.exec(e))?Tn(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=gn.exec(e))?Fn(t[1],t[2]/100,t[3]/100,1):(t=_n.exec(e))?Fn(t[1],t[2]/100,t[3]/100,t[4]):vn.hasOwnProperty(e)?wn(vn[e]):e===`transparent`?new On(NaN,NaN,NaN,0):null}function wn(e){return new On(e>>16&255,e>>8&255,e&255,1)}function Tn(e,t,n,r){return r<=0&&(e=t=n=NaN),new On(e,t,n,r)}function En(e){return e instanceof an||(e=Cn(e)),e?(e=e.rgb(),new On(e.r,e.g,e.b,e.opacity)):new On}function Dn(e,t,n,r){return arguments.length===1?En(e):new On(e,t,n,r??1)}function On(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}nn(On,Dn,rn(an,{brighter(e){return e=e==null?sn:sn**+e,new On(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?on:on**+e,new On(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new On(Nn(this.r),Nn(this.g),Nn(this.b),Mn(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:kn,formatHex:kn,formatHex8:An,formatRgb:jn,toString:jn}));function kn(){return`#${Pn(this.r)}${Pn(this.g)}${Pn(this.b)}`}function An(){return`#${Pn(this.r)}${Pn(this.g)}${Pn(this.b)}${Pn((isNaN(this.opacity)?1:this.opacity)*255)}`}function jn(){let e=Mn(this.opacity);return`${e===1?`rgb(`:`rgba(`}${Nn(this.r)}, ${Nn(this.g)}, ${Nn(this.b)}${e===1?`)`:`, ${e})`}`}function Mn(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Nn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Pn(e){return e=Nn(e),(e<16?`0`:``)+e.toString(16)}function Fn(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Rn(e,t,n,r)}function In(e){if(e instanceof Rn)return new Rn(e.h,e.s,e.l,e.opacity);if(e instanceof an||(e=Cn(e)),!e)return new Rn;if(e instanceof Rn)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new Rn(o,s,c,e.opacity)}function Ln(e,t,n,r){return arguments.length===1?In(e):new Rn(e,t,n,r??1)}function Rn(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}nn(Rn,Ln,rn(an,{brighter(e){return e=e==null?sn:sn**+e,new Rn(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?on:on**+e,new Rn(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new On(Vn(e>=240?e-240:e+120,i,r),Vn(e,i,r),Vn(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Rn(zn(this.h),Bn(this.s),Bn(this.l),Mn(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=Mn(this.opacity);return`${e===1?`hsl(`:`hsla(`}${zn(this.h)}, ${Bn(this.s)*100}%, ${Bn(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function zn(e){return e=(e||0)%360,e<0?e+360:e}function Bn(e){return Math.max(0,Math.min(1,e||0))}function Vn(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var Hn=e=>()=>e;function Un(e,t){return function(n){return e+n*t}}function Wn(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function Gn(e){return(e=+e)==1?Kn:function(t,n){return n-t?Wn(t,n,e):Hn(isNaN(t)?n:t)}}function Kn(e,t){var n=t-e;return n?Un(e,n):Hn(isNaN(e)?t:e)}var qn=(function e(t){var n=Gn(t);function r(e,t){var r=n((e=Dn(e)).r,(t=Dn(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=Kn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function Jn(e,t){t||=[];var n=e?Math.min(t.length,e.length):0,r=t.slice(),i;return function(a){for(i=0;in&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:Qn(r,i)})),n=tr.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:Qn(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:Qn(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:Qn(e,n)},{i:s-2,x:Qn(t,r)})}else(n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--br}function Ir(){Dr=(Er=kr.now())+Or,br=xr=0;try{Fr()}finally{br=0,Rr(),Dr=0}}function Lr(){var e=kr.now(),t=e-Er;t>Cr&&(Or-=t,Er=e)}function Rr(){for(var e,t=wr,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:wr=n);Tr=e,zr(r)}function zr(e){br||(xr&&=clearTimeout(xr),e-Dr>24?(e<1/0&&(xr=setTimeout(Ir,e-kr.now()-Or)),Sr&&=clearInterval(Sr)):(Sr||=(Er=kr.now(),setInterval(Lr,Cr)),br=1,Ar(Ir)))}function Br(e,t,n){var r=new Nr;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var Vr=w(`start`,`end`,`cancel`,`interrupt`),Hr=[];function Ur(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;qr(e,n,{name:t,index:r,group:i,on:Vr,tween:Hr,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function Wr(e,t){var n=Kr(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function Gr(e,t){var n=Kr(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function Kr(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function qr(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=Pr(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return Br(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function Yr(e){return this.each(function(){Jr(this,e)})}function Xr(e,t){var n,r;return function(){var i=Gr(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function Ei(e,t,n){var r,i,a=Ti(t)?Wr:Gr;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function Di(e,t){var n=this._id;return arguments.length<2?Kr(this.node(),n).on.on(e):this.each(Ei(n,e,t))}function Oi(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function ki(){return this.on(`end.remove`,Oi(this._id))}function Ai(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=ee(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;o()=>e;function aa(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function oa(e,t,n){this.k=e,this.x=t,this.y=n}oa.prototype={constructor:oa,scale:function(e){return e===1?this:new oa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new oa(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return`translate(`+this.x+`,`+this.y+`) scale(`+this.k+`)`}};var sa=new oa(1,0,0);ca.prototype=oa.prototype;function ca(e){for(;!e.__zoom;)if(!(e=e.parentNode))return sa;return e.__zoom}function la(e){e.stopImmediatePropagation()}function ua(e){e.preventDefault(),e.stopImmediatePropagation()}function da(e){return(!e.ctrlKey||e.type===`wheel`)&&!e.button}function fa(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute(`viewBox`)?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function pa(){return this.__zoom||sa}function ma(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function ha(){return navigator.maxTouchPoints||`ontouchstart`in this}function ga(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],o=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function _a(){var e=da,t=fa,n=ga,r=ma,i=ha,a=[0,1/0],o=[[-1/0,-1/0],[1/0,1/0]],s=250,c=yr,l=w(`start`,`zoom`,`end`),u,d,f,p=500,m=150,h=0,g=10;function _(e){e.property(`__zoom`,pa).on(`wheel.zoom`,T,{passive:!1}).on(`mousedown.zoom`,E).on(`dblclick.zoom`,D).filter(i).on(`touchstart.zoom`,O).on(`touchmove.zoom`,k).on(`touchend.zoom touchcancel.zoom`,A).style(`-webkit-tap-highlight-color`,`rgba(0,0,0,0)`)}_.transform=function(e,t,n,r){var i=e.selection?e.selection():e;i.property(`__zoom`,pa),e===i?i.interrupt().each(function(){S(this,arguments).event(r).start().zoom(null,typeof t==`function`?t.apply(this,arguments):t).end()}):x(e,t,n,r)},_.scaleBy=function(e,t,n,r){_.scaleTo(e,function(){return this.__zoom.k*(typeof t==`function`?t.apply(this,arguments):t)},n,r)},_.scaleTo=function(e,r,i,a){_.transform(e,function(){var e=t.apply(this,arguments),a=this.__zoom,s=i==null?b(e):typeof i==`function`?i.apply(this,arguments):i,c=a.invert(s),l=typeof r==`function`?r.apply(this,arguments):r;return n(y(v(a,l),s,c),e,o)},i,a)},_.translateBy=function(e,r,i,a){_.transform(e,function(){return n(this.__zoom.translate(typeof r==`function`?r.apply(this,arguments):r,typeof i==`function`?i.apply(this,arguments):i),t.apply(this,arguments),o)},null,a)},_.translateTo=function(e,r,i,a,s){_.transform(e,function(){var e=t.apply(this,arguments),s=this.__zoom,c=a==null?b(e):typeof a==`function`?a.apply(this,arguments):a;return n(sa.translate(c[0],c[1]).scale(s.k).translate(typeof r==`function`?-r.apply(this,arguments):-r,typeof i==`function`?-i.apply(this,arguments):-i),e,o)},a,s)};function v(e,t){return t=Math.max(a[0],Math.min(a[1],t)),t===e.k?e:new oa(t,e.x,e.y)}function y(e,t,n){var r=t[0]-n[0]*e.k,i=t[1]-n[1]*e.k;return r===e.x&&i===e.y?e:new oa(e.k,r,i)}function b(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function x(e,n,r,i){e.on(`start.zoom`,function(){S(this,arguments).event(i).start()}).on(`interrupt.zoom end.zoom`,function(){S(this,arguments).event(i).end()}).tween(`zoom`,function(){var e=this,a=arguments,o=S(e,a).event(i),s=t.apply(e,a),l=r==null?b(s):typeof r==`function`?r.apply(e,a):r,u=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),d=e.__zoom,f=typeof n==`function`?n.apply(e,a):n,p=c(d.invert(l).concat(u/d.k),f.invert(l).concat(u/f.k));return function(e){if(e===1)e=f;else{var t=p(e),n=u/t[2];e=new oa(n,l[0]-t[0]*n,l[1]-t[1]*n)}o.zoom(null,e)}})}function S(e,t,n){return!n&&e.__zooming||new C(e,t)}function C(e,n){this.that=e,this.args=n,this.active=0,this.sourceEvent=null,this.extent=t.apply(e,n),this.taps=0}C.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit(`start`)),this},zoom:function(e,t){return this.mouse&&e!==`mouse`&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&e!==`touch`&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&e!==`touch`&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit(`zoom`),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit(`end`)),this},emit:function(e){var t=Bt(this.that).datum();l.call(e,this.that,new aa(e,{sourceEvent:this.sourceEvent,target:_,type:e,transform:this.that.__zoom,dispatch:l}),t)}};function T(t,...i){if(!e.apply(this,arguments))return;var s=S(this,i).event(t),c=this.__zoom,l=Math.max(a[0],Math.min(a[1],c.k*2**r.apply(this,arguments))),u=Ht(t);if(s.wheel)(s.mouse[0][0]!==u[0]||s.mouse[0][1]!==u[1])&&(s.mouse[1]=c.invert(s.mouse[0]=u)),clearTimeout(s.wheel);else if(c.k===l)return;else s.mouse=[u,c.invert(u)],Jr(this),s.start();ua(t),s.wheel=setTimeout(d,m),s.zoom(`mouse`,n(y(v(c,l),s.mouse[0],s.mouse[1]),s.extent,o));function d(){s.wheel=null,s.end()}}function E(t,...r){if(f||!e.apply(this,arguments))return;var i=t.currentTarget,a=S(this,r,!0).event(t),s=Bt(t.view).on(`mousemove.zoom`,d,!0).on(`mouseup.zoom`,p,!0),c=Ht(t,i),l=t.clientX,u=t.clientY;qt(t.view),la(t),a.mouse=[c,this.__zoom.invert(c)],Jr(this),a.start();function d(e){if(ua(e),!a.moved){var t=e.clientX-l,r=e.clientY-u;a.moved=t*t+r*r>h}a.event(e).zoom(`mouse`,n(y(a.that.__zoom,a.mouse[0]=Ht(e,i),a.mouse[1]),a.extent,o))}function p(e){s.on(`mousemove.zoom mouseup.zoom`,null),Jt(e.view,a.moved),ua(e),a.event(e).end()}}function D(r,...i){if(e.apply(this,arguments)){var a=this.__zoom,c=Ht(r.changedTouches?r.changedTouches[0]:r,this),l=a.invert(c),u=a.k*(r.shiftKey?.5:2),d=n(y(v(a,u),c,l),t.apply(this,i),o);ua(r),s>0?Bt(this).transition().duration(s).call(x,d,c,r):Bt(this).call(_.transform,d,c,r)}}function O(t,...n){if(e.apply(this,arguments)){var r=t.touches,i=r.length,a=S(this,n,t.changedTouches.length===i).event(t),o,s,c,l;for(la(t),s=0;s`Seems like you have not used ${e===`svelte`?`SvelteFlowProvider`:`ReactFlowProvider`} as an ancestor. Help: https://${e}flow.dev/error#001`,error002:()=>`It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.`,error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>`The parent container needs a width and a height to render the graph.`,error005:()=>`Only child nodes can use a parent extent.`,error006:()=>`Can't create edge. An edge needs a source and a target.`,error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e===`source`?n:r}", edge id: ${t}.`,error010:()=>`Handle: No node id found. Make sure to only use a Handle inside a custom Node.`,error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e=`react`)=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>`useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.`,error015:()=>`It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs.`,error016:e=>`Edge with id "${e}" does not exist, it may have been removed. This can happen when an edge is deleted before the "onEdgeClick" handler is called.`},ya=[[-1/0,-1/0],[1/0,1/0]],ba=[`Enter`,` `,`Escape`],xa={"node.a11yDescription.default":`Press enter or space to select a node. Press delete to remove it and escape to cancel.`,"node.a11yDescription.keyboardDisabled":`Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.`,"node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":`Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.`,"controls.ariaLabel":`Control Panel`,"controls.zoomIn.ariaLabel":`Zoom In`,"controls.zoomOut.ariaLabel":`Zoom Out`,"controls.fitView.ariaLabel":`Fit View`,"controls.interactive.ariaLabel":`Toggle Interactivity`,"minimap.ariaLabel":`Mini Map`,"handle.ariaLabel":`Handle`},Sa;(function(e){e.Strict=`strict`,e.Loose=`loose`})(Sa||={});var Ca;(function(e){e.Free=`free`,e.Vertical=`vertical`,e.Horizontal=`horizontal`})(Ca||={});var wa;(function(e){e.Partial=`partial`,e.Full=`full`})(wa||={});var Ta={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null},Ea;(function(e){e.Bezier=`default`,e.Straight=`straight`,e.Step=`step`,e.SmoothStep=`smoothstep`,e.SimpleBezier=`simplebezier`})(Ea||={});var Da;(function(e){e.Arrow=`arrow`,e.ArrowClosed=`arrowclosed`})(Da||={});var H;(function(e){e.Left=`left`,e.Top=`top`,e.Right=`right`,e.Bottom=`bottom`})(H||={});var Oa={[H.Left]:H.Right,[H.Right]:H.Left,[H.Top]:H.Bottom,[H.Bottom]:H.Top},ka=e=>!!e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e,Aa=e=>!!e&&typeof e==`object`&&`id`in e&&`position`in e&&!(`source`in e)&&!(`target`in e),ja=e=>!!e&&typeof e==`object`&&`id`in e&&`internals`in e&&!(`source`in e)&&!(`target`in e),Ma=(e,t=[0,0])=>{let{width:n,height:r}=uo(e),i=e.origin??t,a=n*i[0],o=r*i[1];return{x:e.position.x-a,y:e.position.y-o}},Na=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};let n=!1,r=e.reduce((e,r)=>{let i=typeof r==`string`,a=!t.nodeLookup&&!i?r:void 0;return t.nodeLookup&&(a=i?t.nodeLookup.get(r):ja(r)?r:t.nodeLookup.get(r.id)),a?(n=!0,Ka(e,Xa(a,t.nodeOrigin))):e},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return n?Ja(r):{x:0,y:0,width:0,height:0}},Pa=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(e=>{(t.filter===void 0||t.filter(e))&&(n=Ka(n,Xa(e)),r=!0)}),r?Ja(n):{x:0,y:0,width:0,height:0}},Fa=(e,t,[n,r,i]=[0,0,1],a=!1,o=!1)=>{let s=(t.x-n)/i,c=(t.y-r)/i,l=t.width/i,u=t.height/i,d=[];for(let t of e.values()){let{measured:e,selectable:n=!0,hidden:r=!1}=t;if(o&&!n||r)continue;let i=e.width??t.width??t.initialWidth??0,f=e.height??t.height??t.initialHeight??0,{x:p,y:m}=t.internals.positionAbsolute,h=Qa(s,c,l,u,p,m,i,f),g=i*f,_=a&&h>0;(!t.internals.handleBounds||_||h>=g||t.dragging)&&d.push(t)}return d},Ia=(e,t)=>{let n=new Set;return e.forEach(e=>{n.add(e.id)}),t.filter(e=>n.has(e.source)||n.has(e.target))};function La(e,t){let n=new Map,r=t?.nodes?new Set(t.nodes.map(e=>e.id)):null;return e.forEach(e=>{let i;if(t?.includeHiddenNodes){let{width:t,height:n}=uo(e);i=t>0&&n>0}else i=!!(e.measured.width&&e.measured.height&&!e.hidden);i&&(!r||r.has(e.id))&&n.set(e.id,e)}),n}async function Ra({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:a},o){if(e.size===0)return!0;let s=lo(Pa(La(e,o)),t,n,o?.minZoom??i,o?.maxZoom??a,o?.padding??.1);return await r.setViewport(s,{duration:o?.duration,ease:o?.ease,interpolate:o?.interpolate}),!0}function za({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:a}){let o=n.get(e),s=o.parentId?n.get(o.parentId):void 0,{x:c,y:l}=s?s.internals.positionAbsolute:{x:0,y:0},u=o.origin??r,d=o.extent||i;if(o.extent===`parent`&&!o.expandParent){if(!s)a?.(`005`,va.error005());else{let{width:e,height:t}=uo(s);e&&t&&(d=[[c,l],[c+e,l+t]])}}else s&&W(o.extent)&&(d=[[o.extent[0][0]+c,o.extent[0][1]+l],[o.extent[1][0]+c,o.extent[1][1]+l]]);let f=W(d)?Ha(t,d,o.measured):t;return(o.measured.width===void 0||o.measured.height===void 0)&&a?.(`015`,va.error015()),{position:{x:f.x-c+(o.measured.width??0)*u[0],y:f.y-l+(o.measured.height??0)*u[1]},positionAbsolute:f}}async function Ba({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){let a=new Set(e.map(e=>e.id)),o=[];for(let e of n){if(e.deletable===!1)continue;let t=a.has(e.id),n=!t&&e.parentId&&o.find(t=>t.id===e.parentId);(t||n)&&o.push(e)}let s=new Set(t.map(e=>e.id)),c=r.filter(e=>e.deletable!==!1),l=Ia(o,c);for(let e of c)s.has(e.id)&&!l.find(t=>t.id===e.id)&&l.push(e);if(!i)return{edges:l,nodes:o};let u=await i({nodes:o,edges:l});return typeof u==`boolean`?u?{edges:l,nodes:o}:{edges:[],nodes:[]}:u}var Va=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Ha=(e={x:0,y:0},t,n)=>({x:Va(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Va(e.y,t[0][1],t[1][1]-(n?.height??0))});function Ua(e,t,n){let{width:r,height:i}=uo(n),{x:a,y:o}=n.internals.positionAbsolute;return Ha(e,[[a,o],[a+r,o+i]],t)}var Wa=(e,t,n)=>en?-Va(Math.abs(e-n),1,t)/t:0,Ga=(e,t,n=15,r=40)=>[Wa(e.x,r,t.width-r)*n,Wa(e.y,r,t.height-r)*n],Ka=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),qa=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Ja=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Ya=(e,t=[0,0])=>{let{x:n,y:r}=ja(e)?e.internals.positionAbsolute:Ma(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Xa=(e,t=[0,0])=>{let{x:n,y:r}=ja(e)?e.internals.positionAbsolute:Ma(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},Za=(e,t)=>Ja(Ka(qa(e),qa(t))),Qa=(e,t,n,r,i,a,o,s)=>{let c=Math.max(0,Math.min(e+n,i+o)-Math.max(e,i)),l=Math.max(0,Math.min(t+r,a+s)-Math.max(t,a));return Math.ceil(c*l)},$a=(e,t)=>Qa(e.x,e.y,e.width,e.height,t.x,t.y,t.width,t.height),eo=e=>to(e.width)&&to(e.height)&&to(e.x)&&to(e.y),to=e=>!isNaN(e)&&isFinite(e),no=(e,t)=>(e,t)=>{},ro=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),io=({x:e,y:t},[n,r,i],a=!1,o=[1,1])=>{let s={x:(e-n)/i,y:(t-r)/i};return a?ro(s,o):s},ao=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function oo(e,t){if(typeof e==`number`)return Math.floor((t-t/(1+e))*.5);if(typeof e==`string`&&e.endsWith(`px`)){let t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if(typeof e==`string`&&e.endsWith(`%`)){let n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function so(e,t,n){if(typeof e==`string`||typeof e==`number`){let r=oo(e,n),i=oo(e,t);return{top:r,right:i,bottom:r,left:i,x:i*2,y:r*2}}if(typeof e==`object`){let r=oo(e.top??e.y??0,n),i=oo(e.bottom??e.y??0,n),a=oo(e.left??e.x??0,t),o=oo(e.right??e.x??0,t);return{top:r,right:o,bottom:i,left:a,x:a+o,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function co(e,t,n,r,i,a){let{x:o,y:s}=ao(e,[t,n,r]),{x:c,y:l}=ao({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=i-c,d=a-l;return{left:Math.floor(o),top:Math.floor(s),right:Math.floor(u),bottom:Math.floor(d)}}var lo=(e,t,n,r,i,a)=>{let o=so(a,t,n),s=(t-o.x)/e.width,c=(n-o.y)/e.height,l=Va(Math.min(s,c),r,i),u=e.x+e.width/2,d=e.y+e.height/2,f=t/2-u*l,p=n/2-d*l,m=co(e,f,p,l,t,n),h={left:Math.min(m.left-o.left,0),top:Math.min(m.top-o.top,0),right:Math.min(m.right-o.right,0),bottom:Math.min(m.bottom-o.bottom,0)};return{x:f-h.left+h.right,y:p-h.top+h.bottom,zoom:l}},U=()=>typeof navigator<`u`&&navigator?.userAgent?.indexOf(`Mac`)>=0;function W(e){return e!=null&&e!==`parent`}function uo(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function fo(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function po(e,t={width:0,height:0},n,r,i){let a={...e},o=r.get(n);if(o){let e=o.origin||i;a.x+=o.internals.positionAbsolute.x-(t.width??0)*e[0],a.y+=o.internals.positionAbsolute.y-(t.height??0)*e[1]}return a}function mo(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ho(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function go(e){return{...xa,...e||{}}}function _o(e){return e===null?null:e?`valid`:`invalid`}function vo(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){let{x:a,y:o}=wo(e),s=io({x:a-(i?.left??0),y:o-(i?.top??0)},r),{x:c,y:l}=n?ro(s,t):s;return{xSnapped:c,ySnapped:l,...s}}var yo=e=>({width:e.offsetWidth,height:e.offsetHeight}),bo=e=>e?.getRootNode?.()||window?.document,xo=[`INPUT`,`SELECT`,`TEXTAREA`];function So(e){let t=e.composedPath?.()?.[0]||e.target;return t?.nodeType===1?xo.includes(t.nodeName)||t.hasAttribute(`contenteditable`)||!!t.closest(`.nokey`):!1}var Co=e=>`clientX`in e,wo=(e,t)=>{let n=Co(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},To=(e,t,n,r,i)=>{let a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...yo(t)}})};function Eo({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:a,targetControlX:o,targetControlY:s}){let c=e*.125+i*.375+o*.375+n*.125,l=t*.125+a*.375+s*.375+r*.125;return[c,l,Math.abs(c-e),Math.abs(l-t)]}function Do(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Oo({pos:e,x1:t,y1:n,x2:r,y2:i,c:a}){switch(e){case H.Left:return[t-Do(t-r,a),n];case H.Right:return[t+Do(r-t,a),n];case H.Top:return[t,n-Do(n-i,a)];case H.Bottom:return[t,n+Do(i-n,a)]}}function ko({sourceX:e,sourceY:t,sourcePosition:n=H.Bottom,targetX:r,targetY:i,targetPosition:a=H.Top,curvature:o=.25}){let[s,c]=Oo({pos:n,x1:e,y1:t,x2:r,y2:i,c:o}),[l,u]=Oo({pos:a,x1:r,y1:i,x2:e,y2:t,c:o}),[d,f,p,m]=Eo({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:s,sourceControlY:c,targetControlX:l,targetControlY:u});return[`M${e},${t} C${s},${c} ${l},${u} ${r},${i}`,d,f,p,m]}function Ao({sourceX:e,sourceY:t,targetX:n,targetY:r}){let i=Math.abs(n-e)/2,a=n0}var No=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||``}-${n}${r||``}`,Po=(e,t)=>t.some(t=>t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle)),Fo=(e,t,n={})=>{if(!e.source||!e.target)return n.onError?.(`006`,va.error006()),t;let r=n.getEdgeId||No,i;return i=ka(e)?{...e}:{...e,id:r(e)},Po(i,t)?t:(i.sourceHandle===null&&delete i.sourceHandle,i.targetHandle===null&&delete i.targetHandle,t.concat(i))};function Io({sourceX:e,sourceY:t,targetX:n,targetY:r}){let[i,a,o,s]=Ao({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,a,o,s]}var Lo={[H.Left]:{x:-1,y:0},[H.Right]:{x:1,y:0},[H.Top]:{x:0,y:-1},[H.Bottom]:{x:0,y:1}},Ro=({source:e,sourcePosition:t=H.Bottom,target:n})=>t===H.Left||t===H.Right?e.xMath.sqrt((t.x-e.x)**2+(t.y-e.y)**2);function Bo({source:e,sourcePosition:t=H.Bottom,target:n,targetPosition:r=H.Top,center:i,offset:a,stepPosition:o}){let s=Lo[t],c=Lo[r],l={x:e.x+s.x*a,y:e.y+s.y*a},u={x:n.x+c.x*a,y:n.y+c.y*a},d=Ro({source:l,sourcePosition:t,target:u}),f=d.x===0?`y`:`x`,p=d[f],m=[],h,g,_={x:0,y:0},v={x:0,y:0},[,,y,b]=Ao({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(s[f]*c[f]===-1){f===`x`?(h=i.x??l.x+(u.x-l.x)*o,g=i.y??(l.y+u.y)/2):(h=i.x??(l.x+u.x)/2,g=i.y??l.y+(u.y-l.y)*o);let e=[{x:h,y:l.y},{x:h,y:u.y}],t=[{x:l.x,y:g},{x:u.x,y:g}];m=s[f]===p?f===`x`?e:t:f===`x`?t:e}else{let i=[{x:l.x,y:u.y}],o=[{x:u.x,y:l.y}];if(m=f===`x`?s.x===p?o:i:s.y===p?i:o,t===r){let t=Math.abs(e[f]-n[f]);if(t<=a){let r=Math.min(a-1,a-t);s[f]===p?_[f]=(l[f]>e[f]?-1:1)*r:v[f]=(u[f]>n[f]?-1:1)*r}}if(t!==r){let e=f===`x`?`y`:`x`,t=s[f]===c[e],n=l[e]>u[e],r=l[e]=Math.max(Math.abs(d.y-m[0].y),Math.abs(y.y-m[0].y))?(h=(d.x+y.x)/2,g=m[0].y):(h=m[0].x,g=(d.y+y.y)/2)}let x={x:l.x+_.x,y:l.y+_.y},S={x:u.x+v.x,y:u.y+v.y};return[[e,...x.x!==m[0].x||x.y!==m[0].y?[x]:[],...m,...S.x!==m[m.length-1].x||S.y!==m[m.length-1].y?[S]:[],n],h,g,y,b]}function Vo(e,t,n,r){let i=Math.min(zo(e,t)/2,zo(t,n)/2,r),{x:a,y:o}=t;if(e.x===a&&a===n.x||e.y===o&&o===n.y)return`L${a} ${o}`;if(e.y===o){let t=e.xe.id===t):e[0])||null}function Jo(e,t){return e?typeof e==`string`?e:`${t?`${t}__`:``}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join(`&`)}`:``}function Yo(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){let a=new Set;return e.reduce((e,o)=>([o.markerStart||r,o.markerEnd||i].forEach(r=>{if(r&&typeof r==`object`){let i=Jo(r,t);a.has(i)||(e.push({id:i,color:r.color||n,...r}),a.add(i))}}),e),[]).sort((e,t)=>e.id.localeCompare(t.id))}var Xo=1e3,Zo=10,Qo={nodeOrigin:[0,0],nodeExtent:ya,elevateNodesOnSelect:!0,zIndexMode:`basic`,defaults:{}},$o={...Qo,checkEquality:!0};function es(e,t){let n={...e};for(let e in t)t[e]!==void 0&&(n[e]=t[e]);return n}function ts(e,t,n){let r=es(Qo,n);for(let n of e.values())if(n.parentId)os(n,e,t,r);else{let e=Ha(Ma(n,r.nodeOrigin),W(n.extent)?n.extent:r.nodeExtent,uo(n));n.internals.positionAbsolute=e}}function ns(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;let n=[],r=[];for(let t of e.handles){let i={id:t.id,width:t.width??1,height:t.height??1,nodeId:e.id,x:t.x,y:t.y,position:t.position,type:t.type};t.type===`source`?n.push(i):t.type===`target`&&r.push(i)}return{source:n,target:r}}function rs(e){return e===`manual`}function is(e,t,n,r={}){let i=es($o,r),a={i:0},o=new Map(t),s=i?.elevateNodesOnSelect&&!rs(i.zIndexMode)?Xo:0,c=e.length>0,l=!1;t.clear(),n.clear();for(let u of e){let e=o.get(u.id);if(i.checkEquality&&u===e?.internals.userNode)t.set(u.id,e);else{let n=Ha(Ma(u,i.nodeOrigin),W(u.extent)?u.extent:i.nodeExtent,uo(u));e={...i.defaults,...u,measured:{width:u.measured?.width,height:u.measured?.height},internals:{positionAbsolute:n,handleBounds:ns(u,e),z:ss(u,s,i.zIndexMode),userNode:u}},t.set(u.id,e)}(e.measured===void 0||e.measured.width===void 0||e.measured.height===void 0)&&!e.hidden&&(c=!1),u.parentId&&os(e,t,n,r,a),l||=u.selected??!1}return{nodesInitialized:c,hasSelectedNodes:l}}function as(e,t){if(!e.parentId)return;let n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function os(e,t,n,r,i){let{elevateNodesOnSelect:a,nodeOrigin:o,nodeExtent:s,zIndexMode:c}=es(Qo,r),l=e.parentId,u=t.get(l);if(!u){console.warn(`Parent node ${l} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}as(e,n),i&&!u.parentId&&u.internals.rootParentIndex===void 0&&c===`auto`&&(u.internals.rootParentIndex=++i.i,u.internals.z=u.internals.z+i.i*Zo),i&&u.internals.rootParentIndex!==void 0&&(i.i=u.internals.rootParentIndex);let{x:d,y:f,z:p}=cs(e,u,o,s,a&&!rs(c)?Xo:0,c),{positionAbsolute:m}=e.internals,h=d!==m.x||f!==m.y;(h||p!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:h?{x:d,y:f}:m,z:p}})}function ss(e,t,n){let r=to(e.zIndex)?e.zIndex:0;return rs(n)?r:r+(e.selected?t:0)}function cs(e,t,n,r,i,a){let{x:o,y:s}=t.internals.positionAbsolute,c=uo(e),l=Ma(e,n),u=W(e.extent)?Ha(l,e.extent,c):l,d=Ha({x:o+u.x,y:s+u.y},r,c);e.extent===`parent`&&(d=Ua(d,c,t));let f=ss(e,i,a),p=t.internals.z??0;return{x:d.x,y:d.y,z:p>=f?p+1:f}}function ls(e,t,n,r=[0,0]){let i=[],a=new Map;for(let n of e){let e=t.get(n.parentId);if(!e)continue;let r=Za(a.get(n.parentId)?.expandedRect??Ya(e),n.rect);a.set(n.parentId,{expandedRect:r,parent:e})}return a.size>0&&a.forEach(({expandedRect:t,parent:a},o)=>{let s=a.internals.positionAbsolute,c=uo(a),l=a.origin??r,u=t.x0||d>0||m||h)&&(i.push({id:o,type:`position`,position:{x:a.position.x-u+m,y:a.position.y-d+h}}),n.get(o)?.forEach(t=>{e.some(e=>e.id===t.id)||i.push({id:t.id,type:`position`,position:{x:t.position.x+u,y:t.position.y+d}})})),(c.width0){let e=ls(f,t,n,i);l.push(...e)}return{changes:l,updatedInternals:c}}async function ds({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:a}){if(!t||!e.x&&!e.y)return!1;let o=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,a]],r);return!!o&&(o.x!==n[0]||o.y!==n[1]||o.k!==n[2])}function fs(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function ps(e,t,n){e.clear(),t.clear();for(let r of n){let{source:n,target:i,sourceHandle:a=null,targetHandle:o=null}=r,s={edgeId:r.id,source:n,target:i,sourceHandle:a,targetHandle:o},c=`${n}-${a}--${i}-${o}`;fs(`source`,s,`${i}-${o}--${n}-${a}`,e,n,a),fs(`target`,s,c,e,i,o),t.set(r.id,r)}}function ms(e,t){if(!e.parentId)return!1;let n=t.get(e.parentId);return n?n.selected?!0:ms(n,t):!1}function hs(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function gs(e,t,n,r){let i=new Map;for(let[a,o]of e)if((o.selected||o.id===r)&&(!o.parentId||!ms(o,e))&&(o.draggable||t&&o.draggable===void 0)){let t=e.get(a);t&&i.set(a,{id:a,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return i}function _s({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){let i=[];for(let[e,a]of t){let t=n.get(e)?.internals.userNode;t&&i.push({...t,position:a.position,dragging:r})}if(!e)return[i[0],i];let a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:i[0],i]}function vs({dragItems:e,snapGrid:t,x:n,y:r}){let i=e.values().next().value;if(!i)return null;let a={x:n-i.distance.x,y:r-i.distance.y},o=ro(a,t);return{x:o.x-a.x,y:o.y-a.y}}function ys({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let a={x:null,y:null},o=0,s=new Map,c=!1,l={x:0,y:0},u=null,d=!1,f=null,p=!1,m=!1,h=null;function g({noDragClassName:g,handleSelector:_,domNode:v,isSelectable:y,nodeId:b,nodeClickDistance:x=0}){f=Bt(v);function S({x:e,y:n}){let{nodeLookup:i,nodeExtent:o,snapGrid:c,snapToGrid:l,nodeOrigin:u,onNodeDrag:d,onSelectionDrag:f,onError:p,updateNodePositions:g}=t();a={x:e,y:n};let _=!1,v=s.size>1,y=v&&o?qa(Pa(s)):null,x=v&&l?vs({dragItems:s,snapGrid:c,x:e,y:n}):null;for(let[t,r]of s){if(!i.has(t))continue;let a={x:e-r.distance.x,y:n-r.distance.y};l&&(a=x?{x:Math.round(a.x+x.x),y:Math.round(a.y+x.y)}:ro(a,c));let s=null;if(v&&o&&!r.extent&&y){let{positionAbsolute:e}=r.internals,t=e.x-y.x+o[0][0],n=e.x+r.measured.width-y.x2+o[1][0],i=e.y-y.y+o[0][1],a=e.y+r.measured.height-y.y2+o[1][1];s=[[t,i],[n,a]]}let{position:d,positionAbsolute:f}=za({nodeId:t,nextPosition:a,nodeLookup:i,nodeExtent:s||o,nodeOrigin:u,onError:p});_=_||r.position.x!==d.x||r.position.y!==d.y,r.position=d,r.internals.positionAbsolute=f}if(m||=_,_&&(g(s,!0),h&&(r||d||!b&&f))){let[e,t]=_s({nodeId:b,dragItems:s,nodeLookup:i});r?.(h,s,e,t),d?.(h,e,t),b||f?.(h,t)}}async function C(){if(!u)return;let{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:i}=t();if(!i){c=!1,cancelAnimationFrame(o);return}let[s,d]=Ga(l,u,r);(s!==0||d!==0)&&(a.x=(a.x??0)-s/e[2],a.y=(a.y??0)-d/e[2],await n({x:s,y:d})&&S(a)),o=requestAnimationFrame(C)}function w(r){let{nodeLookup:i,multiSelectionActive:o,nodesDraggable:c,transform:l,snapGrid:f,snapToGrid:p,selectNodesOnDrag:m,onNodeDragStart:h,onSelectionDragStart:g,unselectNodesAndEdges:_}=t();d=!0,(!m||!y)&&!o&&b&&(i.get(b)?.selected||_()),y&&m&&b&&e?.(b);let v=vo(r.sourceEvent,{transform:l,snapGrid:f,snapToGrid:p,containerBounds:u});if(a=v,s=gs(i,c,v,b),s.size>0&&(n||h||!b&&g)){let[e,t]=_s({nodeId:b,dragItems:s,nodeLookup:i});n?.(r.sourceEvent,s,e,t),h?.(r.sourceEvent,e,t),b||g?.(r.sourceEvent,t)}}let T=tn().clickDistance(x).on(`start`,e=>{let{domNode:n,nodeDragThreshold:r,transform:i,snapGrid:o,snapToGrid:s}=t();u=n?.getBoundingClientRect()||null,p=!1,m=!1,h=e.sourceEvent,r===0&&w(e),a=vo(e.sourceEvent,{transform:i,snapGrid:o,snapToGrid:s,containerBounds:u}),l=wo(e.sourceEvent,u)}).on(`drag`,e=>{let{autoPanOnNodeDrag:n,transform:r,snapGrid:i,snapToGrid:o,nodeDragThreshold:f,nodeLookup:m}=t(),g=vo(e.sourceEvent,{transform:r,snapGrid:i,snapToGrid:o,containerBounds:u});if(h=e.sourceEvent,(e.sourceEvent.type===`touchmove`&&e.sourceEvent.touches.length>1||b&&!m.has(b))&&(p=!0),!p){if(!c&&n&&d&&(c=!0,C()),!d){let t=wo(e.sourceEvent,u),n=t.x-l.x,r=t.y-l.y;Math.sqrt(n*n+r*r)>f&&w(e)}(a.x!==g.xSnapped||a.y!==g.ySnapped)&&s&&d&&(l=wo(e.sourceEvent,u),S(g))}}).on(`end`,e=>{if(!d||p){p&&s.size>0&&t().updateNodePositions(s,!1);return}if(c=!1,d=!1,cancelAnimationFrame(o),s.size>0){let{nodeLookup:n,updateNodePositions:r,onNodeDragStop:a,onSelectionDragStop:o}=t();if(m&&=(r(s,!1),!1),i||a||!b&&o){let[t,r]=_s({nodeId:b,dragItems:s,nodeLookup:n,dragging:!1});i?.(e.sourceEvent,s,t,r),a?.(e.sourceEvent,t,r),b||o?.(e.sourceEvent,r)}}}).filter(e=>{let t=e.target;return!e.button&&(!g||!hs(t,`.${g}`,v))&&(!_||hs(t,_,v))});f.call(T)}function _(){f?.on(`.drag`,null)}return{update:g,destroy:_}}function bs(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())$a(i,Ya(e))>0&&r.push(e);return r}var xs=250;function Ss(e,t,n,r){let i=[],a=1/0,o=bs(e,n,t+xs);for(let n of o){let o=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=Ko(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function Cs(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===`strict`?o.internals.handleBounds?.[t]:[...o.internals.handleBounds?.source??[],...o.internals.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...Ko(o,c,c.position,!0)}:c}function ws(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function Ts(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}var Es=()=>!0;function Ds(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:a,isTarget:o,domNode:s,nodeLookup:c,lib:l,autoPanOnConnect:u,flowId:d,panBy:f,cancelConnection:p,onConnectStart:m,onConnect:h,onConnectEnd:g,isValidConnection:_=Es,onReconnectEnd:v,updateConnection:y,getTransform:b,getFromHandle:x,autoPanSpeed:S,dragThreshold:C=1,handleDomNode:w}){let T=bo(e.target),E=0,D,{x:O,y:k}=wo(e),A=ws(a,w),j=s?.getBoundingClientRect(),M=!1;if(!j||!A)return;let N=Cs(i,A,r,c,t);if(!N)return;let P=wo(e,j),ee=!1,F=null,I=!1,te=null;function ne(){if(!u||!j)return;let[e,t]=Ga(P,j,S);f({x:e,y:t}),E=requestAnimationFrame(ne)}let L={...N,nodeId:i,type:A,position:N.position},R=c.get(i),z={inProgress:!0,isValid:null,from:Ko(R,L,H.Left,!0),fromHandle:L,fromPosition:L.position,fromNode:R,to:P,toHandle:null,toPosition:Oa[L.position],toNode:null,pointer:P};function B(){M=!0,y(z),m?.(e,{nodeId:i,handleId:r,handleType:A})}C===0&&B();function re(e){if(!M){let{x:t,y:n}=wo(e),r=t-O,i=n-k;if(!(r*r+i*i>C*C))return;B()}if(!x()||!L){ie(e);return}let a=b();P=wo(e,j),D=Ss(io(P,a,!1,[1,1]),n,c,L),ee||=(ne(),!0);let s=Os(e,{handle:D,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:o?`target`:`source`,isValidConnection:_,doc:T,lib:l,flowId:d,nodeLookup:c});te=s.handleDomNode,F=s.connection,I=Ts(!!D,s.isValid);let u=c.get(i),f=u?Ko(u,L,H.Left,!0):z.from,p={...z,from:f,isValid:I,to:s.toHandle&&I?ao({x:s.toHandle.x,y:s.toHandle.y},a):P,toHandle:s.toHandle,toPosition:I&&s.toHandle?s.toHandle.position:Oa[L.position],toNode:s.toHandle?c.get(s.toHandle.nodeId):null,pointer:P};y(p),z=p}function ie(e){if(!(`touches`in e&&e.touches.length>0)){if(M){(D||te)&&F&&I&&h?.(F);let{inProgress:t,...n}=z,r={...n,toPosition:z.toHandle?z.toPosition:null};g?.(e,r),a&&v?.(e,r)}p(),cancelAnimationFrame(E),ee=!1,I=!1,F=null,te=null,T.removeEventListener(`mousemove`,re),T.removeEventListener(`mouseup`,ie),T.removeEventListener(`touchmove`,re),T.removeEventListener(`touchend`,ie)}}T.addEventListener(`mousemove`,re),T.addEventListener(`mouseup`,ie),T.addEventListener(`touchmove`,re),T.addEventListener(`touchend`,ie)}function Os(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=Es,nodeLookup:u}){let d=a===`target`,f=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=wo(e),h=o.elementFromPoint(p,m),g=h?.classList.contains(`${s}-flow__handle`)?h:f,_={handleDomNode:g,isValid:!1,connection:null,toHandle:null};if(g){let e=ws(void 0,g),t=g.getAttribute(`data-nodeid`),a=g.getAttribute(`data-handleid`),o=g.classList.contains(`connectable`),s=g.classList.contains(`connectableend`);if(!t||!e)return _;let c={source:d?t:r,sourceHandle:d?a:i,target:d?r:t,targetHandle:d?i:a};_.connection=c,_.isValid=o&&s&&(n===Sa.Strict?d&&e===`source`||!d&&e===`target`:t!==r||a!==i)&&l(c),_.toHandle=Cs(t,e,a,u,n,!0)}return _}var ks={onPointerDown:Ds,isValid:Os};function As({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){let i=Bt(e);function a({translateExtent:e,width:a,height:o,zoomStep:s=1,pannable:c=!0,zoomable:l=!0,inversePan:u=!1}){let d=e=>{if(e.sourceEvent.type!==`wheel`||!t)return;let r=n(),i=e.sourceEvent.ctrlKey&&U()?10:1,a=-e.sourceEvent.deltaY*(e.sourceEvent.deltaMode===1?.05:e.sourceEvent.deltaMode?1:.002)*s,o=r[2]*2**(a*i);t.scaleTo(o)},f=[0,0],p=_a().on(`start`,e=>{(e.sourceEvent.type===`mousedown`||e.sourceEvent.type===`touchstart`)&&(f=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])}).on(`zoom`,c?i=>{let s=n();if(i.sourceEvent.type!==`mousemove`&&i.sourceEvent.type!==`touchmove`||!t)return;let c=[i.sourceEvent.clientX??i.sourceEvent.touches[0].clientX,i.sourceEvent.clientY??i.sourceEvent.touches[0].clientY],l=[c[0]-f[0],c[1]-f[1]];f=c;let d=r()*Math.max(s[2],Math.log(s[2]))*(u?-1:1),p={x:s[0]-l[0]*d,y:s[1]-l[1]*d},m=[[0,0],[a,o]];t.setViewportConstrained({x:p.x,y:p.y,zoom:s[2]},m,e)}:null).on(`zoom.wheel`,l?d:null);i.call(p,{})}function o(){i.on(`zoom`,null)}return{update:a,destroy:o,pointer:Ht}}var js=e=>({x:e.x,y:e.y,zoom:e.k}),Ms=({x:e,y:t,zoom:n})=>sa.translate(e,t).scale(n),Ns=(e,t)=>e.target.closest(`.${t}`),Ps=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Fs=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Is=(e,t=0,n=Fs,r=()=>{})=>{let i=typeof t==`number`&&t>0;return i||r(),i?e.transition().duration(t).ease(n).on(`end`,r):e},Ls=e=>{let t=e.ctrlKey&&U()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Rs({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:a,zoomOnPinch:o,onPanZoomStart:s,onPanZoom:c,onPanZoomEnd:l}){return u=>{if(Ns(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();let d=n.property(`__zoom`).k||1;if(u.ctrlKey&&o){let e=Ht(u),t=d*2**Ls(u);r.scaleTo(n,t,e,u);return}let f=u.deltaMode===1?20:1,p=i===Ca.Vertical?0:u.deltaX*f,m=i===Ca.Horizontal?0:u.deltaY*f;!U()&&u.shiftKey&&i!==Ca.Vertical&&(p=u.deltaY*f,m=0),r.translateBy(n,-(p/d)*a,-(m/d)*a,{internal:!0});let h=js(n.property(`__zoom`));clearTimeout(e.panScrollTimeout),e.isPanScrolling?c?.(u,h):(e.isPanScrolling=!0,s?.(u,h)),e.panScrollTimeout=setTimeout(()=>{l?.(u,h),e.isPanScrolling=!1},150)}}function zs({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){let a=r.type===`wheel`,o=!t&&a&&!r.ctrlKey,s=Ns(r,e);if(r.ctrlKey&&a&&s&&r.preventDefault(),o||s)return null;r.preventDefault(),n.call(this,r,i)}}function Bs({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;let i=js(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,r.sourceEvent?.type===`mousedown`&&t(!0),n&&n?.(r.sourceEvent,i)}}function Vs({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return a=>{e.usedRightMouseButton=!!(n&&Ps(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),i&&!a.sourceEvent?.internal&&i?.(a.sourceEvent,js(a.transform))}}function Hs({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:a}){return o=>{if(!o.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&Ps(t,e.mouseButton??0)&&!e.usedRightMouseButton&&o.sourceEvent&&a(o.sourceEvent),e.usedRightMouseButton=!1,r(!1),i)){let t=js(o.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{i?.(o.sourceEvent,t)},n?150:0)}}}function Us({panActivationKeyPressed:e,zoomActivationKeyPressed:t,zoomOnScroll:n,zoomOnPinch:r,panOnDrag:i,panOnScroll:a,zoomOnDoubleClick:o,userSelectionActive:s,noWheelClassName:c,noPanClassName:l,lib:u,connectionInProgress:d}){return f=>{let p=t||n,m=r&&f.ctrlKey,h=f.type===`wheel`;if(f.button===1&&f.type===`mousedown`&&(Ns(f,`${u}-flow__node`)||Ns(f,`${u}-flow__edge`)||Ns(f,`${u}-flow__selection`)||Ns(f,`${u}-flow__nodesselection`)))return!0;if(!i&&!p&&!a&&!o&&!r||s||d&&!h||Ns(f,c)&&h||Ns(f,l)&&(!h||a&&h&&!t)||!r&&f.ctrlKey&&h)return!1;if(!r&&f.type===`touchstart`&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!a&&!m&&h||!i&&(f.type===`mousedown`||f.type===`touchstart`)||Array.isArray(i)&&!i.includes(f.button)&&f.type===`mousedown`)return!1;let g=Array.isArray(i)&&i.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||h||e)&&g}}function Ws({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:i,onPanZoom:a,onPanZoomStart:o,onPanZoomEnd:s,onDraggingChange:c}){let l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect(),d=[[0,0],[u.width,u.height]];(typeof ResizeObserver<`u`?new ResizeObserver(e=>{let t=e[0];t&&(d=[[0,0],[t.contentRect.width,t.contentRect.height]])}):null)?.observe(e);let f=_a().extent(()=>d).scaleExtent([t,n]).translateExtent(r),p=Bt(e).call(f);y({x:i.x,y:i.y,zoom:Va(i.zoom,t,n)},[[0,0],[u.width,u.height]],r);let m=p.on(`wheel.zoom`),h=p.on(`dblclick.zoom`);f.wheelDelta(Ls);async function g(e,t){return p?new Promise(n=>{f?.interpolate(t?.interpolate===`linear`?ar:yr).transform(Is(p,t?.duration,t?.ease,()=>n(!0)),e)}):!1}function _({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:i,panOnDrag:u,panOnScrollMode:d,panOnScrollSpeed:g,preventScrolling:_,zoomOnPinch:y,zoomOnScroll:b,zoomOnDoubleClick:x,panActivationKeyPressed:S=!1,zoomActivationKeyPressed:C,lib:w,onTransformChange:T,connectionInProgress:E,paneClickDistance:D,selectionOnDrag:O}){r&&!l.isZoomingOrPanning&&v();let k=i&&!C&&!r;f.clickDistance(O?1/0:!to(D)||D<0?0:D);let A=k?Rs({zoomPanValues:l,noWheelClassName:e,d3Selection:p,d3Zoom:f,panOnScrollMode:d,panOnScrollSpeed:g,zoomOnPinch:y,onPanZoomStart:o,onPanZoom:a,onPanZoomEnd:s}):zs({noWheelClassName:e,preventScrolling:_,d3ZoomHandler:m});p.on(`wheel.zoom`,A,{passive:!1});let j=Bs({zoomPanValues:l,onDraggingChange:c,onPanZoomStart:o});f.on(`start`,j);let M=Vs({zoomPanValues:l,panOnDrag:u,onPaneContextMenu:!!n,onPanZoom:a,onTransformChange:T});f.on(`zoom`,M);let N=Hs({zoomPanValues:l,panOnDrag:u,panOnScroll:i,onPaneContextMenu:n,onPanZoomEnd:s,onDraggingChange:c});f.on(`end`,N);let P=Us({panActivationKeyPressed:S,zoomActivationKeyPressed:C,panOnDrag:u,zoomOnScroll:b,panOnScroll:i,zoomOnDoubleClick:x,zoomOnPinch:y,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:w,connectionInProgress:E});f.filter(P),x?p.on(`dblclick.zoom`,h):p.on(`dblclick.zoom`,null)}function v(){f.on(`zoom`,null)}async function y(e,t,n){let r=Ms(e),i=f?.constrain()(r,t,n);return i&&await g(i),i}async function b(e,t){let n=Ms(e);return await g(n,t),n}function x(e){if(p){let t=Ms(e),n=p.property(`__zoom`);(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&f?.transform(p,t,null,{sync:!0})}}function S(){let e=p?ca(p.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}}async function C(e,t){return p?new Promise(n=>{f?.interpolate(t?.interpolate===`linear`?ar:yr).scaleTo(Is(p,t?.duration,t?.ease,()=>n(!0)),e)}):!1}async function w(e,t){return p?new Promise(n=>{f?.interpolate(t?.interpolate===`linear`?ar:yr).scaleBy(Is(p,t?.duration,t?.ease,()=>n(!0)),e)}):!1}function T(e){f?.scaleExtent(e)}function E(e){f?.translateExtent(e)}function D(e){let t=!to(e)||e<0?0:e;f?.clickDistance(t)}return{update:_,destroy:v,setViewport:b,setViewportConstrained:y,getViewport:S,scaleTo:C,scaleBy:w,setScaleExtent:T,setTranslateExtent:E,syncViewport:x,setClickDistance:D}}var Gs;(function(e){e.Line=`line`,e.Handle=`handle`})(Gs||={});function Ks({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:a}){let o=e-t,s=n-r,c=[o>0?1:o<0?-1:0,s>0?1:s<0?-1:0];return o&&i&&(c[0]*=-1),s&&a&&(c[1]*=-1),c}function qs(e){return{isHorizontal:e.includes(`right`)||e.includes(`left`),isVertical:e.includes(`bottom`)||e.includes(`top`),affectsX:e.includes(`left`),affectsY:e.includes(`top`)}}function Js(e,t){return Math.max(0,t-e)}function Ys(e,t){return Math.max(0,e-t)}function Xs(e,t,n){return Math.max(0,t-e,e-n)}function Zs(e,t){return e?!t:t}function Qs(e,t,n,r,i,a,o,s){let{affectsX:c,affectsY:l}=t,{isHorizontal:u,isVertical:d}=t,f=u&&d,{xSnapped:p,ySnapped:m}=n,{minWidth:h,maxWidth:g,minHeight:_,maxHeight:v}=r,{x:y,y:b,width:x,height:S,aspectRatio:C}=e,w=Math.floor(u?p-e.pointerX:0),T=Math.floor(d?m-e.pointerY:0),E=x+(c?-w:w),D=S+(l?-T:T),O=-a[0]*x,k=-a[1]*S,A=Xs(E,h,g),j=Xs(D,_,v);if(o){let e=0,t=0;c&&w<0?e=Js(y+w+O,o[0][0]):!c&&w>0&&(e=Ys(y+E+O,o[1][0])),l&&T<0?t=Js(b+T+k,o[0][1]):!l&&T>0&&(t=Ys(b+D+k,o[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(s){let e=0,t=0;c&&w>0?e=Ys(y+w,s[0][0]):!c&&w<0&&(e=Js(y+E,s[1][0])),l&&T>0?t=Ys(b+T,s[0][1]):!l&&T<0&&(t=Js(b+D,s[1][1])),A=Math.max(A,e),j=Math.max(j,t)}if(i){if(u){let e=Xs(E/C,_,v)*C;if(A=Math.max(A,e),o){let e=0;e=!c&&!l||c&&!l&&f?Ys(b+k+E/C,o[1][1])*C:Js(b+k+(c?w:-w)/C,o[0][1])*C,A=Math.max(A,e)}if(s){let e=0;e=!c&&!l||c&&!l&&f?Js(b+E/C,s[1][1])*C:Ys(b+(c?w:-w)/C,s[0][1])*C,A=Math.max(A,e)}}if(d){let e=Xs(D*C,h,g)/C;if(j=Math.max(j,e),o){let e=0;e=!c&&!l||l&&!c&&f?Ys(y+D*C+O,o[1][0])/C:Js(y+(l?T:-T)*C+O,o[0][0])/C,j=Math.max(j,e)}if(s){let e=0;e=!c&&!l||l&&!c&&f?Js(y+D*C,s[1][0])/C:Ys(y+(l?T:-T)*C,s[0][0])/C,j=Math.max(j,e)}}}T+=T<0?j:-j,w+=w<0?A:-A,i&&(f?E>D*C?T=(Zs(c,l)?-w:w)/C:w=(Zs(c,l)?-T:T)*C:u?(T=w/C,l=c):(w=T*C,c=l));let M=c?y+w:y,N=l?b+T:b;return{width:x+(c?-w:w),height:S+(l?-T:T),x:a[0]*w*(c?-1:1)+M,y:a[1]*T*(l?-1:1)+N}}var $s={width:0,height:0,x:0,y:0},ec={...$s,pointerX:0,pointerY:0,aspectRatio:1};function tc(e,t,n){let r=t.position.x+e.position.x,i=t.position.y+e.position.y,a=e.measured.width??0,o=e.measured.height??0,s=n[0]*a,c=n[1]*o;return[[r-s,i-c],[r+a-s,i+o-c]]}function nc({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){let a=Bt(e),o={controlDirection:qs(`bottom-right`),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function s({controlPosition:e,boundaries:s,keepAspectRatio:c,resizeDirection:l,onResizeStart:u,onResize:d,onResizeEnd:f,shouldResize:p}){let m={...$s},h={...ec};o={boundaries:s,resizeDirection:l,keepAspectRatio:c,controlDirection:qs(e)};let g,_=null,v=[],y,b,x,S=!1,C=tn().on(`start`,e=>{let{nodeLookup:r,transform:i,snapGrid:a,snapToGrid:o,nodeOrigin:s,paneDomNode:c}=n();if(g=r.get(t),!g)return;_=c?.getBoundingClientRect()??null;let{xSnapped:l,ySnapped:d}=vo(e.sourceEvent,{transform:i,snapGrid:a,snapToGrid:o,containerBounds:_});m={width:g.measured.width??0,height:g.measured.height??0,x:g.position.x??0,y:g.position.y??0},h={...m,pointerX:l,pointerY:d,aspectRatio:m.width/m.height},y=void 0,b=W(g.extent)?g.extent:void 0,g.parentId&&(g.extent===`parent`||g.expandParent)&&(y=r.get(g.parentId)),y&&g.extent===`parent`&&(b=[[0,0],[y.measured.width,y.measured.height]]),v=[],x=void 0;for(let[e,n]of r)if(n.parentId===t&&(v.push({id:e,position:{...n.position},extent:n.extent}),n.extent===`parent`||n.expandParent)){let e=tc(n,g,n.origin??s);x=x?[[Math.min(e[0][0],x[0][0]),Math.min(e[0][1],x[0][1])],[Math.max(e[1][0],x[1][0]),Math.max(e[1][1],x[1][1])]]:e}u?.(e,{...m})}).on(`drag`,e=>{let{transform:t,snapGrid:i,snapToGrid:a,nodeOrigin:s}=n(),c=vo(e.sourceEvent,{transform:t,snapGrid:i,snapToGrid:a,containerBounds:_}),l=[];if(!g)return;let{x:u,y:f,width:C,height:w}=m,T={},E=g.origin??s,{width:D,height:O,x:k,y:A}=Qs(h,o.controlDirection,c,o.boundaries,o.keepAspectRatio,E,b,x),j=D!==C,M=O!==w,N=k!==u&&j,P=A!==f&&M;if(!N&&!P&&!j&&!M)return;if((N||P||E[0]===1||E[1]===1)&&(T.x=N?k:m.x,T.y=P?A:m.y,m.x=T.x,m.y=T.y,v.length>0)){let e=k-u,t=A-f;for(let n of v)n.position={x:n.position.x-e+E[0]*(D-C),y:n.position.y-t+E[1]*(O-w)},l.push(n)}if((j||M)&&(T.width=j&&(!o.resizeDirection||o.resizeDirection===`horizontal`)?D:m.width,T.height=M&&(!o.resizeDirection||o.resizeDirection===`vertical`)?O:m.height,m.width=T.width,m.height=T.height),y&&g.expandParent){let e=E[0]*(T.width??0);T.x&&T.x{S&&=(f?.(e,{...m}),i?.({...m}),!1)});a.call(C)}function c(){a.on(`.drag`,null)}return{update:s,destroy:c}}var rc=o((e=>{var t=u();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),ic=o(((e,t)=>{t.exports=rc()})),ac=o((e=>{var t=u(),n=ic();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),oc=c(o(((e,t)=>{t.exports=ac()}))(),1),sc=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{n.clear()}},o=t=e(r,i,a);return a},cc=e=>e?sc(e):sc,{useDebugValue:lc}=y.default,{useSyncExternalStoreWithSelector:uc}=oc.default,dc=e=>e;function fc(e,t=dc,n){let r=uc(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return lc(r),r}var pc=(e,t)=>{let n=cc(e),r=(e,r=t)=>fc(n,e,r);return Object.assign(r,n),r},mc=(e,t)=>e?pc(e,t):pc;function hc(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var gc=m(),_c=(0,y.createContext)(null),vc=_c.Provider,yc=va.error001(`react`);function G(e,t){let n=(0,y.useContext)(_c);if(n===null)throw Error(yc);return fc(n,e,t)}function bc(){let e=(0,y.useContext)(_c);if(e===null)throw Error(yc);return(0,y.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}var xc={display:`none`},Sc={position:`absolute`,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0px, 0px, 0px, 0px)`,clipPath:`inset(100%)`},Cc=`react-flow__node-desc`,wc=`react-flow__edge-desc`,Tc=`react-flow__aria-live`,Ec=e=>e.ariaLiveMessage,Dc=e=>e.ariaLabelConfig;function Oc({rfId:e}){let t=G(Ec);return(0,x.jsx)(`div`,{id:`${Tc}-${e}`,"aria-live":`assertive`,"aria-atomic":`true`,style:Sc,children:t})}function kc({rfId:e,disableKeyboardA11y:t}){let n=G(Dc);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{id:`${Cc}-${e}`,style:xc,children:t?n[`node.a11yDescription.default`]:n[`node.a11yDescription.keyboardDisabled`]}),(0,x.jsx)(`div`,{id:`${wc}-${e}`,style:xc,children:n[`edge.a11yDescription.default`]}),!t&&(0,x.jsx)(Oc,{rfId:e})]})}var Ac=(0,y.forwardRef)(({position:e=`top-left`,children:t,className:n,style:r,...i},a)=>{let o=`${e}`.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__panel`,n,...o]),style:r,ref:a,...i,children:t})});Ac.displayName=`Panel`;var jc=`https://reactflow.dev?utm_source=attribution`;function Mc({proOptions:e,position:t=`bottom-right`}){return(0,y.useEffect)(()=>{},[]),e?.hideAttribution?null:(0,x.jsx)(Ac,{position:t,className:`react-flow__attribution`,"data-message":`Please only hide this attribution when you are subscribed to React Flow Pro: ${jc}`,children:(0,x.jsx)(`a`,{href:jc,target:`_blank`,rel:`noopener noreferrer`,"aria-label":`React Flow attribution`,children:`React Flow`})})}var Nc=e=>{let t=[],n=[];for(let[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(let[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},Pc=e=>e.id;function Fc(e,t){return hc(e.selectedNodes.map(Pc),t.selectedNodes.map(Pc))&&hc(e.selectedEdges.map(Pc),t.selectedEdges.map(Pc))}function Ic({onSelectionChange:e}){let t=bc(),{selectedNodes:n,selectedEdges:r}=G(Nc,Fc);return(0,y.useEffect)(()=>{let i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach(e=>e(i))},[n,r,e]),null}var Lc=e=>!!e.onSelectionChangeHandlers;function Rc({onSelectionChange:e}){let t=G(Lc);return e||t?(0,x.jsx)(Ic,{onSelectionChange:e}):null}var zc=[0,0],Bc={x:0,y:0,zoom:1},Vc=[...`nodes.edges.defaultNodes.defaultEdges.onConnect.onConnectStart.onConnectEnd.onClickConnectStart.onClickConnectEnd.nodesDraggable.autoPanOnNodeFocus.nodesConnectable.nodesFocusable.edgesFocusable.edgesReconnectable.elevateNodesOnSelect.elevateEdgesOnSelect.minZoom.maxZoom.nodeExtent.onNodesChange.onEdgesChange.elementsSelectable.connectionMode.snapGrid.snapToGrid.translateExtent.connectOnClick.defaultEdgeOptions.fitView.fitViewOptions.onNodesDelete.onEdgesDelete.onDelete.onNodeDrag.onNodeDragStart.onNodeDragStop.onSelectionDrag.onSelectionDragStart.onSelectionDragStop.onMoveStart.onMove.onMoveEnd.noPanClassName.nodeOrigin.autoPanOnConnect.autoPanOnNodeDrag.onError.connectionRadius.isValidConnection.selectNodesOnDrag.nodeDragThreshold.connectionDragThreshold.onBeforeDelete.debug.autoPanSpeed.ariaLabelConfig.zIndexMode`.split(`.`),`rfId`],Hc=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),Uc={translateExtent:ya,nodeOrigin:zc,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:`nopan`,rfId:`1`};function Wc(e){let{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:a,setNodeExtent:o,reset:s,setDefaultNodesAndEdges:c}=G(Hc,hc),l=bc();(0,y.useEffect)(()=>(c(e.defaultNodes,e.defaultEdges),()=>{u.current=Uc,s()}),[]);let u=(0,y.useRef)(Uc);return(0,y.useEffect)(()=>{for(let s of Vc){let c=e[s];c!==u.current[s]&&e[s]!==void 0&&(s===`nodes`?t(c):s===`edges`?n(c):s===`minZoom`?r(c):s===`maxZoom`?i(c):s===`translateExtent`?a(c):s===`nodeExtent`?o(c):s===`ariaLabelConfig`?l.setState({ariaLabelConfig:go(c)}):s===`fitView`?l.setState({fitViewQueued:c}):s===`fitViewOptions`?l.setState({fitViewOptions:c}):l.setState({[s]:c}))}u.current=e},Vc.map(t=>e[t])),null}function Gc(){return typeof window>`u`||!window.matchMedia?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function Kc(e){let[t,n]=(0,y.useState)(e===`system`?null:e);return(0,y.useEffect)(()=>{if(e!==`system`){n(e);return}let t=Gc(),r=()=>n(t?.matches?`dark`:`light`);return r(),t?.addEventListener(`change`,r),()=>{t?.removeEventListener(`change`,r)}},[e]),t===null?Gc()?.matches?`dark`:`light`:t}var qc=typeof document<`u`?document:null;function Jc(e=null,t={target:qc,actInsideInputWithModifier:!0}){let[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(!1),a=(0,y.useRef)(new Set([])),[o,s]=(0,y.useMemo)(()=>{if(e!==null){let t=(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`).map(e=>e.replace(/\+/g,` `).replace(` `,` +`).split(` `));return[t,t.reduce((e,t)=>e.concat(...t),[])]}return[[],[]]},[e]);return(0,y.useEffect)(()=>{let n=t?.target??qc,c=t?.actInsideInputWithModifier??!0;if(e!==null){let e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!c)&&So(e))return!1;let n=Xc(e.code,s);if(a.current.add(e[n]),Yc(o,a.current,!1)){let n=e.composedPath?.()?.[0]||e.target,a=n?.nodeName===`BUTTON`||n?.nodeName===`A`;t.preventDefault!==!1&&(i.current||!a)&&e.preventDefault(),r(!0)}},l=e=>{let t=Xc(e.code,s);Yc(o,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(e[t]),e.key===`Meta`&&a.current.clear(),i.current=!1},u=()=>{a.current.clear(),r(!1)};return n?.addEventListener(`keydown`,e),n?.addEventListener(`keyup`,l),window.addEventListener(`blur`,u),window.addEventListener(`contextmenu`,u),()=>{n?.removeEventListener(`keydown`,e),n?.removeEventListener(`keyup`,l),window.removeEventListener(`blur`,u),window.removeEventListener(`contextmenu`,u)}}},[e,r]),n}function Yc(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function Xc(e,t){return t.includes(e)?`code`:`key`}var Zc=()=>{let e=bc();return(0,y.useMemo)(()=>({zoomIn:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):!1},zoomOut:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):!1},zoomTo:async(t,n)=>{let{panZoom:r}=e.getState();return r?r.scaleTo(t,n):!1},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,i,a],panZoom:o}=e.getState();return o?(await o.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??a},n),!0):!1},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:i,minZoom:a,maxZoom:o,panZoom:s}=e.getState(),c=lo(t,r,i,a,o,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0):!1},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:i,snapToGrid:a,domNode:o}=e.getState();if(!o)return t;let{x:s,y:c}=o.getBoundingClientRect(),l={x:t.x-s,y:t.y-c},u=n.snapGrid??i;return io(l,r,n.snapToGrid??a,u)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:i,y:a}=r.getBoundingClientRect(),o=ao(t,n);return{x:o.x+i,y:o.y+a}}}),[])};function Qc(e,t){let n=[],r=new Map,i=[];for(let t of e)if(t.type===`add`){i.push(t);continue}else if(t.type===`remove`||t.type===`replace`)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if(t[0].type===`remove`)continue;if(t[0].type===`replace`){n.push({...t[0].item});continue}let i={...e};for(let e of t)$c(e,i);n.push(i)}return i.length&&i.forEach(e=>{e.index===void 0?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function $c(e,t){switch(e.type){case`select`:t.selected=e.selected;break;case`position`:e.position!==void 0&&(t.position=e.position),e.dragging!==void 0&&(t.dragging=e.dragging);break;case`dimensions`:e.dimensions!==void 0&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes===`width`)&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes===`height`)&&(t.height=e.dimensions.height))),typeof e.resizing==`boolean`&&(t.resizing=e.resizing)}}function el(e,t){return Qc(e,t)}function tl(e,t){return Qc(e,t)}function nl(e,t){return{id:e,type:`select`,selected:t}}function rl(e,t=new Set,n=!1){let r=[];for(let[i,a]of e){let e=t.has(i);!(a.selected===void 0&&!e)&&a.selected!==e&&(n&&(a.selected=e),r.push(nl(a.id,e)))}return r}function il({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,i]of e.entries()){let e=t.get(i.id),a=e?.internals?.userNode??e;a!==void 0&&a!==i&&n.push({id:i.id,item:i,type:`replace`}),a===void 0&&n.push({item:i,type:`add`,index:r})}for(let[e]of t)r.get(e)===void 0&&n.push({id:e,type:`remove`});return n}function al(e){return{id:e.id,type:`remove`}}var ol=no(`React Flow`,`https://reactflow.dev/`);function sl(e,t,n={}){return Fo(e,t,{...n,onError:n.onError??ol})}var cl=e=>Aa(e),ll=e=>ka(e);function ul(e){return(0,y.forwardRef)(e)}var dl=typeof window<`u`?y.useLayoutEffect:y.useEffect;function fl(e){let[t,n]=(0,y.useState)(BigInt(0)),[r]=(0,y.useState)(()=>pl(()=>n(e=>e+BigInt(1))));return dl(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}function pl(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var ml=(0,y.createContext)(null);function hl({children:e}){let t=bc(),n=fl((0,y.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:a,nodeLookup:o,fitViewQueued:s,onNodesChangeMiddlewareMap:c}=t.getState(),l=n;for(let t of e)l=typeof t==`function`?t(l):t;let u=il({items:l,lookup:o});for(let e of c.values())u=e(u);i&&r(l),u.length>0?a?.(u):s&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=fl((0,y.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:a,edgeLookup:o}=t.getState(),s=n;for(let t of e)s=typeof t==`function`?t(s):t;i?r(s):a&&a(il({items:s,lookup:o}))},[])),i=(0,y.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,x.jsx)(ml.Provider,{value:i,children:e})}function gl(){let e=(0,y.useContext)(ml);if(!e)throw Error(`useBatchContext must be used within a BatchProvider`);return e}var _l=e=>!!e.panZoom;function vl(){let e=Zc(),t=bc(),n=gl(),r=G(_l),i=(0,y.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},a=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),i=cl(e)?e:n.get(e.id),a=i.parentId?po(i.position,i.measured,i.parentId,n,r):i.position;return Ya({...i,position:a,width:i.measured?.width??i.width,height:i.measured?.height??i.height})},o=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&cl(e)?e:{...r,...e}}return r}))},s=(e,t,n={replace:!1})=>{i(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&ll(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,a,o]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:i,y:a,zoom:o}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:i,onNodesDelete:a,onEdgesDelete:o,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:l,onBeforeDelete:u}=t.getState(),{nodes:d,edges:f}=await Ba({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:u}),p=f.length>0,m=d.length>0;if(p){let e=f.map(al);o?.(f),c(e)}if(m){let e=d.map(al);a?.(d),s(e)}return(m||p)&&l?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let i=eo(e),o=i?e:a(e),s=r!==void 0;return o?(r||t.getState().nodes).filter(r=>{let a=t.getState().nodeLookup.get(r.id);if(a&&!i&&(r.id===e.id||!a.internals.positionAbsolute))return!1;let c=Ya(s?r:a),l=$a(c,o);return n&&l>0||l>=c.width*c.height||l>=o.width*o.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=eo(e)?e:a(e);if(!r)return!1;let i=$a(r,t);return n&&i>0||i>=t.width*t.height||i>=r.width*r.height},updateNode:o,updateNodeData:(e,t,n={replace:!1})=>{o(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return Na(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:``}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:``}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??ho();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,y.useMemo)(()=>({...i,...e,viewportInitialized:r}),[r])}var yl=e=>e.selected,bl=typeof window<`u`?window:void 0;function xl({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=bc(),{deleteElements:r}=vl(),i=Jc(e,{actInsideInputWithModifier:!1}),a=Jc(t,{target:bl});(0,y.useEffect)(()=>{if(i){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(yl),edges:e.filter(yl)}),n.setState({nodesSelectionActive:!1})}},[i]),(0,y.useEffect)(()=>{n.setState({multiSelectionActive:a})},[a])}function Sl(e){let t=bc();(0,y.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;let n=yo(e.current);(n.height===0||n.width===0)&&t.getState().onError?.(`004`,va.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener(`resize`,n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener(`resize`,n),t&&e.current&&t.unobserve(e.current)}}},[])}var Cl={position:`absolute`,width:`100%`,height:`100%`,top:0,left:0},wl=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function Tl({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panActivationKeyPressed:i,panOnScrollSpeed:a=.5,panOnScrollMode:o=Ca.Free,zoomOnDoubleClick:s=!0,panOnDrag:c=!0,defaultViewport:l,translateExtent:u,minZoom:d,maxZoom:f,zoomActivationKeyCode:p,preventScrolling:m=!0,children:h,noWheelClassName:g,noPanClassName:_,onViewportChange:v,isControlledViewport:b,paneClickDistance:S,selectionOnDrag:C}){let w=bc(),T=(0,y.useRef)(null),{userSelectionActive:E,lib:D,connectionInProgress:O}=G(wl,hc),k=Jc(p),A=(0,y.useRef)();Sl(T);let j=(0,y.useCallback)(e=>{v?.({x:e[0],y:e[1],zoom:e[2]}),b||w.setState({transform:e})},[v,b]);return(0,y.useEffect)(()=>{if(T.current){A.current=Ws({domNode:T.current,minZoom:d,maxZoom:f,translateExtent:u,viewport:l,onDraggingChange:e=>w.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=w.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=w.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=w.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=A.current.getViewport();return w.setState({panZoom:A.current,transform:[e,t,n],domNode:T.current.closest(`.react-flow`)}),()=>{A.current?.destroy()}}},[]),(0,y.useEffect)(()=>{A.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panActivationKeyPressed:i,panOnScrollSpeed:a,panOnScrollMode:o,zoomOnDoubleClick:s,panOnDrag:c,zoomActivationKeyPressed:k,preventScrolling:m,noPanClassName:_,userSelectionActive:E,noWheelClassName:g,lib:D,onTransformChange:j,connectionInProgress:O,selectionOnDrag:C,paneClickDistance:S})},[e,t,n,r,i,a,o,s,c,k,m,_,E,g,D,j,O,C,S]),(0,x.jsx)(`div`,{className:`react-flow__renderer`,ref:T,style:Cl,children:h})}var El=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Dl(){let{userSelectionActive:e,userSelectionRect:t}=G(El,hc);return e&&t?(0,x.jsx)(`div`,{className:`react-flow__selection react-flow__container`,style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var Ol=(e,t)=>n=>{n.target===t.current&&e?.(n)},kl=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function Al({isSelecting:e,selectionKeyPressed:t,selectionMode:n=wa.Full,panOnDrag:r,autoPanOnSelection:i,paneClickDistance:a,selectionOnDrag:o,onSelectionStart:s,onSelectionEnd:c,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:d,onPaneMouseEnter:f,onPaneMouseMove:p,onPaneMouseLeave:m,children:h}){let g=(0,y.useRef)(0),_=bc(),{userSelectionActive:v,elementsSelectable:b,dragging:C,panBy:w,autoPanSpeed:T}=G(kl,hc),E=b&&(e||v),D=(0,y.useRef)(null),O=(0,y.useRef)(),k=(0,y.useRef)(new Set),A=(0,y.useRef)(new Set),j=(0,y.useRef)(!1),M=(0,y.useRef)(!1),N=(0,y.useRef)({x:0,y:0}),P=(0,y.useRef)(!1),ee=e=>{if(M.current||j.current||_.getState().connection.inProgress){M.current=!1,j.current=!1;return}l?.(e),_.getState().resetSelectedElements(),_.setState({nodesSelectionActive:!1})},F=e=>{if(Array.isArray(r)&&r?.includes(2)){e.preventDefault();return}u?.(e)},I=d?e=>d(e):void 0,te=e=>{M.current&&=(e.stopPropagation(),!1)},ne=n=>{if(n.pointerType===`touch`&&r!==!1&&!t)return;let{domNode:i,transform:a}=_.getState();if(O.current=i?.getBoundingClientRect(),!O.current)return;let s=n.target===D.current;if(!s&&n.target.closest(`.nokey`)||!e||!(o&&s||t)||n.button!==0||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),M.current=!1;let{x:c,y:l}=wo(n.nativeEvent,O.current),u=io({x:c,y:l},a);_.setState({userSelectionRect:{width:0,height:0,startX:u.x,startY:u.y,x:c,y:l}}),s||(n.stopPropagation(),n.preventDefault())};function L(e,t){let{userSelectionRect:r}=_.getState();if(!r)return;let{transform:i,nodeLookup:a,edgeLookup:o,connectionLookup:s,triggerNodeChanges:c,triggerEdgeChanges:l,defaultEdgeOptions:u}=_.getState(),d={x:r.startX,y:r.startY},{x:f,y:p}=ao(d,i),m={startX:d.x,startY:d.y,x:ee.id)),A.current=new Set;let v=u?.selectable??!0;for(let e of k.current){let t=s.get(e);if(t)for(let{edgeId:e}of t.values()){let t=o.get(e);t&&(t.selectable??v)&&A.current.add(e)}}mo(h,k.current)||c(rl(a,k.current,!0)),mo(g,A.current)||l(rl(o,A.current)),_.setState({userSelectionRect:m,userSelectionActive:!0,nodesSelectionActive:!1})}function R(){if(!i||!O.current)return;let[e,t]=Ga(N.current,O.current,T);w({x:e,y:t}).then(e=>{if(!M.current||!e){g.current=requestAnimationFrame(R);return}let{x:t,y:n}=N.current;L(t,n),g.current=requestAnimationFrame(R)})}let z=()=>{cancelAnimationFrame(g.current),g.current=0,P.current=!1};(0,y.useEffect)(()=>()=>z(),[]);let B=e=>{let{userSelectionRect:n,transform:r,resetSelectedElements:i}=_.getState();if(!O.current||!n)return;let{x:o,y:c}=wo(e.nativeEvent,O.current);N.current={x:o,y:c};let l=ao({x:n.startX,y:n.startY},r);if(!M.current){let n=t?0:a;if(Math.hypot(o-l.x,c-l.y)<=n)return;i(),s?.(e)}M.current=!0,P.current||=(R(),!0),L(o,c)},re=e=>{if(!E){e.target===D.current&&_.getState().connection.inProgress&&(j.current=!0);return}e.button===0&&(e.target?.releasePointerCapture?.(e.pointerId),!v&&e.target===D.current&&_.getState().userSelectionRect&&ee?.(e),_.setState({userSelectionActive:!1,userSelectionRect:null}),M.current&&(c?.(e),_.setState({nodesSelectionActive:k.current.size>0})),z())},ie=e=>{e.target?.releasePointerCapture?.(e.pointerId),z()},ae=r===!0||Array.isArray(r)&&r.includes(0);return(0,x.jsxs)(`div`,{className:S([`react-flow__pane`,{draggable:ae,dragging:C,selection:e}]),onClick:E?void 0:Ol(ee,D),onContextMenu:Ol(F,D),onWheel:Ol(I,D),onPointerEnter:E?void 0:f,onPointerMove:E?B:p,onPointerUp:re,onPointerCancel:E?ie:void 0,onPointerDownCapture:E?ne:void 0,onClickCapture:E?te:void 0,onPointerLeave:m,ref:D,style:Cl,children:[h,(0,x.jsx)(Dl,{})]})}function jl({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:o,nodeLookup:s,onError:c}=t.getState(),l=s.get(e);if(!l){c?.(`012`,va.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&o)&&(a({nodes:[l],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):i([e])}function Ml({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,nodeClickDistance:o}){let s=bc(),[c,l]=(0,y.useState)(!1),u=(0,y.useRef)();return(0,y.useEffect)(()=>{if(!t)return u.current=ys({getStoreItems:()=>s.getState(),onNodeMouseDown:t=>{jl({id:t,store:s,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}}),()=>{u.current?.destroy(),u.current=void 0}},[t,s,e]),(0,y.useEffect)(()=>{t||!e.current||!u.current||u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:a,nodeId:i,nodeClickDistance:o})},[n,r,t,a,e,i,o]),c}var Nl=e=>t=>t.selected&&(t.draggable||e&&t.draggable===void 0);function Pl(){let e=bc();return(0,y.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:a,onError:o,updateNodePositions:s,nodeLookup:c,nodeOrigin:l}=e.getState(),u=new Map,d=Nl(a),f=r?i[0]:5,p=r?i[1]:5,m=t.direction.x*f*t.factor,h=t.direction.y*p*t.factor;for(let[,e]of c){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+h};r&&(t=ro(t,i));let{position:a,positionAbsolute:s}=za({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:l,onError:o});e.position=a,e.internals.positionAbsolute=s,u.set(e.id,e)}s(u)},[])}var Fl=(0,y.createContext)(null),Il=Fl.Provider;Fl.Consumer;var Ll=()=>(0,y.useContext)(Fl),Rl=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),zl=(0,y.createContext)(null);function Bl({children:e}){let t=G(Rl,hc);return(0,x.jsx)(zl.Provider,{value:t,children:e})}function K(){let e=(0,y.useContext)(zl);if(!e)throw Error(`useHandleConfig must be used within a HandleConfigProvider`);return e}var q={connectingFrom:!1,connectingTo:!1,clickConnecting:!1,isPossibleEndHandle:!0,connectionInProcess:!1,clickConnectionInProcess:!1,valid:!1},Vl=(e,t,n)=>r=>{let{connectionClickStartHandle:i,connectionMode:a,connection:o}=r,{fromHandle:s,toHandle:c,isValid:l}=o;if(!s&&!i)return q;let u=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:u,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:a===Sa.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:u&&l}};function Hl({type:e=`source`,position:t=H.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:o,onConnect:s,children:c,className:l,onMouseDown:u,onTouchStart:d,...f},p){let m=o||null,h=e===`target`,g=bc(),_=Ll(),{connectOnClick:v,noPanClassName:y,rfId:b}=K(),{connectingFrom:C,connectingTo:w,clickConnecting:T,isPossibleEndHandle:E,connectionInProcess:D,clickConnectionInProcess:O,valid:k}=G(Vl(_,m,e),hc);_||g.getState().onError?.(`010`,va.error010());let A=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=g.getState(),i={...t,...e};if(r){let{edges:e,setEdges:t,onError:n}=g.getState();t(sl(i,e,{onError:n}))}n?.(i),s?.(i)},j=e=>{if(!_)return;let t=Co(e.nativeEvent);if(i&&(t&&e.button===0||!t)){let t=g.getState();ks.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:h,handleId:m,nodeId:_,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>g.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:A,isValidConnection:n||((...e)=>g.getState().isValidConnection?.(...e)??!0),getTransform:()=>g.getState().transform,getFromHandle:()=>g.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):d?.(e)};return(0,x.jsx)(`div`,{"data-handleid":m,"data-nodeid":_,"data-handlepos":t,"data-id":`${b}-${_}-${m}-${e}`,className:S([`react-flow__handle`,`react-flow__handle-${t}`,`nodrag`,y,l,{source:!h,target:h,connectable:r,connectablestart:i,connectableend:a,clickconnecting:T,connectingfrom:C,connectingto:w,valid:k,connectionindicator:r&&(!D||E)&&(D||O?a:i)}]),onMouseDown:j,onTouchStart:j,onClick:v?t=>{let{onClickConnectStart:r,onClickConnectEnd:a,connectionClickStartHandle:o,connectionMode:s,isValidConnection:c,lib:l,rfId:u,nodeLookup:d,connection:f}=g.getState();if(!_||!o&&!i)return;if(!o){r?.(t.nativeEvent,{nodeId:_,handleId:m,handleType:e}),g.setState({connectionClickStartHandle:{nodeId:_,type:e,id:m}});return}let p=bo(t.target),h=n||c,{connection:v,isValid:y}=ks.isValid(t.nativeEvent,{handle:{nodeId:_,id:m,type:e},connectionMode:s,fromNodeId:o.nodeId,fromHandleId:o.id||null,fromType:o.type,isValidConnection:h,flowId:u,doc:p,lib:l,nodeLookup:d});y&&v&&A(v);let b=structuredClone(f);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,a?.(t,b),g.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f,children:c})}var Ul=(0,y.memo)(ul(Hl));function Wl({data:e,isConnectable:t,sourcePosition:n=H.Bottom}){return(0,x.jsxs)(x.Fragment,{children:[e?.label,(0,x.jsx)(Ul,{type:`source`,position:n,isConnectable:t})]})}function Gl({data:e,isConnectable:t,targetPosition:n=H.Top,sourcePosition:r=H.Bottom}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{type:`target`,position:n,isConnectable:t}),e?.label,(0,x.jsx)(Ul,{type:`source`,position:r,isConnectable:t})]})}function Kl(){return null}function ql({data:e,isConnectable:t,targetPosition:n=H.Top}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{type:`target`,position:n,isConnectable:t}),e?.label]})}var Jl={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Yl={input:Wl,default:Gl,output:ql,group:Kl};function Xl(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var Zl=e=>{let{width:t,height:n,x:r,y:i}=Pa(e.nodeLookup,{filter:e=>!!e.selected});return{width:to(t)?t:null,height:to(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function Ql({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=bc(),{width:i,height:a,transformString:o,userSelectionActive:s}=G(Zl,hc),c=Pl(),l=(0,y.useRef)(null);(0,y.useEffect)(()=>{n||l.current?.focus({preventScroll:!0})},[n]);let u=!s&&i!==null&&a!==null;if(Ml({nodeRef:l,disabled:!u}),!u)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,x.jsx)(`div`,{className:S([`react-flow__nodesselection`,`react-flow__container`,t]),style:{transform:o},children:(0,x.jsx)(`div`,{ref:l,className:`react-flow__nodesselection-rect`,onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(Jl,e.key)&&(e.preventDefault(),c({direction:Jl[e.key],factor:e.shiftKey?4:1}))},style:{width:i,height:a}})})}var $l=typeof window<`u`?window:void 0,eu=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function tu({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,paneClickDistance:s,deleteKeyCode:c,selectionKeyCode:l,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:g,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:b,panOnScrollSpeed:S,panOnScrollMode:C,zoomOnDoubleClick:w,panOnDrag:T,autoPanOnSelection:E,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,preventScrolling:j,onSelectionContextMenu:M,noWheelClassName:N,noPanClassName:P,disableKeyboardA11y:ee,onViewportChange:F,isControlledViewport:I}){let{nodesSelectionActive:te,userSelectionActive:ne}=G(eu,hc),L=Jc(l,{target:$l}),R=Jc(h,{target:$l}),z=R||T,B=R||b,re=u&&z!==!0,ie=L||ne||re;return xl({deleteKeyCode:c,multiSelectionKeyCode:m}),(0,x.jsx)(Tl,{onPaneContextMenu:a,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:B,panActivationKeyPressed:R,panOnScrollSpeed:S,panOnScrollMode:C,zoomOnDoubleClick:w,panOnDrag:!L&&z,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,zoomActivationKeyCode:g,preventScrolling:j,noWheelClassName:N,noPanClassName:P,onViewportChange:F,isControlledViewport:I,paneClickDistance:s,selectionOnDrag:re,children:(0,x.jsxs)(Al,{onSelectionStart:f,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,panOnDrag:z,autoPanOnSelection:E,isSelecting:!!ie,selectionMode:d,selectionKeyPressed:L,paneClickDistance:s,selectionOnDrag:re,children:[e,te&&(0,x.jsx)(Ql,{onSelectionContextMenu:M,noPanClassName:P,disableKeyboardA11y:ee})]})})}tu.displayName=`FlowRenderer`;var nu=(0,y.memo)(tu),ru=e=>t=>e?Fa(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys());function iu(e){return G((0,y.useCallback)(ru(e),[e]),hc)}var au=e=>e.updateNodeInternals;function ou(){let e=G(au),[t]=(0,y.useState)(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute(`data-id`);n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,y.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function su({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let i=bc(),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(e.sourcePosition),c=(0,y.useRef)(e.targetPosition),l=(0,y.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,y.useEffect)(()=>{a.current&&!e.hidden&&(!u||o.current!==a.current)&&(o.current&&r?.unobserve(o.current),r?.observe(a.current),o.current=a.current)},[u,e.hidden]),(0,y.useEffect)(()=>()=>{o.current&&=(r?.unobserve(o.current),null)},[]),(0,y.useEffect)(()=>{if(a.current){let n=l.current!==t,r=s.current!==e.sourcePosition,o=c.current!==e.targetPosition;(n||r||o)&&(l.current=t,s.current=e.sourcePosition,c.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:a.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),a}function cu({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:i,onContextMenu:a,onDoubleClick:o,nodesDraggable:s,elementsSelectable:c,nodesConnectable:l,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:p,disableKeyboardA11y:m,rfId:h,nodeTypes:g,nodeClickDistance:_,onError:v}){let{node:y,internals:b,isParent:C}=G(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},hc),w=y.type||`default`,T=g?.[w]||Yl[w];T===void 0&&(v?.(`003`,va.error003(w)),w=`default`,T=g?.default||Yl.default);let E=!!(y.draggable||s&&y.draggable===void 0),D=!!(y.selectable||c&&y.selectable===void 0),O=!!(y.connectable||l&&y.connectable===void 0),k=!!(y.focusable||u&&y.focusable===void 0),A=bc(),j=fo(y),M=su({node:y,nodeType:w,hasDimensions:j,resizeObserver:d}),N=Ml({nodeRef:M,disabled:y.hidden||!E,noDragClassName:f,handleSelector:y.dragHandle,nodeId:e,isSelectable:D,nodeClickDistance:_}),P=Pl();if(y.hidden)return null;let ee=uo(y),F=Xl(y),I=D||E||t||n||r||i,te=n?e=>n(e,{...b.userNode}):void 0,ne=r?e=>r(e,{...b.userNode}):void 0,L=i?e=>i(e,{...b.userNode}):void 0,R=a?e=>a(e,{...b.userNode}):void 0,z=o?e=>o(e,{...b.userNode}):void 0,B=n=>{let{selectNodesOnDrag:r,nodeDragThreshold:i}=A.getState();D&&(!r||!E||i>0)&&jl({id:e,store:A,nodeRef:M}),t&&t(n,{...b.userNode})},re=t=>{if(!(So(t.nativeEvent)||m)){if(ba.includes(t.key)&&D){let n=t.key===`Escape`;jl({id:e,store:A,unselect:n,nodeRef:M})}else if(E&&y.selected&&Object.prototype.hasOwnProperty.call(Jl,t.key)){t.preventDefault();let{ariaLabelConfig:e}=A.getState();A.setState({ariaLiveMessage:e[`node.a11yDescription.ariaLiveMessage`]({direction:t.key.replace(`Arrow`,``).toLowerCase(),x:~~b.positionAbsolute.x,y:~~b.positionAbsolute.y})}),P({direction:Jl[t.key],factor:t.shiftKey?4:1})}}},ie=()=>{if(m||!M.current?.matches(`:focus-visible`))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:i,setCenter:a}=A.getState();i&&(Fa(new Map([[e,y]]),{x:0,y:0,width:n,height:r},t,!0).length>0||a(y.position.x+ee.width/2,y.position.y+ee.height/2,{zoom:t[2]}))};return(0,x.jsx)(`div`,{className:S([`react-flow__node`,`react-flow__node-${w}`,{[p]:E},y.className,{selected:y.selected,selectable:D,parent:C,draggable:E,dragging:N}]),ref:M,style:{zIndex:b.z,transform:`translate(${b.positionAbsolute.x}px,${b.positionAbsolute.y}px)`,pointerEvents:I?`all`:`none`,visibility:j?`visible`:`hidden`,...y.style,...F},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:te,onMouseMove:ne,onMouseLeave:L,onContextMenu:R,onClick:B,onDoubleClick:z,onKeyDown:k?re:void 0,tabIndex:k?0:void 0,onFocus:k?ie:void 0,role:y.ariaRole??(k?`group`:void 0),"aria-roledescription":`node`,"aria-describedby":m?void 0:`${Cc}-${h}`,"aria-label":y.ariaLabel,...y.domAttributes,children:(0,x.jsx)(Il,{value:e,children:(0,x.jsx)(T,{id:e,data:y.data,type:w,positionAbsoluteX:b.positionAbsolute.x,positionAbsoluteY:b.positionAbsolute.y,selected:y.selected??!1,selectable:D,draggable:E,deletable:y.deletable??!0,isConnectable:O,sourcePosition:y.sourcePosition,targetPosition:y.targetPosition,dragging:N,dragHandle:y.dragHandle,zIndex:b.z,parentId:y.parentId,...ee})})})}var lu=(0,y.memo)(cu),uu=e=>({nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function du(e){let{nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,onError:i}=G(uu,hc),a=iu(e.onlyRenderVisibleElements),o=ou();return(0,x.jsx)(`div`,{className:`react-flow__nodes`,style:Cl,children:a.map(a=>(0,x.jsx)(lu,{id:a,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:o,nodesDraggable:e.nodesDraggable??!0,nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,nodeClickDistance:e.nodeClickDistance,onError:i},a))})}du.displayName=`NodeRenderer`;var fu=(0,y.memo)(du);function pu(e){return G((0,y.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&Mo({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),hc)}var mu=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e}};return(0,x.jsx)(`polyline`,{className:`arrow`,style:n,strokeLinecap:`round`,fill:`none`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4`})},hu=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e,fill:e}};return(0,x.jsx)(`polyline`,{className:`arrowclosed`,style:n,strokeLinecap:`round`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4 -5,-4`})},gu={[Da.Arrow]:mu,[Da.ArrowClosed]:hu};function _u(e){let t=bc();return(0,y.useMemo)(()=>Object.prototype.hasOwnProperty.call(gu,e)?gu[e]:(t.getState().onError?.(`009`,va.error009(e)),null),[e])}var vu=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a=`strokeWidth`,strokeWidth:o,orient:s=`auto-start-reverse`})=>{let c=_u(t);return c?(0,x.jsx)(`marker`,{className:`react-flow__arrowhead`,id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:`-10 -10 20 20`,markerUnits:a,orient:s,refX:`0`,refY:`0`,children:(0,x.jsx)(c,{color:n,strokeWidth:o})}):null},yu=({defaultColor:e,rfId:t})=>{let n=G(e=>e.edges),r=G(e=>e.defaultEdgeOptions),i=(0,y.useMemo)(()=>Yo(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return i.length?(0,x.jsx)(`svg`,{className:`react-flow__marker`,"aria-hidden":`true`,children:(0,x.jsx)(`defs`,{children:i.map(e=>(0,x.jsx)(vu,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};yu.displayName=`MarkerDefinitions`;var bu=(0,y.memo)(yu);function xu({x:e,y:t,label:n,labelStyle:r,labelShowBg:i=!0,labelBgStyle:a,labelBgPadding:o=[2,4],labelBgBorderRadius:s=2,children:c,className:l,...u}){let[d,f]=(0,y.useState)({x:1,y:0,width:0,height:0}),p=S([`react-flow__edge-textwrapper`,l]),m=(0,y.useRef)(null);return(0,y.useEffect)(()=>{if(m.current){let e=m.current.getBBox();f({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,x.jsxs)(`g`,{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?`visible`:`hidden`,...u,children:[i&&(0,x.jsx)(`rect`,{width:d.width+2*o[0],x:-o[0],y:-o[1],height:d.height+2*o[1],className:`react-flow__edge-textbg`,style:a,rx:s,ry:s}),(0,x.jsx)(`text`,{className:`react-flow__edge-text`,y:d.height/2,dy:`0.3em`,ref:m,style:r,children:n}),c]}):null}xu.displayName=`EdgeText`;var Su=(0,y.memo)(xu);function Cu({path:e,labelX:t,labelY:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c,interactionWidth:l=20,...u}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{...u,d:e,fill:`none`,className:S([`react-flow__edge-path`,u.className])}),l?(0,x.jsx)(`path`,{d:e,fill:`none`,strokeOpacity:0,strokeWidth:l,className:`react-flow__edge-interaction`}):null,r&&to(t)&&to(n)?(0,x.jsx)(Su,{x:t,y:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c}):null]})}function wu({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===H.Left||e===H.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function Tu({sourceX:e,sourceY:t,sourcePosition:n=H.Bottom,targetX:r,targetY:i,targetPosition:a=H.Top}){let[o,s]=wu({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,l]=wu({pos:a,x1:r,y1:i,x2:e,y2:t}),[u,d,f,p]=Eo({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:s,targetControlX:c,targetControlY:l});return[`M${e},${t} C${o},${s} ${c},${l} ${r},${i}`,u,d,f,p]}function Eu(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o,targetPosition:s,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})=>{let[v,y,b]=Tu({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s}),S=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:S,path:v,labelX:y,labelY:b,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})})}var Du=Eu({isInternal:!1}),Ou=Eu({isInternal:!0});Du.displayName=`SimpleBezierEdge`,Ou.displayName=`SimpleBezierEdgeInternal`;function ku(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:p=H.Bottom,targetPosition:m=H.Top,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,S]=Ho({sourceX:n,sourceY:r,sourcePosition:p,targetX:i,targetY:a,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition}),C=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:C,path:y,labelX:b,labelY:S,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:g,interactionWidth:v})})}var Au=ku({isInternal:!1}),ju=ku({isInternal:!0});Au.displayName=`SmoothStepEdge`,ju.displayName=`SmoothStepEdgeInternal`;function Mu(e){return(0,y.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,x.jsx)(Au,{...n,id:r,pathOptions:(0,y.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var Nu=Mu({isInternal:!1}),Pu=Mu({isInternal:!0});Nu.displayName=`StepEdge`,Pu.displayName=`StepEdgeInternal`;function Fu(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})=>{let[g,_,v]=Io({sourceX:n,sourceY:r,targetX:i,targetY:a}),y=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:y,path:g,labelX:_,labelY:v,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})})}var Iu=Fu({isInternal:!1}),Lu=Fu({isInternal:!0});Iu.displayName=`StraightEdge`,Lu.displayName=`StraightEdgeInternal`;function Ru(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o=H.Bottom,targetPosition:s=H.Top,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,S]=ko({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s,curvature:_?.curvature}),C=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:C,path:y,labelX:b,labelY:S,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:v})})}var zu=Ru({isInternal:!1}),Bu=Ru({isInternal:!0});zu.displayName=`BezierEdge`,Bu.displayName=`BezierEdgeInternal`;var Vu={default:Bu,straight:Lu,step:Pu,smoothstep:ju,simplebezier:Ou},Hu={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null,zIndex:void 0},Uu=(e,t,n)=>n===H.Left?e-t:n===H.Right?e+t:e,Wu=(e,t,n)=>n===H.Top?e-t:n===H.Bottom?e+t:e,Gu=`react-flow__edgeupdater`;function Ku({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:o,type:s}){return(0,x.jsx)(`circle`,{onMouseDown:i,onMouseEnter:a,onMouseOut:o,className:S([Gu,`${Gu}-${s}`]),cx:Uu(t,r,e),cy:Wu(n,r,e),r,stroke:`transparent`,fill:`transparent`})}function qu({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:i,targetX:a,targetY:o,sourcePosition:s,targetPosition:c,onReconnect:l,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:p}){let m=bc(),h=(e,t)=>{if(e.button!==0)return;let{autoPanOnConnect:r,domNode:i,connectionMode:a,connectionRadius:o,lib:s,onConnectStart:c,cancelConnection:p,nodeLookup:h,rfId:g,panBy:_,updateConnection:v}=m.getState(),y=t.type===`target`;ks.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:o,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:y,edgeUpdaterType:t.type,lib:s,flowId:g,cancelConnection:p,panBy:_,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>l?.(n,e),onConnectStart:(r,i)=>{f(!0),u?.(e,n,t.type),c?.(r,i)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=e=>h(e,{nodeId:n.target,id:n.targetHandle??null,type:`target`}),_=e=>h(e,{nodeId:n.source,id:n.sourceHandle??null,type:`source`}),v=()=>p(!0),y=()=>p(!1);return(0,x.jsxs)(x.Fragment,{children:[(e===!0||e===`source`)&&(0,x.jsx)(Ku,{position:s,centerX:r,centerY:i,radius:t,onMouseDown:g,onMouseEnter:v,onMouseOut:y,type:`source`}),(e===!0||e===`target`)&&(0,x.jsx)(Ku,{position:c,centerX:a,centerY:o,radius:t,onMouseDown:_,onMouseEnter:v,onMouseOut:y,type:`target`})]})}function Ju({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:i,onDoubleClick:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,rfId:m,edgeTypes:h,noPanClassName:g,onError:_,disableKeyboardA11y:v}){let b=G(t=>t.edgeLookup.get(e)),C=G(e=>e.defaultEdgeOptions);b=C?{...C,...b}:b;let w=b.type||`default`,T=h?.[w]||Vu[w];T===void 0&&(_?.(`011`,va.error011(w)),w=`default`,T=h?.default||Vu.default);let E=!!(b.focusable||t&&b.focusable===void 0),D=d!==void 0&&(b.reconnectable||n&&b.reconnectable===void 0),O=!!(b.selectable||r&&b.selectable===void 0),k=(0,y.useRef)(null),[A,j]=(0,y.useState)(!1),[M,N]=(0,y.useState)(!1),P=bc(),{zIndex:ee=b.zIndex,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R}=G((0,y.useCallback)(t=>{let n=t.nodeLookup.get(b.source),r=t.nodeLookup.get(b.target);if(!n||!r)return Hu;let i=Wo({id:e,sourceNode:n,targetNode:r,sourceHandle:b.sourceHandle||null,targetHandle:b.targetHandle||null,connectionMode:t.connectionMode,onError:_}),a=jo({selected:b.selected,zIndex:b.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode});return{...i||Hu,zIndex:a}},[b.source,b.target,b.sourceHandle,b.targetHandle,b.selected,b.zIndex,_]),hc),z=(0,y.useMemo)(()=>b.markerStart?`url('#${Jo(b.markerStart,m)}')`:void 0,[b.markerStart,m]),B=(0,y.useMemo)(()=>b.markerEnd?`url('#${Jo(b.markerEnd,m)}')`:void 0,[b.markerEnd,m]);if(b.hidden||F===null||I===null||te===null||ne===null)return null;let re=t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:a}=P.getState();O&&(P.setState({nodesSelectionActive:!1}),b.selected&&a?(r({nodes:[],edges:[b]}),k.current?.blur()):n([e])),i&&i(t,b)},ie=a?e=>{a(e,{...b})}:void 0,ae=o?e=>{o(e,{...b})}:void 0,oe=s?e=>{s(e,{...b})}:void 0,se=c?e=>{c(e,{...b})}:void 0,ce=l?e=>{l(e,{...b})}:void 0;return(0,x.jsx)(`svg`,{style:{zIndex:ee},children:(0,x.jsxs)(`g`,{className:S([`react-flow__edge`,`react-flow__edge-${w}`,b.className,g,{selected:b.selected,animated:b.animated,inactive:!O&&!i,updating:A,selectable:O}]),onClick:re,onDoubleClick:ie,onContextMenu:ae,onMouseEnter:oe,onMouseMove:se,onMouseLeave:ce,onKeyDown:E?t=>{if(!v&&ba.includes(t.key)&&O){let{unselectNodesAndEdges:n,addSelectedEdges:r}=P.getState();t.key===`Escape`?(k.current?.blur(),n({edges:[b]})):r([e])}}:void 0,tabIndex:E?0:void 0,role:b.ariaRole??(E?`group`:`img`),"aria-roledescription":`edge`,"data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":b.ariaLabel===null?void 0:b.ariaLabel||`Edge from ${b.source} to ${b.target}`,"aria-describedby":E?`${wc}-${m}`:void 0,ref:k,...b.domAttributes,children:[!M&&(0,x.jsx)(T,{id:e,source:b.source,target:b.target,type:b.type,selected:b.selected,animated:b.animated,selectable:O,deletable:b.deletable??!0,label:b.label,labelStyle:b.labelStyle,labelShowBg:b.labelShowBg,labelBgStyle:b.labelBgStyle,labelBgPadding:b.labelBgPadding,labelBgBorderRadius:b.labelBgBorderRadius,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R,data:b.data,style:b.style,sourceHandleId:b.sourceHandle,targetHandleId:b.targetHandle,markerStart:z,markerEnd:B,pathOptions:`pathOptions`in b?b.pathOptions:void 0,interactionWidth:b.interactionWidth}),D&&(0,x.jsx)(qu,{edge:b,isReconnectable:D,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R,setUpdateHover:j,setReconnecting:N})]})})}var Yu=(0,y.memo)(Ju),Xu=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Zu({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:i,onReconnect:a,onEdgeContextMenu:o,onEdgeMouseEnter:s,onEdgeMouseMove:c,onEdgeMouseLeave:l,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:h}){let{edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,onError:y}=G(Xu,hc),b=pu(t);return(0,x.jsxs)(`div`,{className:`react-flow__edges`,children:[(0,x.jsx)(bu,{defaultColor:e,rfId:n}),b.map(e=>(0,x.jsx)(Yu,{id:e,edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,noPanClassName:i,onReconnect:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,rfId:n,onError:y,edgeTypes:r,disableKeyboardA11y:h},e))]})}Zu.displayName=`EdgeRenderer`;var Qu=(0,y.memo)(Zu),$u=e=>`translate(${e[0]}px,${e[1]}px) scale(${e[2]})`;function ed({children:e}){let t=bc(),n=(0,y.useRef)(null),[r]=(0,y.useState)(()=>t.getState().transform);return dl(()=>{let e=null,r=()=>{let r=t.getState().transform;e&&r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2]||(e=r,n.current&&(n.current.style.transform=$u(r)))};return r(),t.subscribe(r)},[t]),(0,x.jsx)(`div`,{ref:n,className:`react-flow__viewport xyflow__viewport react-flow__container`,style:{transform:$u(r)},children:e})}function td(e){let t=vl(),n=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var nd=e=>e.panZoom?.syncViewport;function rd(e){let t=G(nd),n=bc();return(0,y.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function id(e){return e.connection.inProgress?{...e.connection,to:io(e.connection.to,e.transform)}:{...e.connection}}function ad(e){return e?t=>e(id(t)):id}function od(e){return G(ad(e),hc)}var sd=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function cd({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:i,width:a,height:o,isValid:s,inProgress:c}=G(sd,hc);return a&&i&&c?(0,x.jsx)(`svg`,{style:e,width:a,height:o,className:`react-flow__connectionline react-flow__container`,children:(0,x.jsx)(`g`,{className:S([`react-flow__connection`,_o(s)]),children:(0,x.jsx)(ld,{style:t,type:n,CustomComponent:r,isValid:s})})}):null}var ld=({style:e,type:t=Ea.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:i,from:a,fromNode:o,fromHandle:s,fromPosition:c,to:l,toNode:u,toHandle:d,toPosition:f,pointer:p}=od();if(!i)return;if(n)return(0,x.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:o,fromHandle:s,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:c,toPosition:f,connectionStatus:_o(r),toNode:u,toHandle:d,pointer:p});let m=``,h={sourceX:a.x,sourceY:a.y,sourcePosition:c,targetX:l.x,targetY:l.y,targetPosition:f};switch(t){case Ea.Bezier:[m]=ko(h);break;case Ea.SimpleBezier:[m]=Tu(h);break;case Ea.Step:[m]=Ho({...h,borderRadius:0});break;case Ea.SmoothStep:[m]=Ho(h);break;default:[m]=Io(h)}return(0,x.jsx)(`path`,{d:m,fill:`none`,className:`react-flow__connection-path`,style:e})};ld.displayName=`ConnectionLine`;var ud={};function dd(e=ud){(0,y.useRef)(e),bc(),(0,y.useEffect)(()=>{},[e])}function fd(){bc(),(0,y.useRef)(!1),(0,y.useEffect)(()=>{},[])}function pd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:i,onNodeDoubleClick:a,onEdgeDoubleClick:o,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:h,connectionLineComponent:g,connectionLineContainerStyle:_,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,multiSelectionKeyCode:S,panActivationKeyCode:C,zoomActivationKeyCode:w,deleteKeyCode:T,onlyRenderVisibleElements:E,elementsSelectable:D,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,preventScrolling:M,defaultMarkerColor:N,zoomOnScroll:P,zoomOnPinch:ee,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,zoomOnDoubleClick:ne,panOnDrag:L,autoPanOnSelection:R,onPaneClick:z,onPaneMouseEnter:B,onPaneMouseMove:re,onPaneMouseLeave:ie,onPaneScroll:ae,onPaneContextMenu:oe,paneClickDistance:se,nodeClickDistance:ce,onEdgeContextMenu:le,onEdgeMouseEnter:ue,onEdgeMouseMove:de,onEdgeMouseLeave:fe,reconnectRadius:pe,onReconnect:me,onReconnectStart:he,onReconnectEnd:ge,noDragClassName:_e,noWheelClassName:ve,noPanClassName:ye,disableKeyboardA11y:be,nodeExtent:xe,rfId:Se,viewport:Ce,onViewportChange:we,nodesDraggable:Te}){return dd(e),dd(t),fd(),td(n),rd(Ce),(0,x.jsx)(nu,{onPaneClick:z,onPaneMouseEnter:B,onPaneMouseMove:re,onPaneMouseLeave:ie,onPaneContextMenu:oe,onPaneScroll:ae,paneClickDistance:se,deleteKeyCode:T,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:S,panActivationKeyCode:C,zoomActivationKeyCode:w,elementsSelectable:D,zoomOnScroll:P,zoomOnPinch:ee,zoomOnDoubleClick:ne,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,panOnDrag:L,autoPanOnSelection:R,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,onSelectionContextMenu:d,preventScrolling:M,noDragClassName:_e,noWheelClassName:ve,noPanClassName:ye,disableKeyboardA11y:be,onViewportChange:we,isControlledViewport:!!Ce,children:(0,x.jsxs)(ed,{children:[(0,x.jsx)(Qu,{edgeTypes:t,onEdgeClick:i,onEdgeDoubleClick:o,onReconnect:me,onReconnectStart:he,onReconnectEnd:ge,onlyRenderVisibleElements:E,onEdgeContextMenu:le,onEdgeMouseEnter:ue,onEdgeMouseMove:de,onEdgeMouseLeave:fe,reconnectRadius:pe,defaultMarkerColor:N,noPanClassName:ye,disableKeyboardA11y:be,rfId:Se}),(0,x.jsx)(cd,{style:h,type:m,component:g,containerStyle:_}),(0,x.jsx)(`div`,{className:`react-flow__edgelabel-renderer`}),(0,x.jsx)(fu,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:a,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,nodeClickDistance:ce,onlyRenderVisibleElements:E,noPanClassName:ye,noDragClassName:_e,disableKeyboardA11y:be,nodeExtent:xe,rfId:Se,nodesDraggable:Te}),(0,x.jsx)(`div`,{className:`react-flow__viewport-portal`})]})})}pd.displayName=`GraphView`;var md=(0,y.memo)(pd),hd=no(`React Flow`,`https://reactflow.dev/`),gd=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c=.5,maxZoom:l=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f=`basic`}={})=>{let p=new Map,m=new Map,h=new Map,g=new Map,_=r??t??[],v=n??e??[],y=u??[0,0],b=d??ya;ps(h,g,_);let{nodesInitialized:x}=is(v,p,m,{nodeOrigin:y,nodeExtent:b,zIndexMode:f}),S=[0,0,1];if(o&&i&&a){let{x:e,y:t,zoom:n}=lo(Pa(p,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),i,a,c,l,s?.padding??.1);S=[e,t,n]}return{rfId:`1`,width:i??0,height:a??0,transform:S,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:m,edges:_,edgeLookup:g,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:l,translateExtent:ya,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Sa.Strict,domNode:null,paneDragging:!1,noPanClassName:`nopan`,nodeOrigin:y,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:o??!1,fitViewOptions:s,fitViewResolver:null,connection:{...Ta},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:``,autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:hd,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:`react`,debug:!1,ariaLabelConfig:xa,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},_d=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>mc((p,m)=>{async function h(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:a,minZoom:o,maxZoom:s}=m();t&&(await Ra({nodes:e,width:i,height:a,panZoom:t,minZoom:o,maxZoom:s},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...gd({nodes:e,edges:t,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,fitViewQueued:o,zIndexMode:s,nodesSelectionActive:c}=m(),{nodesInitialized:l,hasSelectedNodes:u}=is(e,t,n,{nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,checkEquality:!0,zIndexMode:s}),d=c&&u;o&&l?(h(),p({nodes:e,nodesInitialized:l,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:d})):p({nodes:e,nodesInitialized:l,nodesSelectionActive:d})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=m();ps(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:a,nodeExtent:o,debug:s,fitViewQueued:c,zIndexMode:l}=m(),{changes:u,updatedInternals:d}=us(e,n,r,i,a,o,l);d&&(ts(n,r,{nodeOrigin:a,nodeExtent:o,zIndexMode:l}),c?(h(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),u?.length>0&&(s&&console.log(`React Flow: trigger node changes`,u),t?.(u)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:i,triggerNodeChanges:a,connection:o,updateConnection:s,onNodesChangeMiddlewareMap:c}=m();for(let[a,c]of e){let e=i.get(a),l=!!(e?.expandParent&&e?.parentId&&c?.position),u={id:a,type:`position`,position:l?{x:Math.max(0,c.position.x),y:Math.max(0,c.position.y)}:c.position,dragging:t};if(e&&o.inProgress&&o.fromNode.id===e.id){let t=Ko(e,o.fromHandle,H.Left,!0);s({...o,from:t})}l&&e.parentId&&n.push({id:a,parentId:e.parentId,rect:{...c.internals.positionAbsolute,width:c.measured.width??0,height:c.measured.height??0}}),r.push(u)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=m(),a=ls(n,i,e,t);r.push(...a)}for(let e of c.values())r=e(r);a(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:a}=m();e?.length&&(i&&n(el(e,r)),a&&console.log(`React Flow: trigger node changes`,e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:a}=m();e?.length&&(i&&n(tl(e,r)),a&&console.log(`React Flow: trigger edge changes`,e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){i(e.map(e=>nl(e,!0)));return}i(rl(r,new Set([...e]),!0)),a(rl(n))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){a(e.map(e=>nl(e,!0)));return}a(rl(n,new Set([...e]))),i(rl(r,new Set,!0))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:a,triggerEdgeChanges:o}=m(),s=e||r,c=t||n,l=[];for(let e of s){if(!e.selected)continue;let t=i.get(e.id);t&&(t.selected=!1),l.push(nl(e.id,!1))}let u=[];for(let e of c)e.selected&&u.push(nl(e.id,!1));a(l),o(u)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=m();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=m();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:i}=m();if(!i)return;let a=t.reduce((e,t)=>t.selected?[...e,nl(t.id,!1)]:e,[]),o=e.reduce((e,t)=>t.selected?[...e,nl(t.id,!1)]:e,[]);n(a),r(o)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:a,nodeExtent:o,zIndexMode:s}=m();(e[0][0]!==o[0][0]||e[0][1]!==o[0][1]||e[1][0]!==o[1][0]||e[1][1]!==o[1][1])&&(is(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:a,checkEquality:!1,zIndexMode:s}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:i,translateExtent:a}=m();return ds({delta:e,panZoom:i,transform:t,translateExtent:a,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:i,maxZoom:a,panZoom:o}=m();if(!o)return!1;let s=n?.zoom===void 0?a:n.zoom;return await o.setViewport({x:r/2-e*s,y:i/2-t*s,zoom:s},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0},cancelConnection:()=>{p({connection:{...Ta}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...gd()})}},Object.is);function vd({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:i,initialHeight:a,initialMinZoom:o,initialMaxZoom:s,initialFitViewOptions:c,fitView:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:p}){let[m]=(0,y.useState)(()=>_d({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:l,minZoom:o,maxZoom:s,fitViewOptions:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,x.jsx)(vc,{value:m,children:(0,x.jsx)(hl,{children:(0,x.jsx)(Bl,{children:p})})})}function yd({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:i,width:a,height:o,fitView:s,fitViewOptions:c,minZoom:l,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p}){return(0,y.useContext)(_c)?(0,x.jsx)(x.Fragment,{children:e}):(0,x.jsx)(vd,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:i,initialWidth:a,initialHeight:o,fitView:s,initialFitViewOptions:c,initialMinZoom:l,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p,children:e})}var bd={width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`,zIndex:0};function xd({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a,edgeTypes:o,onNodeClick:s,onEdgeClick:c,onInit:l,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,onNodeMouseEnter:v,onNodeMouseMove:b,onNodeMouseLeave:C,onNodeContextMenu:w,onNodeDoubleClick:T,onNodeDragStart:E,onNodeDrag:D,onNodeDragStop:O,onNodesDelete:k,onEdgesDelete:A,onDelete:j,onSelectionChange:M,onSelectionDragStart:N,onSelectionDrag:P,onSelectionDragStop:ee,onSelectionContextMenu:F,onSelectionStart:I,onSelectionEnd:te,onBeforeDelete:ne,connectionMode:L,connectionLineType:R=Ea.Bezier,connectionLineStyle:z,connectionLineComponent:B,connectionLineContainerStyle:re,deleteKeyCode:ie=`Backspace`,selectionKeyCode:ae=`Shift`,selectionOnDrag:oe=!1,selectionMode:se=wa.Full,panActivationKeyCode:ce=`Space`,multiSelectionKeyCode:le=U()?`Meta`:`Control`,zoomActivationKeyCode:ue=U()?`Meta`:`Control`,snapToGrid:de,snapGrid:fe,onlyRenderVisibleElements:pe=!1,selectNodesOnDrag:me,nodesDraggable:he,autoPanOnNodeFocus:ge,nodesConnectable:_e,nodesFocusable:ve,nodeOrigin:ye=zc,edgesFocusable:be,edgesReconnectable:xe,elementsSelectable:Se=!0,defaultViewport:Ce=Bc,minZoom:we=.5,maxZoom:Te=2,translateExtent:Ee=ya,preventScrolling:De=!0,nodeExtent:Oe,defaultMarkerColor:ke=`#b1b1b7`,zoomOnScroll:Ae=!0,zoomOnPinch:je=!0,panOnScroll:Me=!1,panOnScrollSpeed:Ne=.5,panOnScrollMode:Pe=Ca.Free,zoomOnDoubleClick:Fe=!0,panOnDrag:Ie=!0,onPaneClick:Le,onPaneMouseEnter:Re,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:Ve,onPaneContextMenu:He,paneClickDistance:Ue=1,nodeClickDistance:We=0,children:Ge,onReconnect:Ke,onReconnectStart:qe,onReconnectEnd:Je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Xe,onEdgeMouseEnter:Ze,onEdgeMouseMove:Qe,onEdgeMouseLeave:$e,reconnectRadius:et=10,onNodesChange:tt,onEdgesChange:nt,noDragClassName:rt=`nodrag`,noWheelClassName:it=`nowheel`,noPanClassName:at=`nopan`,fitView:ot,fitViewOptions:st,connectOnClick:ct,attributionPosition:lt,proOptions:ut,defaultEdgeOptions:dt,elevateNodesOnSelect:ft=!0,elevateEdgesOnSelect:pt=!1,disableKeyboardA11y:mt=!1,autoPanOnConnect:ht,autoPanOnNodeDrag:gt,autoPanOnSelection:_t=!0,autoPanSpeed:vt,connectionRadius:yt,isValidConnection:bt,onError:xt,style:St,id:Ct,nodeDragThreshold:wt,connectionDragThreshold:Tt,viewport:Et,onViewportChange:Dt,width:Ot,height:kt,colorMode:At=`light`,debug:jt,onScroll:Mt,ariaLabelConfig:Nt,zIndexMode:Pt=`basic`,...Ft},It){let Lt=Ct||`1`,Rt=Kc(At),zt=(0,y.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:`instant`}),Mt?.(e)},[Mt]);return(0,x.jsx)(`div`,{"data-testid":`rf__wrapper`,...Ft,onScroll:zt,style:{...St,...bd},ref:It,className:S([`react-flow`,i,Rt]),id:Ct,role:`application`,children:(0,x.jsxs)(yd,{nodes:e,edges:t,width:Ot,height:kt,fitView:ot,fitViewOptions:st,minZoom:we,maxZoom:Te,nodeOrigin:ye,nodeExtent:Oe,zIndexMode:Pt,children:[(0,x.jsx)(Wc,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,nodesDraggable:he,autoPanOnNodeFocus:ge,nodesConnectable:_e,nodesFocusable:ve,edgesFocusable:be,edgesReconnectable:xe,elementsSelectable:Se,elevateNodesOnSelect:ft,elevateEdgesOnSelect:pt,minZoom:we,maxZoom:Te,nodeExtent:Oe,onNodesChange:tt,onEdgesChange:nt,snapToGrid:de,snapGrid:fe,connectionMode:L,translateExtent:Ee,connectOnClick:ct,defaultEdgeOptions:dt,fitView:ot,fitViewOptions:st,onNodesDelete:k,onEdgesDelete:A,onDelete:j,onNodeDragStart:E,onNodeDrag:D,onNodeDragStop:O,onSelectionDrag:P,onSelectionDragStart:N,onSelectionDragStop:ee,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:at,nodeOrigin:ye,rfId:Lt,autoPanOnConnect:ht,autoPanOnNodeDrag:gt,autoPanSpeed:vt,onError:xt,connectionRadius:yt,isValidConnection:bt,selectNodesOnDrag:me,nodeDragThreshold:wt,connectionDragThreshold:Tt,onBeforeDelete:ne,debug:jt,ariaLabelConfig:Nt,zIndexMode:Pt}),(0,x.jsx)(md,{onInit:l,onNodeClick:s,onEdgeClick:c,onNodeMouseEnter:v,onNodeMouseMove:b,onNodeMouseLeave:C,onNodeContextMenu:w,onNodeDoubleClick:T,nodeTypes:a,edgeTypes:o,connectionLineType:R,connectionLineStyle:z,connectionLineComponent:B,connectionLineContainerStyle:re,selectionKeyCode:ae,selectionOnDrag:oe,selectionMode:se,deleteKeyCode:ie,multiSelectionKeyCode:le,panActivationKeyCode:ce,zoomActivationKeyCode:ue,onlyRenderVisibleElements:pe,defaultViewport:Ce,translateExtent:Ee,minZoom:we,maxZoom:Te,preventScrolling:De,zoomOnScroll:Ae,zoomOnPinch:je,zoomOnDoubleClick:Fe,panOnScroll:Me,panOnScrollSpeed:Ne,panOnScrollMode:Pe,panOnDrag:Ie,autoPanOnSelection:_t,onPaneClick:Le,onPaneMouseEnter:Re,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:Ve,onPaneContextMenu:He,paneClickDistance:Ue,nodeClickDistance:We,onSelectionContextMenu:F,onSelectionStart:I,onSelectionEnd:te,onReconnect:Ke,onReconnectStart:qe,onReconnectEnd:Je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Xe,onEdgeMouseEnter:Ze,onEdgeMouseMove:Qe,onEdgeMouseLeave:$e,reconnectRadius:et,defaultMarkerColor:ke,noDragClassName:rt,noWheelClassName:it,noPanClassName:at,rfId:Lt,disableKeyboardA11y:mt,nodeExtent:Oe,viewport:Et,onViewportChange:Dt,nodesDraggable:he}),(0,x.jsx)(Rc,{onSelectionChange:M}),Ge,(0,x.jsx)(Mc,{proOptions:ut,position:lt}),(0,x.jsx)(kc,{rfId:Lt,disableKeyboardA11y:mt})]})})}var Sd=ul(xd),Cd=e=>e.domNode?.querySelector(`.react-flow__edgelabel-renderer`);function J({children:e}){let t=G(Cd);return t?(0,gc.createPortal)(e,t):null}var wd=e=>({x:e.transform[0],y:e.transform[1],zoom:e.transform[2]});function Td(){return G(wd,hc)}function Ed(e){let[t,n]=(0,y.useState)(e);return[t,n,(0,y.useCallback)(e=>n(t=>el(e,t)),[])]}function Dd(e){let[t,n]=(0,y.useState)(e);return[t,n,(0,y.useCallback)(e=>n(t=>tl(e,t)),[])]}va.error014();function Od({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,x.jsx)(`path`,{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:S([`react-flow__background-pattern`,n,r])})}function kd({radius:e,className:t}){return(0,x.jsx)(`circle`,{cx:e,cy:e,r:e,className:S([`react-flow__background-pattern`,`dots`,t])})}var Ad;(function(e){e.Lines=`lines`,e.Dots=`dots`,e.Cross=`cross`})(Ad||={});var jd={[Ad.Dots]:1,[Ad.Lines]:1,[Ad.Cross]:6},Md=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Nd({id:e,variant:t=Ad.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=0,color:o,bgColor:s,style:c,className:l,patternClassName:u}){let d=(0,y.useRef)(null),{transform:f,patternId:p}=G(Md,hc),m=r||jd[t],h=t===Ad.Dots,g=t===Ad.Cross,_=Array.isArray(n)?n:[n,n],v=[_[0]*f[2]||1,_[1]*f[2]||1],b=m*f[2],C=Array.isArray(a)?a:[a,a],w=g?[b,b]:v,T=[C[0]*f[2]+w[0]/2,C[1]*f[2]+w[1]/2],E=`${p}${e||``}`;return(0,x.jsxs)(`svg`,{className:S([`react-flow__background`,l]),style:{...c,...Cl,"--xy-background-color-props":s,"--xy-background-pattern-color-props":o},ref:d,"data-testid":`rf__background`,children:[(0,x.jsx)(`pattern`,{id:E,x:f[0]%v[0],y:f[1]%v[1],width:v[0],height:v[1],patternUnits:`userSpaceOnUse`,patternTransform:`translate(-${T[0]},-${T[1]})`,children:h?(0,x.jsx)(kd,{radius:b/2,className:u}):(0,x.jsx)(Od,{dimensions:w,lineWidth:i,variant:t,className:u})}),(0,x.jsx)(`rect`,{x:`0`,y:`0`,width:`100%`,height:`100%`,fill:`url(#${E})`})]})}Nd.displayName=`Background`,(0,y.memo)(Nd);function Pd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,children:(0,x.jsx)(`path`,{d:`M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z`})})}function Fd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 5`,children:(0,x.jsx)(`path`,{d:`M0 0h32v4.2H0z`})})}function Id(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 30`,children:(0,x.jsx)(`path`,{d:`M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z`})})}function Ld(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,x.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z`})})}function Rd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,x.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z`})})}function zd({children:e,className:t,...n}){return(0,x.jsx)(`button`,{type:`button`,className:S([`react-flow__controls-button`,t]),...n,children:e})}var Bd=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Vd({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:o,onFitView:s,onInteractiveChange:c,className:l,children:u,position:d=`bottom-left`,orientation:f=`vertical`,"aria-label":p}){let m=bc(),{isInteractive:h,minZoomReached:g,maxZoomReached:_,ariaLabelConfig:v}=G(Bd,hc),{zoomIn:y,zoomOut:b,fitView:C}=vl();return(0,x.jsxs)(Ac,{className:S([`react-flow__controls`,f===`horizontal`?`horizontal`:`vertical`,l]),position:d,style:e,"data-testid":`rf__controls`,"aria-label":p??v[`controls.ariaLabel`],children:[t&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zd,{onClick:()=>{y(),a?.()},className:`react-flow__controls-zoomin`,title:v[`controls.zoomIn.ariaLabel`],"aria-label":v[`controls.zoomIn.ariaLabel`],disabled:_,children:(0,x.jsx)(Pd,{})}),(0,x.jsx)(zd,{onClick:()=>{b(),o?.()},className:`react-flow__controls-zoomout`,title:v[`controls.zoomOut.ariaLabel`],"aria-label":v[`controls.zoomOut.ariaLabel`],disabled:g,children:(0,x.jsx)(Fd,{})})]}),n&&(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:()=>{C(i),s?.()},title:v[`controls.fitView.ariaLabel`],"aria-label":v[`controls.fitView.ariaLabel`],children:(0,x.jsx)(Id,{})}),r&&(0,x.jsx)(zd,{className:`react-flow__controls-interactive`,onClick:()=>{m.setState({nodesDraggable:!h,nodesConnectable:!h,elementsSelectable:!h}),c?.(!h)},title:v[`controls.interactive.ariaLabel`],"aria-label":v[`controls.interactive.ariaLabel`],children:h?(0,x.jsx)(Rd,{}):(0,x.jsx)(Ld,{})}),u]})}Vd.displayName=`Controls`;var Hd=(0,y.memo)(Vd);function Ud({id:e,x:t,y:n,width:r,height:i,style:a,color:o,strokeColor:s,strokeWidth:c,className:l,borderRadius:u,shapeRendering:d,selected:f,onClick:p}){let{background:m,backgroundColor:h}=a||{},g=o||m||h;return(0,x.jsx)(`rect`,{className:S([`react-flow__minimap-node`,{selected:f},l]),x:t,y:n,rx:u,ry:u,width:r,height:i,style:{fill:g,stroke:s,strokeWidth:c},shapeRendering:d,onClick:p?t=>p(t,e):void 0})}var Wd=(0,y.memo)(Ud),Gd=e=>e.nodes.map(e=>e.id),Kd=e=>e instanceof Function?e:()=>e;function qd({nodeStrokeColor:e,nodeColor:t,nodeClassName:n=``,nodeBorderRadius:r=5,nodeStrokeWidth:i,nodeComponent:a=Wd,onClick:o}){let s=G(Gd,hc),c=Kd(t),l=Kd(e),u=Kd(n),d=typeof window>`u`||window.chrome?`crispEdges`:`geometricPrecision`;return(0,x.jsx)(x.Fragment,{children:s.map(e=>(0,x.jsx)(Yd,{id:e,nodeColorFunc:c,nodeStrokeColorFunc:l,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:i,NodeComponent:a,onClick:o,shapeRendering:d},e))})}function Jd({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:i,nodeStrokeWidth:a,shapeRendering:o,NodeComponent:s,onClick:c}){let{node:l,x:u,y:d,width:f,height:p}=G(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:i,y:a}=n.internals.positionAbsolute,{width:o,height:s}=uo(r);return{node:r,x:i,y:a,width:o,height:s}},hc);return!l||l.hidden||!fo(l)?null:(0,x.jsx)(s,{x:u,y:d,width:f,height:p,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:i,strokeColor:n(l),strokeWidth:a,shapeRendering:o,onClick:c,id:l.id})}var Yd=(0,y.memo)(Jd),Xd=(0,y.memo)(qd),Zd=200,Qd=150,$d=e=>!e.hidden,ef=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]},n=!1;for(let t of e.nodeLookup.values())if(!t.hidden){n=!0;break}return{viewBB:t,boundingRect:n?Za(Pa(e.nodeLookup,{filter:$d}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},tf=(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,nf=(e,t)=>tf(e.viewBB,t.viewBB)&&tf(e.boundingRect,t.boundingRect)&&e.rfId===t.rfId&&e.panZoom===t.panZoom&&e.translateExtent===t.translateExtent&&e.flowWidth===t.flowWidth&&e.flowHeight===t.flowHeight&&e.ariaLabelConfig===t.ariaLabelConfig,rf=`react-flow__minimap-desc`;function af({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:i=``,nodeBorderRadius:a=5,nodeStrokeWidth:o,nodeComponent:s,bgColor:c,maskColor:l,maskStrokeColor:u,maskStrokeWidth:d,position:f=`bottom-right`,onClick:p,onNodeClick:m,pannable:h=!1,zoomable:g=!1,ariaLabel:_,inversePan:v,zoomStep:b=1,offsetScale:C=5}){let w=bc(),T=(0,y.useRef)(null),{boundingRect:E,panZoom:D,viewBB:O,rfId:k,translateExtent:A,flowWidth:j,flowHeight:M,ariaLabelConfig:N}=G(ef,nf),P=e?.width??Zd,ee=e?.height??Qd,F=E.width/P,I=E.height/ee,te=Math.max(F,I),ne=te*P,L=te*ee,R=C*te,z=E.x-(ne-E.width)/2-R,B=E.y-(L-E.height)/2-R,re=ne+R*2,ie=L+R*2,ae=`${rf}-${k}`,oe=(0,y.useRef)(0),se=(0,y.useRef)();oe.current=te,(0,y.useEffect)(()=>{let e=w.getState().panZoom;if(T.current&&e)return se.current=As({domNode:T.current,panZoom:e,getTransform:()=>w.getState().transform,getViewScale:()=>oe.current}),()=>{se.current?.destroy()}},[D]),(0,y.useEffect)(()=>{se.current?.update({translateExtent:A,width:j,height:M,inversePan:v,pannable:h,zoomStep:b,zoomable:g})},[h,g,v,b,A,j,M]);let ce=p?e=>{let[t,n]=se.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,le=(0,y.useCallback)((e,t)=>{let n=w.getState().nodeLookup.get(t).internals.userNode;m?.(e,n)},[m]),ue=m?le:void 0,de=_??N[`minimap.ariaLabel`];return(0,x.jsx)(Ac,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c==`string`?c:void 0,"--xy-minimap-mask-background-color-props":typeof l==`string`?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof u==`string`?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d==`number`?d*te:void 0,"--xy-minimap-node-background-color-props":typeof r==`string`?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n==`string`?n:void 0,"--xy-minimap-node-stroke-width-props":typeof o==`number`?o:void 0},className:S([`react-flow__minimap`,t]),"data-testid":`rf__minimap`,children:(0,x.jsxs)(`svg`,{width:P,height:ee,viewBox:`${z} ${B} ${re} ${ie}`,className:`react-flow__minimap-svg`,role:`img`,"aria-labelledby":ae,ref:T,onClick:ce,children:[de&&(0,x.jsx)(`title`,{id:ae,children:de}),(0,x.jsx)(Xd,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:o,nodeComponent:s}),(0,x.jsx)(`path`,{className:`react-flow__minimap-mask`,d:`M${z-R},${B-R}h${re+R*2}v${ie+R*2}h${-re-R*2}z - M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}af.displayName=`MiniMap`;var of=(0,y.memo)(af),sf=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,cf={[Gs.Line]:`right`,[Gs.Handle]:`bottom-right`};function lf({nodeId:e,position:t,variant:n=Gs.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let v=Ll(),b=typeof e==`string`?e:v,C=bc(),w=(0,y.useRef)(null),T=n===Gs.Handle,E=G((0,y.useCallback)(sf(T&&p),[T,p]),hc),D=(0,y.useRef)(null),O=t??cf[n];(0,y.useEffect)(()=>{if(!(!w.current||!b))return D.current||=nc({domNode:w.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=C.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=C.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=ls([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...po({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};C.getState().triggerNodeChanges([n])}}),D.current.update({controlPosition:O,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{D.current?.destroy()}},[O,s,c,l,u,d,h,g,_,m]);let k=O.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__resize-control`,`nodrag`,...k,n,r]),ref:w,style:{...i,scale:E,...o&&{[T?`backgroundColor`:`borderColor`]:o}},children:a})}(0,y.memo)(lf);var uf=e=>e?.meta?.viewId??e?.meta?.diagramType??`architecture`,df=e=>e?.meta?.architectureView??`relations`,ff=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&df(e)!==`relations`,pf={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`},mf=Object.freeze([{id:`capabilities`,type:`architecture`,label:pf.capabilities},{id:`engineering`,type:`architecture`,label:pf.engineering},{id:`relations`,type:`architecture`,label:pf.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]),hf=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?df(e):e.meta.diagramType,gf=e=>mf.find(t=>t.id===hf(e))?.label??e?.meta?.diagramType??pf.relations,_f=(e,t)=>{let n=e=>{let t=mf.findIndex(t=>t.id===hf(e));return t<0?mf.length:t};return n(e)-n(t)},vf={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются."}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`}},yf=[`en`,...Object.keys(vf)];function bf(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(vf,r)?vf[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function xf(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}function Sf(e){if(!ff(e)||e.layout?.overviewConnections===`all`)return e.edges;let t=xf(e);return e.edges.filter(e=>t.has(e.source)&&t.get(e.source)===t.get(e.target))}var Cf=e=>({...e,edges:Sf(e)}),wf=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),Tf=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),Ef=Object.freeze({...wf,nodeGap:32,groupInset:24,groupGap:32});Object.freeze({...Tf,nodeGap:40,layerGap:48});var Df=e=>e?.cardLayout?Ef:wf,Of=.75,kf=.45;Object.freeze({width:1392,height:688});var Af=[`er`,`deployment`,`dataflow`,`usecase`],jf=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[Af.includes(e)?`right`:`down`],Mf=(e,t)=>(t?.direction??jf(e)[0])===`down`,Nf={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},Pf=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],Ff={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},If=`MIT License + M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}af.displayName=`MiniMap`;var of=(0,y.memo)(af),sf=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,cf={[Gs.Line]:`right`,[Gs.Handle]:`bottom-right`};function lf({nodeId:e,position:t,variant:n=Gs.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let v=Ll(),b=typeof e==`string`?e:v,C=bc(),w=(0,y.useRef)(null),T=n===Gs.Handle,E=G((0,y.useCallback)(sf(T&&p),[T,p]),hc),D=(0,y.useRef)(null),O=t??cf[n];(0,y.useEffect)(()=>{if(!(!w.current||!b))return D.current||=nc({domNode:w.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=C.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=C.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=ls([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...po({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};C.getState().triggerNodeChanges([n])}}),D.current.update({controlPosition:O,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{D.current?.destroy()}},[O,s,c,l,u,d,h,g,_,m]);let k=O.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__resize-control`,`nodrag`,...k,n,r]),ref:w,style:{...i,scale:E,...o&&{[T?`backgroundColor`:`borderColor`]:o}},children:a})}(0,y.memo)(lf);var uf=e=>e?.meta?.viewId??e?.meta?.diagramType??`architecture`,df=e=>e?.meta?.architectureView??`relations`,ff=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&df(e)!==`relations`,pf={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`},mf=Object.freeze([{id:`capabilities`,type:`architecture`,label:pf.capabilities},{id:`engineering`,type:`architecture`,label:pf.engineering},{id:`relations`,type:`architecture`,label:pf.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]),hf=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?df(e):e.meta.diagramType,gf=e=>mf.find(t=>t.id===hf(e))?.label??e?.meta?.diagramType??pf.relations,_f=(e,t)=>{let n=e=>{let t=mf.findIndex(t=>t.id===hf(e));return t<0?mf.length:t};return n(e)-n(t)},vf={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}},yf=[`en`,...Object.keys(vf)];function bf(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(vf,r)?vf[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function xf(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}var Sf=e=>!ff(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null;function Cf(e){let t=Sf(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function wf(e){let t=Sf(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!ff(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=xf(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function Tf(e){if(!Sf(e))return{...e,edges:wf(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of Cf(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:wf(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}var Ef=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),Df=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),Of=Object.freeze({...Ef,nodeGap:32,groupInset:24,groupGap:32});Object.freeze({...Df,nodeGap:40,layerGap:48});var kf=e=>e?.cardLayout?Of:Ef,Af=.75,jf=.45;Object.freeze({width:1392,height:688});var Mf=[`er`,`deployment`,`dataflow`,`usecase`],Nf=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[Mf.includes(e)?`right`:`down`],Pf=(e,t)=>(t?.direction??Nf(e)[0])===`down`,Ff={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},If=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],Lf={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},Rf=`MIT License Copyright (c) 2021-2022 Modulz Copyright (c) 2022-Present WorkOS @@ -256,9 +256,9 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -`,Y=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),Lf=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],Rf={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},zf={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},Bf=e=>parseInt(e.paper.slice(1,3),16)<128?zf:Rf,Vf=(e,t)=>({...Bf(t)[e.overviewTone??`subtle`]??Bf(t).subtle,role:`neutral`,label:`Components / actors`});function Hf(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}var Uf=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`],Wf=Object.fromEntries(Object.entries(Nf).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?Hf(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:Hf(n,e===`dark`?t[3]:t[1],.09),header:Hf(n,t[2],e===`dark`?.16:.09)})),sequenceTones:Pf.map(t=>Ff[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=Ff[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:Uf.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}])),Gf=new Set([`failure`]),Kf=new Set([`data`,`database`,`dataStore`,`entity`]),X={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},qf=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase()));function Jf(e,t){let n=2166136261;for(let t of e)n=Math.imul(n^t.codePointAt(0),16777619);return(n>>>0)%t}var Yf=(e,t)=>(e.tags??[]).some(e=>String(e).trim().toLowerCase()===t);function Xf(e){let t=e.nodes.filter(e=>e.kind===`state`);if(e.meta?.diagramType!==`state`||!t.some(qf))return new Map;let n=new Map(e.nodes.map(e=>[e.id,[]]));for(let t of e.edges)t.kind===`transition`&&t.source!==t.target&&n.get(t.source)?.push(t.target);let r=new Set(e.nodes.filter(e=>e.kind===`final`).map(e=>e.id)),i=new Map(e.nodes.filter(e=>e.kind===`initial`).map(e=>[e.id,0]));for(let e of i.keys())for(let t of n.get(e)??[])i.has(t)||i.set(t,i.get(e)+1);let a=e=>Yf(e,`failure`)?`failed`:qf(e)?`goal`:n.get(e.id).every(e=>r.has(e))?`ended`:`flight`,o=e=>i.get(e.id)??1/0,s=t.filter(e=>a(e)===`flight`).sort((e,t)=>Math.sign(o(e)-o(t))||0);return new Map(t.map(e=>[e.id,a(e)===`flight`?{role:`flight`,index:s.indexOf(e)}:{role:a(e)}]))}function Zf(e,t){let n=[...new Set(e.flatMap(e=>[...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)]).filter(Boolean))].sort(),r=new Map(n.map(e=>[e,t.moduleTones[Jf(e,t.moduleTones.length)]]));return r.stateTones=new Map(e.flatMap(e=>[...Xf(e)])),r}function Qf(e){let t=new Map(e);return t.stateTones=e.stateTones,t.plainStates=e.plainStates,t}function $f(e,t){for(let[n,r]of e)e.set(n,{...r,wash:t.card,header:t.surface2});return e.plainStates=!0,e}function ep(e,t){let n=new Map,r=t=>{let n=0,r=e.find(e=>e.id===t.parentId);for(;r&&ne.id===r.parentId);return n};for(let i of e)n.set(i.id,{fill:r(i)%2?t.groupFillNested:t.groupFill,stroke:t.groupLine});return n}var tp={goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state`};function np(e,t,n){if(e.overviewText!==void 0||e.badges!==void 0||e.overviewTone!==void 0)return Vf(e,t);let r=n?.get(e.module),i=e.kind===`state`?n?.stateTones?.get(e.id):void 0;if(i){let a=i.role===`flight`?t.stateTones.flight[i.index%t.stateTones.flight.length]:t.stateTones[i.role];return{role:i.role,label:tp[i.role],fill:n.plainStates?t.card:a.fill,stroke:a.stroke,ring:qf(e)?t.ringCore:void 0,toneIndex:i.index,moduleColor:r?.accent,chip:r?.chip,header:r?.header}}let a;a=[`initial`,`final`].includes(e.kind)?{role:e.kind,label:e.kind===`initial`?`Initial state`:`Final state`,fill:e.kind===`initial`?t.ink:t.surface,stroke:t.ink}:Gf.has(e.kind)?{role:`warning`,label:`Failure`,fill:t.card,stroke:t.warn,ring:t.ringWarn}:qf(e)?{role:`core`,label:`Core component`,fill:t.card,stroke:t.accent,ring:t.ringCore}:Kf.has(e.kind)||[`input`,`output`].includes(e.kind)?{role:`data`,label:`Data / storage`,fill:t.card,stroke:t.data}:[`start`,`end`,`usecase`].includes(e.kind)?{role:`accent`,label:e.kind===`usecase`?`Use case`:`Start / end`,fill:t.card,stroke:t.accent}:{role:`neutral`,label:`Components / actors`,fill:t.card,stroke:t.outline};let o=r&&![`initial`,`final`,`failure`].includes(e.kind);return{...a,fill:o?r.wash:a.fill,stroke:o?r.accent:a.stroke,moduleColor:r?.accent,chip:r?.chip,header:r?.header}}var rp=(e,t)=>e?t.sequenceTones[e.index%t.sequenceTones.length]:void 0;function ip(e,t,n,r,i,a){if(i?.overviewTone!==void 0)return Bf(n).edge;if(a)return rp(a,n);if(e.kind===`failure`)return n.warn;if(e.kind===`success`)return n.accent;let o=r?.get(e.module??i?.module??t?.module);return o?o.accent:Kf.has(t?.kind)?n.data:n.edge}function ap(e){let t={bg:`paper`,panel:`surface2`,canvas:`surface`,ink:`ink`,muted:`ink2`,line:`rule`,accent:`accent`,"accent-soft":`accentSoft`,warm:`warn`,guard:`guard`},n={"font-body":`body`,"font-small":`small`,"edge-line-height":`edgeLineHeight`};return Object.fromEntries([...Object.entries(t).map(([t,n])=>[`--${t}`,e[n]]),...Object.entries(n).map(([e,t])=>[`--${e}`,`${X[t]}px`])])}var op={source:`Source code`,code:`Code`,config:`Configuration`,schema:`Schema`,test:`Test`,document:`Document`,framework:`Framework convention`,inference:`Inference`},sp=e=>`${e.file}:${e.lineStart}${e.lineEnd?`-${e.lineEnd}`:``}`,cp={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function lp(e){let t=Math.min(X.erHeader,e.size.height*.4),n=Math.min(X.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(X.small,Math.min(X.body,n-6)),classHeaderHeight:X.classHeader+(e.subtitle?24:0),classRowHeight:X.classRow}}var up=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\u0000-\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),dp=`\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u3000-\\u303f\\uff00-\\uffef`,fp=RegExp(`[${dp}]`,`u`),pp=RegExp(`[${dp}]|[^${dp}]+`,`gu`),mp=/(?<=[_./\\\-=,;:|&)>\]}])|(?<=[a-z0-9])(?=[A-Z])/u,hp=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),gp=new Set([...`([{〔【《〈「『“‘`]),_p=(e,t)=>!gp.has([...e].at(-1))&&!hp.has([...t][0]);function vp(e,t,n){let r=[];for(let i of e.match(pp))if(fp.test(i)||up(i,t)<=n)r.push(i);else for(let e of i.split(mp))r.push(...up(e,t)<=n?[e]:e);return r}function Z(e,t,n=X.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\r?\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\s+|\S+/g)??[]){let e=up(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\s/.test(c)){for(let e of c){let i=up(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of vp(c,n,a)){let c=up(e,n);if(t&&r+c>a){if(_p(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&_p(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=up(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>up(e,n)))),height:o.length*r,lineHeight:r}}var yp=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,minHeight:64,maxWidth:360}),bp=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function xp(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;up(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}var Sp=(e,t)=>{let n=bf(t,cp[e.kind]??e.kind);return{text:n,width:Math.ceil(up(n,X.small)+n.length*.6)+2*yp.tagPad}};function Cp(e,t,n=!1,r=0){if(n){let t=Z(e.label,e.size.width-30,X.title,26),n=Z(e.subtitle??``,e.size.width-30,X.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=Sp(e,t),a=e.size.width-yp.textX-yp.pad,o=Z(e.label,a-i.width-yp.tagGap-r,X.title,yp.titleLine),s=Z(e.subtitle??``,a,X.body,yp.subtitleLine),c=Z(xp(bp(e),a,X.small),a,X.small,yp.sourceLine),l=yp.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+yp.pad;return{title:o,subtitle:s,source:c,tag:i,contentHeight:l,minHeight:Math.max(yp.minHeight,l)}}function wp(e,t=Tf.labelWidth){let n=Z(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function Tp(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\r`||n[i]===` +`,Y=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),zf=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],Bf={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},Vf={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},Hf=e=>parseInt(e.paper.slice(1,3),16)<128?Vf:Bf,Uf=(e,t)=>({...Hf(t)[e.overviewTone??`subtle`]??Hf(t).subtle,role:`neutral`,label:`Components / actors`});function Wf(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}var Gf=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`],Kf=Object.fromEntries(Object.entries(Ff).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?Wf(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:Wf(n,e===`dark`?t[3]:t[1],.09),header:Wf(n,t[2],e===`dark`?.16:.09)})),sequenceTones:If.map(t=>Lf[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=Lf[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:Gf.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}])),qf=new Set([`failure`]),Jf=new Set([`data`,`database`,`dataStore`,`entity`]),X={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},Yf=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase()));function Xf(e,t){let n=2166136261;for(let t of e)n=Math.imul(n^t.codePointAt(0),16777619);return(n>>>0)%t}var Zf=(e,t)=>(e.tags??[]).some(e=>String(e).trim().toLowerCase()===t);function Qf(e){let t=e.nodes.filter(e=>e.kind===`state`);if(e.meta?.diagramType!==`state`||!t.some(Yf))return new Map;let n=new Map(e.nodes.map(e=>[e.id,[]]));for(let t of e.edges)t.kind===`transition`&&t.source!==t.target&&n.get(t.source)?.push(t.target);let r=new Set(e.nodes.filter(e=>e.kind===`final`).map(e=>e.id)),i=new Map(e.nodes.filter(e=>e.kind===`initial`).map(e=>[e.id,0]));for(let e of i.keys())for(let t of n.get(e)??[])i.has(t)||i.set(t,i.get(e)+1);let a=e=>Zf(e,`failure`)?`failed`:Yf(e)?`goal`:n.get(e.id).every(e=>r.has(e))?`ended`:`flight`,o=e=>i.get(e.id)??1/0,s=t.filter(e=>a(e)===`flight`).sort((e,t)=>Math.sign(o(e)-o(t))||0);return new Map(t.map(e=>[e.id,a(e)===`flight`?{role:`flight`,index:s.indexOf(e)}:{role:a(e)}]))}function $f(e,t){let n=[...new Set(e.flatMap(e=>[...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)]).filter(Boolean))].sort(),r=new Map(n.map(e=>[e,t.moduleTones[Xf(e,t.moduleTones.length)]]));return r.stateTones=new Map(e.flatMap(e=>[...Qf(e)])),r}function ep(e){let t=new Map(e);return t.stateTones=e.stateTones,t.plainStates=e.plainStates,t}function tp(e,t){for(let[n,r]of e)e.set(n,{...r,wash:t.card,header:t.surface2});return e.plainStates=!0,e}function np(e,t){let n=new Map,r=t=>{let n=0,r=e.find(e=>e.id===t.parentId);for(;r&&ne.id===r.parentId);return n};for(let i of e)n.set(i.id,{fill:r(i)%2?t.groupFillNested:t.groupFill,stroke:t.groupLine});return n}var rp={goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state`};function ip(e,t,n){if(e.overviewText!==void 0||e.overviewTone!==void 0)return Uf(e,t);let r=n?.get(e.module),i=e.kind===`state`?n?.stateTones?.get(e.id):void 0;if(i){let a=i.role===`flight`?t.stateTones.flight[i.index%t.stateTones.flight.length]:t.stateTones[i.role];return{role:i.role,label:rp[i.role],fill:n.plainStates?t.card:a.fill,stroke:a.stroke,ring:Yf(e)?t.ringCore:void 0,toneIndex:i.index,moduleColor:r?.accent,chip:r?.chip,header:r?.header}}let a;a=[`initial`,`final`].includes(e.kind)?{role:e.kind,label:e.kind===`initial`?`Initial state`:`Final state`,fill:e.kind===`initial`?t.ink:t.surface,stroke:t.ink}:qf.has(e.kind)?{role:`warning`,label:`Failure`,fill:t.card,stroke:t.warn,ring:t.ringWarn}:Yf(e)?{role:`core`,label:`Core component`,fill:t.card,stroke:t.accent,ring:t.ringCore}:Jf.has(e.kind)||[`input`,`output`].includes(e.kind)?{role:`data`,label:`Data / storage`,fill:t.card,stroke:t.data}:[`start`,`end`,`usecase`].includes(e.kind)?{role:`accent`,label:e.kind===`usecase`?`Use case`:`Start / end`,fill:t.card,stroke:t.accent}:{role:`neutral`,label:`Components / actors`,fill:t.card,stroke:t.outline};let o=r&&![`initial`,`final`,`failure`].includes(e.kind);return{...a,fill:o?r.wash:a.fill,stroke:o?r.accent:a.stroke,moduleColor:r?.accent,chip:r?.chip,header:r?.header}}var ap=(e,t)=>e?t.sequenceTones[e.index%t.sequenceTones.length]:void 0;function op(e,t,n,r,i,a){if(i?.overviewTone!==void 0)return Hf(n).edge;if(a)return ap(a,n);if(e.kind===`failure`)return n.warn;if(e.kind===`success`)return n.accent;let o=r?.get(e.module??i?.module??t?.module);return o?o.accent:Jf.has(t?.kind)?n.data:n.edge}function sp(e){let t={bg:`paper`,panel:`surface2`,canvas:`surface`,ink:`ink`,muted:`ink2`,line:`rule`,accent:`accent`,"accent-soft":`accentSoft`,warm:`warn`,guard:`guard`},n={"font-body":`body`,"font-small":`small`,"edge-line-height":`edgeLineHeight`};return Object.fromEntries([...Object.entries(t).map(([t,n])=>[`--${t}`,e[n]]),...Object.entries(n).map(([e,t])=>[`--${e}`,`${X[t]}px`])])}var cp={source:`Source code`,code:`Code`,config:`Configuration`,schema:`Schema`,test:`Test`,document:`Document`,framework:`Framework convention`,inference:`Inference`},lp=e=>`${e.file}:${e.lineStart}${e.lineEnd?`-${e.lineEnd}`:``}`,up={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function dp(e){let t=Math.min(X.erHeader,e.size.height*.4),n=Math.min(X.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(X.small,Math.min(X.body,n-6)),classHeaderHeight:X.classHeader+(e.subtitle?24:0),classRowHeight:X.classRow}}var fp=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\u0000-\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),pp=`\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u3000-\\u303f\\uff00-\\uffef`,mp=RegExp(`[${pp}]`,`u`),hp=RegExp(`[${pp}]|[^${pp}]+`,`gu`),gp=/(?<=[_./\\\-=,;:|&)>\]}])|(?<=[a-z0-9])(?=[A-Z])/u,_p=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),vp=new Set([...`([{〔【《〈「『“‘`]),yp=(e,t)=>!vp.has([...e].at(-1))&&!_p.has([...t][0]);function bp(e,t,n){let r=[];for(let i of e.match(hp))if(mp.test(i)||fp(i,t)<=n)r.push(i);else for(let e of i.split(gp))r.push(...fp(e,t)<=n?[e]:e);return r}function Z(e,t,n=X.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\r?\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\s+|\S+/g)??[]){let e=fp(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\s/.test(c)){for(let e of c){let i=fp(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of bp(c,n,a)){let c=fp(e,n);if(t&&r+c>a){if(yp(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&yp(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=fp(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>fp(e,n)))),height:o.length*r,lineHeight:r}}var xp=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Sp=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Cp(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;fp(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}var wp=(e,t)=>{let n=bf(t,up[e.kind]??e.kind);return{text:n,width:Math.ceil(fp(n,X.small)+n.length*.6)+2*xp.tagPad}};function Tp(e,t,n=!1,r=0){if(n){let t=Z(e.label,e.size.width-30,X.title,26),n=Z(e.subtitle??``,e.size.width-30,X.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=wp(e,t),a=e.size.width-xp.textX-xp.pad,o=Z(e.label,a-i.width-xp.tagGap-r,X.title,xp.titleLine),s=Z(e.subtitle??``,a,X.body,xp.subtitleLine),c=Z(Cp(Sp(e),a,X.small),a,X.small,xp.sourceLine),l=Ep(e,a),u=l.length?(l.at(-1).row+1)*xp.chipLine:0,d=xp.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+xp.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(xp.minHeight,d)}}function Ep(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(fp(a,X.small)+a.length*.6)+2*xp.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+xp.chipGap}return n}function Dp(e,t=Df.labelWidth){let n=Z(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function Op(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\r`||n[i]===` `;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;nQ(t+16,n+26+r*22,e,`group`)).join(``)}function kp(e,t,n=0,r=0){let i=[`loop`,`par`].includes(e.kind)?5:14,a=e.kind===`security`?` stroke-dasharray="6 4"`:``;return``}function Ap(e=``){return String(e).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`)}function jp(e,t){return{value:String(e??``),width:t}}function Q(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\d.]+)px/)?.[1])||{title:X.title,"shape-title":X.title,"participant-title":X.title,body:X.body,"field-name":X.body,"field-type":X.body,member:X.body,"entity-title":X.title}[r]||X.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ap(e.text)}`:Ap(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&Z(s,1/0,o).width>n.width){let e=Math.max(0,n.width-Z(`…`,1/0,o).width);s=e?(Z(s,e,o).lines[0]??``)+`…`:`…`}return`${Ap(s)}`}function Mp(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=Z(n,r,X.title,29),s=Z(a,r,X.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>Q(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function Np(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ap(t)}"`).join(``)}/>`).join(``)}var Pp=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fp=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ip=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Lp=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Rp=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],zp=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Bp=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function Vp(e,t,n=0,r=0){let i=Bp(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Hp(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Bp(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return Vp(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return Vp(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function Up(e,t,n=0,r=0,i=0){let a=Bp(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return Vp(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return Vp(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Wp(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Bp(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return Vp(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function Gp(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}function Kp(e,t=``){return`${t}.heading{font:650 24px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;fill:${e.ink};letter-spacing:-.5px} +`;)i++;return i===n.length&&a.every(Boolean)?a:null}function kp(e,t){let{width:n,height:r}=Dp(e,t);return{width:n,height:r}}function Ap(e){let t=Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-2*Ef.groupInset)),n=Z(e.label,t,X.small+1.12,22);return{...n,height:12+n.height}}function jp(e,t=0,n=0){return Ap(e).lines.map((e,r)=>Q(t+16,n+26+r*22,e,`group`)).join(``)}function Mp(e,t,n=0,r=0){let i=[`loop`,`par`].includes(e.kind)?5:14,a=e.kind===`security`?` stroke-dasharray="6 4"`:``;return``}function Np(e=``){return String(e).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`)}function Pp(e,t){return{value:String(e??``),width:t}}function Q(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\d.]+)px/)?.[1])||{title:X.title,"shape-title":X.title,"participant-title":X.title,body:X.body,"field-name":X.body,"field-type":X.body,member:X.body,"entity-title":X.title}[r]||X.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Np(e.text)}`:Np(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&Z(s,1/0,o).width>n.width){let e=Math.max(0,n.width-Z(`…`,1/0,o).width);s=e?(Z(s,e,o).lines[0]??``)+`…`:`…`}return`${Np(s)}`}function Fp(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=Z(n,r,X.title,29),s=Z(a,r,X.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>Q(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function Ip(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Np(t)}"`).join(``)}/>`).join(``)}var Lp=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Rp=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},zp=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Bp=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Vp=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],Hp=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Up=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function Wp(e,t,n=0,r=0){let i=Up(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Gp(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Up(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return Wp(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return Wp(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function Kp(e,t,n=0,r=0,i=0){let a=Up(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return Wp(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return Wp(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function qp(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Up(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return Wp(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function Jp(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}function Yp(e,t=``){return`${t}.heading{font:650 24px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;fill:${e.ink};letter-spacing:-.5px} ${t}.meta{font:400 ${X.small}px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;fill:${e.ink3}} ${t}.group{font:650 ${X.small}px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;fill:${e.ink2};letter-spacing:.4px} ${t}[data-diagram-group-id]>.group{fill:${e.ink2}} @@ -275,15 +275,15 @@ ${t}.entity-meta{font:500 ${X.small}px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;fill:${e.ink2}} ${t}.member{font:500 ${X.body}px ui-monospace,monospace;fill:${e.ink2}} ${t}.field-type{font:400 ${X.body}px ui-monospace,monospace;fill:${e.ink3}} -`}function qp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return Zp(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,contentHeight:m}=Cp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),h=t+c,g=n+Math.max(0,(e.size.height-m)/2)+yp.pad,_=h+yp.textX,v=g+u.height+(d.height?4:0),y=v+d.height+(f.height?6:0),b=u.lines.map((e,t)=>Q(_,g+20+t*u.lineHeight,e,`title`)).join(``),x=d.lines.map((e,t)=>Q(_,v+17+t*d.lineHeight,e,`body`)).join(``),S=f.lines.map((e,t)=>Q(_,y+14+t*f.lineHeight,e,`meta`)).join(``),C={x:h+yp.pad,y:g+(yp.titleLine-yp.plate)/2},w=t+e.size.width-c-yp.pad-p.width-l;return`${Jp(e,t,n,r,i,s)}${Yp(e,C.x,C.y,yp.plate,a)}${Q(w+p.width/2,g+18,p.text,`stereotype`,` text-anchor="middle"`)}${b}${x}${S}`}var Jp=(e,t,n,r,i,a)=>Np(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Yp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:qf(e)?i.accent:Kf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${Xp(e)}`}var Xp=e=>Kf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function Zp(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Cp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Jp(e,t,n,r,i,s)}${Yp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,Sp(e,o).text,`stereotype`)}${d}${f}`}var Qp=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],$p=[[.08,0],[1,0],[.92,1],[0,1]];function em(e,t,n){let{width:r,height:i}=e.size;if(bg(e))return Pp(e,t,n,16);if(e.kind===`external`)return Lp(e,t,n,Ip);if(e.kind===`security`)return Pp(e,t,n,22);if(e.kind===`failure`)return Lp(e,t,n,Qp);if(e.kind===`config`)return Lp(e,t,n,$p);if(e.kind===`business`)return Pp(e,t,n,Math.min(28,i/2));let a=Pp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var tm=(e,t,n)=>bg(e)?Hp(e,t,n,16):e.kind===`external`?Wp(e,t,n,Ip):e.kind===`security`?Hp(e,t,n,22):e.kind===`failure`?Wp(e,t,n,Qp):e.kind===`config`?Wp(e,t,n,$p):e.kind===`business`?Hp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Vp(e,t,n,{left:12,right:12,top:2,bottom:2}):Vp(e,t,n),nm=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,rm={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>bg(e)?kg(e,t,n,a,r,i):qp(e,t,n,r,i,a,o,em,nm(e)),outline:em,anchor:tm,cardLayout:!0,contentInset:nm},im=.12,am=(e,t,n)=>e.kind===`decision`?Rp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*im},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Pp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),om=(e,t,n)=>e.kind===`decision`?Wp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Wp(e,t,n,[[im,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Hp(e,t,n,e.size.height/2):Vp(e,t,n),sm=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*im+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function cm(e,t,n,r,i){let{width:a,height:o}=e.size,s=sm(e),c=Mp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Np(am(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var lm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:cm,outline:am,anchor:om,textArea:sm,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},um=(e,t,n)=>e.kind===`actor`?zp(e,t,n):Pp(e,t,n,7,dm(e));function dm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function fm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=dm(e),u=Np(um(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,cp[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ap([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var pm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:fm,outline:um,sequence:!0,selectionHeight:dm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},mm=(e,t,n)=>Pp(e,t,n,9);function hm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=lp(e),u=jp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,jp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,jp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Np(mm(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,jp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var gm={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:hm,outline:mm,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},_m=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function vm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Lp(e,t,n,_m),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Pp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fp(e,t,n):e.kind===`external`?Lp(e,t,n,Ip):e.kind===`service`?Pp(e,t,n,16):Pp(e,t,n,10)}var ym=(e,t,n)=>e.kind===`device`?Vp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Wp(e,t,n,_m):e.kind===`database`?Vp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Wp(e,t,n,Ip):e.kind===`service`?Hp(e,t,n,16):Vp(e,t,n),bm=e=>({container:24,artifact:18,node:20})[e.kind]??0,xm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Sm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>qp(e,...t,vm,xm(e),bm(e)),outline:vm,anchor:ym,cardLayout:!0,contentInset:xm,cardCorner:bm},Cm=(e,t,n)=>Pp(e,t,n,9);function wm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=lp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,jp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,jp(e,m),`member`)).join(``);return`${Np(Cm(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),jp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,jp(e.subtitle,m),`body`):``}${h}${g}`}var Tm={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:wm,outline:Cm,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=Ep(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},Em=e=>e.subtitle?14:e.size.width/2,Dm=[`entry`,`do`,`exit`],Om={side:16,pad:8,line:20,keyWidth:64};function km(e){let t=e.kind===`state`?Dm.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*Om.side-Om.keyWidth,X.small,Om.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*Om.line+2*Om.pad:0}}var Am=2*Om.side+Om.keyWidth,jm=e=>{let{height:t}=km(e);return t?{x:Om.side,y:e.size.height-t,width:e.size.width-2*Om.side,height:t}:null},Mm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+Em(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Rp(e,t,n):Pp(e,t,n,12),Nm=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=Em(e)-e.size.width/2;return Up({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Wp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Vp(e,t,n)},Pm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=km(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Fm(e,t,n,r,i){let{rows:a,height:o}=km(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+Om.pad+c++*Om.line+15;return(r?``:Q(t+Om.side,a,`${e.key} /`,`field-key`))+Q(t+Om.side+Om.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function Im(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Pm(e),o=e.kind===`final`;return`${Np(Mm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Mp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Pm(e),l=n+(e.size.height-km(e).height)/2;return`${Np(Mm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Mp(o,l,e.label,c.width,c.height,e.subtitle)}${Fm(e,t,n,i,a)}`}var Lm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Rm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:Im,outline:Mm,anchor:Nm,textArea:Pm,activityArea:jm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Lm(e).map(e=>e.text).join(` `),edgeLabelParts:Lm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Dm)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},zm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Bm=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Vm=(e,t,n)=>e.kind===`actor`?zp(e,t,n+zm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Hm=(e,t,n)=>e.kind===`actor`?Gp(e,t,n,zm(e)):Up(e,t,n);function Um(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Np(Vm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+zm(e)+98,jp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+zm(e)+122,jp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Bm(e);return`${Np(Vm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Mp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var Wm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Um,outline:Vm,anchor:Hm,textArea:Bm,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Gm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Pp(e,t,n,e.kind===`process`?24:10),Km=e=>({width:e.size.width-32,height:e.size.height-20});function qm(e,t,n,r,i){let a=Km(e);return`${Np(Gm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Mp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Jm=[rm,lm,pm,gm,Sm,Tm,Rm,Wm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:qm,outline:Gm,textArea:Km,anchor:(e,t,n)=>e.kind===`process`?Hp(e,t,n,24):Vp(e,t,n)}],Ym=Jm.map(e=>e.id);Object.fromEntries(Jm.map(e=>[e.id,e.label]));var Xm=new Map(Jm.map(e=>[e.id,e]));if(Xm.size!==Jm.length)throw Error(`Duplicate diagram type`);var Zm=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>Xm.get(e),Qm=(e,t,n,r=!1)=>t===`architecture`&&bg(e)?Sg(e):Cp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),$m=e=>{let t=Zm(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Qm(n,t,e.meta?.locale).minHeight)},eh=(e,t)=>!($(t).undirected??[]).includes(e.kind),th=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),nh=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),rh=(e,t)=>({start:null,end:eh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),ih=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ah=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),oh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var sh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,ch=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),lh=(e,t)=>e?.id??String(t);function uh(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(lh(i,t))}`);return n}function dh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===lh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>dh(e,t,n,r,a)))]}function fh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>lh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=lh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=dh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function ph(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function mh(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>ph(n,t)-ph(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var hh=e=>Z(e.label,Math.min(Tf.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function gh(e,t){let n={...e.position,...e.size},r=hh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>sh(e,t,4)))}function _h(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...ch(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>sh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:lh(null,0)}]}}function vh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;sh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=gh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=_h(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===lh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=dh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...ch(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Tf.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1dh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...ch(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...ch(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${lh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Tf.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>sh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=lh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${lh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function yh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function bh(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function xh(e,t,n=bh(e),r=uh(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Sh=140,Ch=54,wh=(e,t)=>(e.route?.messageY??Sh+e.order*Ch)+(t===`receive`&&e.source===e.target?30:0);function Th(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):wh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=uh(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=wh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:wh(n.get(i.end.edgeId),i.end.at)-l}})}function Dh(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var Oh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),kh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Ah(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function jh(e,t=Kh(e)){e=Cf(e);let n=[..._g(e),...e.groups??[],...e.nodes,...Eh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Ah(n.sourceCardinality,e.points[0],e.points[1]),Ah(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Mh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=Oh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nh(e,t,n=wf.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Ph(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Fh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function Ih(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lh(e,t,n,r){let i={clearance:-1,length:-1,point:Ih(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rh(e,t){let n=Oh(e),r=Oh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Qh(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Nh(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Fh(f,e);return Fh(f,Nh(t,r,a)),f.push(t),Ph(f)}function Vh(e,t,n,r,i,a=wf.endpoint,o=`architecture`){let s=Mh(e,n.sourceSide,r,o),c=Mh(t,n.targetSide,i,o),l=Nh(s,n.sourceSide,a),u=Nh(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Ph([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Ph([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Hh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Uh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var Wh=(e,t=0,n=0)=>e.curved&&Uh(e,t,n)||Hh(e.points,t,n);function Gh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=wh(e,`send`),u=wh(e,`receive`),d=Dh(o,t.id,e,`send`,l,s.get(e.id)),f=Dh(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||Oh(t).x<=Oh(n).x,m=d?d.x+(p?d.width:0):Oh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):Oh(n).x,g=xh(a,e,c,s),_=wp(g,t.id===n.id?Tf.labelWidth:Math.min(Tf.labelWidth,Math.max(1,Math.abs(h-m)-32-12))),v={width:_.width,height:_.height};if(t.id===n.id){let t=48+r*wf.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Bh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:_.lines,labelSize:v,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+v.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:_.lines,labelSize:v,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-v.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Kh(e){e=Cf(e);let t=Zm(e),n=$(t).endpointStub??wf.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rh(t,n)}}),a=t===`sequence`?{graph:e,executions:Eh(e),scopes:uh(e),pairs:bh(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?Oh(i).y:Oh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*wf.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Jh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,dm(e))}:{...e.position,...e.size}}function Yh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Xh(e,t,n,r){let i=Qh(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=Oh(t),o=Mh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function Zh(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&Zh(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=Oh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Mh(n,`left`,o,r).x,c=Mh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Mh(n,`top`,o,r).y,c=Mh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function ig(e){e=Cf(e);let t=Zm(e),n=[],r=Kh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Eh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightsh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!$m(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:yp.minHeight))continue;let{minHeight:r}=t===`architecture`&&bg(n)?Sg(n):Cp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ewf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${wf.endpoint}px`);let f=rg(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!Xh(i.points[0],a,i.sourceSide,t)||!Xh(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nh(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(Oh(a).x-Oh(o).x),t=Math.max(160,i.labelBox.width+32);eqh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),eg(t).some(([e,t])=>Zh(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)qh(i.labelBox,Qh(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=eg(r);for(let i=1;iZh(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ng(a,o,e,t)>wf.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var ag=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),og=(e,t,n)=>Math.max(t,Math.min(n,e)),sg=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=og(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function cg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(sg(e,n,r),sg(t,n,r),sg(n,e,t),sg(r,e,t))}function lg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function ug(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function dg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:og(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:og((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>sg({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>cg(e,t,r,n[(i+1)%n.length])))}var pg=new WeakMap;function mg(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=pg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+zm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,sg({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>cg(e,a,t,n)),...i.map(t=>lg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>dg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>fg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,sg({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>ug(e,t,c);else{let n=s===`rect`?c:Qh(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,lg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),lg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},pg.set(e,{signature:n,probe:l}),l}function hg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return eg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function gg(e,t,n=[]){let r=new Set(n),i=Zm(t),a=ag(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Jh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Kh(e),d=Df($(i)).labelGap,f=[...o.map(e=>Jh(e,i)),...l.flatMap(tg)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>Zh(r,e,t))||l.some(n=>hg(r,e,n).distanceZh(r,e,t)))}))&&r.add(n.id)}return r}var _g=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},vg=e=>e&&typeof e==`object`&&!Array.isArray(e),yg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),bg=e=>e.overviewText!==void 0||e.badges!==void 0||e.overviewTone!==void 0;function xg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!Lf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{vg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!yg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!vg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!vg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!yg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!vg(e.position)||!vg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!yg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!vg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Sg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Cg=e=>e.frame===`none`?0:Y.padding,wg=(e,t)=>{let n=t-Cg(e)*2;return Cg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Tg(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Cg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function Eg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=_g(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Dg=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Og=(e,t,n,r,i=``)=>`${Dg(n)}`;function kg(e,t,n,r){let i=Bf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Sg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Og(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Og(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ag(e,t,n=0,r=0){let i=Bf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Cg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>Og(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>Og(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function jg(e,t=new Map){if(!ff(e))return[];let n=[],r=_g(e);for(let t of r){let r=wg(t,t.size.width)+Cg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Cg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Cg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Tg(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Mg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=np(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Np(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` -`);return`${Ap(g)}${h}${m}`}function Ng(e,t){let n=$(t);return{markup:Np(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Pg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Np(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Fg({data:e,pulse:t}){let{markup:n,height:r}=Ng(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}function Ig({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Lg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Mg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${qf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(Ig,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Fg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Rg({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:kp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` -`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Op(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:yh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:yh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function zg({value:e,point:t,neighbor:n,color:r}){let i=Ah(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Bg({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=rh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(zg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Vg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ag(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Hg={diagram:Lg,boundary:Rg,overview:Vg},Ug={routed:Bg};function Wg(e,t){let n=[...e.groups??[]].sort((t,n)=>ph(t,e.groups??[])-ph(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+ph(t,e.groups??[])})),r=!$m(e);return[..._g(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...n,diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Gg(e,t){return Sf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:eh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Kg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function qg(e,t,n){e=Cf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=np(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!th(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>th(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Jg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}function x(e){if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let t=b(e);return e.edges.filter(e=>t.has(e.source)&&t.get(e.source)===t.get(e.target))}let S=e=>({...e,edges:x(e)});function C(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}let w={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ee=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],te={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},T=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ne=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],re={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},ie={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},ae=e=>parseInt(e.paper.slice(1,3),16)<128?ie:re;function oe(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let se=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(w).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?oe(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:oe(n,e===`dark`?t[3]:t[1],.09),header:oe(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ee.map(t=>te[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=te[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:se.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ce=new Set([`data`,`database`,`dataStore`,`entity`]),E={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},le=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),ue={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function de(e){let t=Math.min(E.erHeader,e.size.height*.4),n=Math.min(E.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(E.small,Math.min(E.body,n-6)),classHeaderHeight:E.classHeader+(e.subtitle?24:0),classRowHeight:E.classRow}}var fe={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются."}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`}};let pe=[`en`,...Object.keys(fe)];function D(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(fe,r)?fe[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let O=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),me=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,he=RegExp(`[${me}]`,`u`),ge=RegExp(`[${me}]|[^${me}]+`,`gu`),_e=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,ve=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),ye=new Set([...`([{〔【《〈「『“‘`]),be=(e,t)=>!ye.has([...e].at(-1))&&!ve.has([...t][0]);function xe(e,t,n){let r=[];for(let i of e.match(ge))if(he.test(i)||O(i,t)<=n)r.push(i);else for(let e of i.split(_e))r.push(...O(e,t)<=n?[e]:e);return r}function k(e,t,n=E.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=O(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=O(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of xe(c,n,a)){let c=O(e,n);if(t&&r+c>a){if(be(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&be(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=O(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>O(e,n)))),height:o.length*r,lineHeight:r}}let A=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,minHeight:64,maxWidth:360}),Se=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ce(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;O(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let we=(e,t)=>{let n=D(t,ue[e.kind]??e.kind);return{text:n,width:Math.ceil(O(n,E.small)+n.length*.6)+2*A.tagPad}};function Te(e,t,n=!1,r=0){if(n){let t=k(e.label,e.size.width-30,E.title,26),n=k(e.subtitle??``,e.size.width-30,E.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=we(e,t),a=e.size.width-A.textX-A.pad,o=k(e.label,a-i.width-A.tagGap-r,E.title,A.titleLine),s=k(e.subtitle??``,a,E.body,A.subtitleLine),c=k(Ce(Se(e),a,E.small),a,E.small,A.sourceLine),l=A.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+A.pad;return{title:o,subtitle:s,source:c,tag:i,contentHeight:l,minHeight:Math.max(A.minHeight,l)}}function Ee(e,t=f.labelWidth){let n=k(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function De(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function M(e,t){return{value:String(e??``),width:t}}function N(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:E.title,"shape-title":E.title,"participant-title":E.title,body:E.body,"field-name":E.body,"field-type":E.body,member:E.body,"entity-title":E.title}[r]||E.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${ke(e.text)}`:ke(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&k(s,1/0,o).width>n.width){let e=Math.max(0,n.width-k(`…`,1/0,o).width);s=e?(k(s,e,o).lines[0]??``)+`…`:`…`}return`${ke(s)}`}function Ae(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=k(n,r,E.title,29),s=k(a,r,E.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>N(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function P(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${ke(t)}"`).join(``)}/>`).join(``)}let F=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],je=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Me=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Ne=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Pe=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],Fe=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Ie=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function I(e,t,n=0,r=0){let i=Ie(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Le(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Ie(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return I(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return I(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function Re(e,t,n=0,r=0,i=0){let a=Ie(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return I(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return I(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function ze(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Ie(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return I(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function Be(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ve=(e,t,n)=>e.kind===`actor`?Fe(e,t,n):F(e,t,n,7,He(e));function He(e){let t=(e.size?.width??280)-28,n=k(e.label,t,20,26).lines.length,r=e.subtitle?k(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?E.sequenceActorHeader+(e.subtitle?22:0):E.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function Ue(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=He(e),u=P(Ve(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=k(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:N(s,n+20,D(o,ue[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>N(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?k(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>N(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${ke([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var We={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:Ue,outline:Ve,sequence:!0,selectionHeight:He,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ge=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Ke=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),qe=(e,t,n)=>e.kind===`actor`?Fe(e,t,n+Ge(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Je=(e,t,n)=>e.kind===`actor`?Be(e,t,n,Ge(e)):Re(e,t,n);function Ye(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${P(qe(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${N(o,n+Ge(e)+98,M(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?N(o,n+Ge(e)+122,M(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Ke(e);return`${P(qe(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Ae(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var Xe={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Ye,outline:qe,anchor:Je,textArea:Ke,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let Ze=e=>e.subtitle?14:e.size.width/2,Qe=[`entry`,`do`,`exit`],L={side:16,pad:8,line:20,keyWidth:64};function $e(e){let t=e.kind===`state`?Qe.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:k(e[t],e.size.width-2*L.side-L.keyWidth,E.small,L.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*L.line+2*L.pad:0}}let et=2*L.side+L.keyWidth,tt=e=>{let{height:t}=$e(e);return t?{x:L.side,y:e.size.height-t,width:e.size.width-2*L.side,height:t}:null},nt=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+Ze(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Pe(e,t,n):F(e,t,n,12),rt=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=Ze(e)-e.size.width/2;return Re({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?ze(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):I(e,t,n)},it=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=$e(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function at(e,t,n,r,i){let{rows:a,height:o}=$e(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+L.pad+c++*L.line+15;return(r?``:N(t+L.side,a,`${e.key} /`,`field-key`))+N(t+L.side+L.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ot(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=it(e),o=e.kind===`final`;return`${P(nt(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Ae(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=it(e),l=n+(e.size.height-$e(e).height)/2;return`${P(nt(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Ae(o,l,e.label,c.width,c.height,e.subtitle)}${at(e,t,n,i,a)}`}let st=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ct={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ot,outline:nt,anchor:rt,textArea:it,activityArea:tt,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>st(e).map(e=>e.text).join(` `),edgeLabelParts:st,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Qe)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let lt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,ut=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),R=(e,t)=>e?.id??String(t);function dt(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(R(i,t))}`);return n}function ft(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===R(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>ft(e,t,n,r,a)))]}function pt(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>R(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=R(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=ft(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function mt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let ht=e=>k(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function gt(e,t){let n={...e.position,...e.size},r=ht(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>lt(e,t,4)))}function _t(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...ut(e)]),...r],f=k(D(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>lt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:R(null,0)}]}}function vt(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;lt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=gt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=_t(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===R(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=ft(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...ut(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:k(c,l,14,20).height+16+(n.body?k(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1ft(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...ut(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...ut(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${R(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=k(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>lt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=R(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${R(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function yt(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function bt(e,t,n=yt(e),r=dt(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function xt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ee(bt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Ct(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):St(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=dt(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=St(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:St(n.get(i.end.edgeId),i.end.at)-l}})}function Tt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let z=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Et=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function Dt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ot(e,t=V(e)){e=S(e);let n=[...J(e),...e.groups??[],...e.nodes,...wt(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Dt(n.sourceCardinality,e.points[0],e.points[1]),Dt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function B(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=z(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function kt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function At(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function jt(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function Mt(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Nt(e,t,n,r){let i={clearance:-1,length:-1,point:Mt(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Pt(e,t){let n=z(e),r=z(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Ft(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?W(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,kt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)jt(p,e);return jt(p,kt(t,r,a)),p.push(t),At(p)}function Lt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=B(e,n.sourceSide,r,o),c=B(t,n.targetSide,i,o),l=kt(s,n.sourceSide,a),u=kt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return At([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return At([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Rt(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function zt(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Bt=(e,t=0,n=0)=>e.curved&&zt(e,t,n)||Rt(e.points,t,n);function Vt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=St(e,`send`),u=St(e,`receive`),p=Tt(o,t.id,e,`send`,l,s.get(e.id)),m=Tt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||z(t).x<=z(n).x,g=p?p.x+(h?p.width:0):z(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):z(n).x,v=bt(a,e,c,s),y=Ee(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,Math.abs(_-g)-32-12))),b={width:y.width,height:y.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?It(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:y.lines,labelSize:b,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+b.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?It({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:y.lines,labelSize:b,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-b.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function V(e){e=S(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Pt(t,n)}}),o=t===`sequence`?{graph:e,executions:wt(e),scopes:dt(e),pairs:yt(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?z(i).y:z(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function H(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,He(e))}:{...e.position,...e.size}}function Ut(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Wt(e,t,n,r){let i=W(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=z(t),o=B(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function U(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&U(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=z(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=B(n,`left`,o,r).x,c=B(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=B(n,`top`,o,r).y,c=B(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function Xt(e){e=S(e);let t=Y(e),n=[],r=V(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...wt(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightlt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!Pr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:A.minHeight))continue;let{minHeight:r}=t===`architecture`&&In(n)?Rn(n):Te(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=Yt(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Wt(i.points[0],a,i.sourceSide,t)||!Wt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=kt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(z(a).x-z(o).x),t=Math.max(160,i.labelBox.width+32);eHt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Kt(t).some(([e,t])=>U(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Ht(i.labelBox,W(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Kt(r);for(let i=1;iU(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>Jt(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let Zt=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),Qt=(e,t,n)=>Math.max(t,Math.min(n,e)),$t=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=Qt(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function en(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min($t(e,n,r),$t(t,n,r),$t(n,e,t),$t(r,e,t))}function tn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function nn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function rn(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:Qt(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:Qt((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>$t({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>en(e,t,r,n[(i+1)%n.length])))}let on=new WeakMap;function sn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=on.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ge(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,k(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,$t({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>en(e,a,t,n)),...i.map(t=>tn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>rn(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>an(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,$t({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>nn(e,t,c);else{let n=s===`rect`?c:W(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,tn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),tn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},on.set(e,{signature:n,probe:l}),l}function cn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Kt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function ln(e,t,n,r=[],i=[]){let a=Y(e),o=Zt(e),s=e.nodes.map(e=>({node:e,probe:sn(e,a),bounds:W(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(tn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001cn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=H(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=V(e),d=h(X(i)).labelGap,f=[...o.map(e=>H(e,i)),...l.flatMap(qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>U(r,e,t))||l.some(n=>cn(r,e,n).distanceU(r,e,t)))}))&&r.add(n.id)}return r}let dn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),fn=e=>({...e.position,...e.size}),pn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),mn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),hn=e=>e.x+`,`+e.y,gn=(e,t)=>e.idt.id);var _n=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function yn(e,t,n=32){let r=vn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=vn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=H(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function xn(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=W(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||gn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Sn(e,n,t+f-d,r,i))}function Sn(e,t,n,r,i){let a=B(e,t,n,r),[o,s]=G[t],c=fn(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function Cn(e,t,n,r=null,i=null){let a=Y(n),o=bn(n),s=[];for(let c of r?[r]:dn)for(let r of dn){let l=xn(e,t,c,a,o,n,i),u=xn(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=W(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Sn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||dn.indexOf(e.sourceSide)-dn.indexOf(t.sourceSide)||dn.indexOf(e.targetSide)-dn.indexOf(t.targetSide))}function wn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function Tn(e,t){let n=e=>({source:hn(e[0]),target:hn(e.at(-1))});return Yt(n(e),e,n(t),t).length}function En(e,t){let n=e.nodes.map(e=>({node:e,r:W(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Gt(e,r,n,t))}function Dn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=wn(i,a,p,m,n);if(r===1/0){let n=Jt(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+hn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function On(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=j(o),f=t.nodes.map(e=>H(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Kt),h=En(t,u),g=Dn(r,i),_=ln(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>Jt(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>U(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+Tn(t,n),0)*i.crossingCost,o&&!kn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>H(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,ee=Math.min(...b.map(e=>e.y))-S,te=Math.max(...b.map(e=>e.y+e.height))+S,T;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[ee,te].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=vn([e.point,...n,t.point]),i=y(r,Math.min(s,T?.cost??1/0));Number.isFinite(i)&&(!T||iH(e,u)),re=new Set([...c,...l].map(e=>e.stub.x)),ie=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...ne,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])re.add(e.x-i.preferredClearance),re.add(e.x+e.width+i.preferredClearance),ie.add(e.y-i.preferredClearance),ie.add(e.y+e.height+i.preferredClearance);let ae=[...re].sort((e,t)=>e-t),oe=[...ie].sort((e,t)=>e-t),se=ae.length,ce=e=>({x:ae[e%se],y:oe[Math.floor(e/se)]}),E=e=>oe.indexOf(e.y)*se+ae.indexOf(e.x),le=new Map,ue=(e,t)=>{let r=hn(e),i=hn(t),a=rU(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),le.set(a,o),o},de=e=>Math.min(...l.map(t=>K(e,t.stub))),fe=new _n,pe=new Map,D=new Map,O=0;for(let e of l){let t=E(e.stub);D.has(t)||D.set(t,[]),D.get(t).push(e)}for(let e of c){if(n.some(t=>U(e.point,e.stub,t))||!Number.isFinite(ue(e.point,e.stub)))continue;let t=E(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+de(e.stub),start:e,serial:O++},o=t*2+r;(!pe.has(o)||pe.get(o).cost>a.cost)&&(pe.set(o,a),fe.push(a))}let me=0;for(;fe.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=fe.pop();if(pe.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,T?.cost??1/0))break;let t=ce(e.id);for(let t of D.get(e.id)??[]){if(!Number.isFinite(ue(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(ce(t.id));r.reverse();let a=yn([e.start.point,...r,t.point],y);if(o&&!kn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return T&&T.cost<=s?T:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%se,c=Math.floor(e.id/se);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=se||a>=oe.length)continue;let o=a*se+n,s=ce(o),c=ue(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(pe.has(d)&&pe.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+de(s),before:e,start:e.start,serial:O++};pe.set(d,f),fe.push(f)}}return T??null}function kn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>mn(f,pn(e,a.labelGap)))||i.some(([e,t])=>U(e,t,pn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>mn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function An(e,t=null){let n=Y(e),r=bn(e),i=V(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=fn(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(qt),...J(e).flatMap(Vn)],s=e.nodes.map(e=>H(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(gn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=kn(e.points,j(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function jn(e,t,n,r,i,a,o,s=0){let c=Y(t),l=j(Et(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Gt(a,o,t,c))||n.some(e=>U(a,o,e))||r.flatMap(q).some(([e,t])=>wn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Mn(e){let t=bn(e),n=[...V(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Nn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=V(t),i=t.nodes.map(e=>H(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=bn(e),c=V(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>pn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(qt),...J(e).flatMap(Vn)].map(e=>pn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||gn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Mn(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+Tn(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||gn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Nn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Mn(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),An({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=V(a).get(e.id);t.label&&S.push(pn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(gn).findIndex(e=>e.id===t.id),r=jn(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=Cn(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=On(i[e],a,[...u,...S],p,s,h,Et(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Mn(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},Pn=e=>e&&typeof e==`object`&&!Array.isArray(e),Fn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),In=e=>e.overviewText!==void 0||e.badges!==void 0||e.overviewTone!==void 0;function Ln(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ne.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{Pn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Fn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!Pn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!Pn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Fn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!Pn(e.position)||!Pn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Fn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!Pn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Rn(e,t=e.size.width){let n=e.overviewTone===`plain`?0:T.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>k(e.label,r*.45-16,T.badge,T.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=k(r.label,a-16,T.badge,T.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=k(e.label,r-(a?a+10:0),T.title,T.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+T.title+t*T.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&k(e.subtitle,1/0,T.body,T.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+T.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=k(t,r,T.body,T.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+T.body+t*T.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let zn=e=>e.frame===`none`?0:T.padding,Bn=(e,t)=>{let n=t-zn(e)*2;return zn(e)+k(e.title,n,T.sectionTitle,T.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+k(t,n,T.body,T.bodyLine).height,0)};function Vn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=zn(e),n=e.position.x+t,r=e.size.width-t*2,i=k(e.title,r,T.sectionTitle,T.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*T.sectionLine,width:k(r,1/0,T.sectionTitle,T.sectionLine).width,height:T.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=k(t,r,T.body,T.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*T.bodyLine,width:k(e,1/0,T.body,T.bodyLine).width,height:T.bodyLine}))),o+=e.height}return a}function Hn(t,{width:n=T.width,gap:r=T.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Rn(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=zn(n),c=i[n.id]??r,p=Bn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,T.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=zn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=T.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,T.margin,h),h+=t.height+Math.max(a[e.id]??r,T.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-T.padding,i=Math.min(...t.map(e=>e.position.y))-k(e.label,n,20,26).height-T.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+T.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+T.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return Xn(o)}function Un(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Rn(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=un(t,r);return r.edges=C(r,Nn(S(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Wn=new WeakMap;function Gn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=Hn(e,{gaps:n,bandGaps:r});return t(a),Wn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??T.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??T.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Kn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),qn=(e,t,n,r,i=``)=>`${Kn(n)}`;function Jn(e,t,n,r){let i=ae(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Rn(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?T.title:T.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>qn(t+e.x+8,n+e.y+3+T.badge+i*T.badgeLine,r,`meta`,`fill:${o.ink};font-size:${T.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Yn(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Bn(t,t.size.width)+zn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-zn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-zn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Vn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Xn(e){return e.edges=C(e,Nn(S(e),{passes:3}).graph),e}function Zn(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return tr(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,contentHeight:m}=Te({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),h=t+c,g=n+Math.max(0,(e.size.height-m)/2)+A.pad,_=h+A.textX,v=g+u.height+(d.height?4:0),y=v+d.height+(f.height?6:0),b=u.lines.map((e,t)=>N(_,g+20+t*u.lineHeight,e,`title`)).join(``),x=d.lines.map((e,t)=>N(_,v+17+t*d.lineHeight,e,`body`)).join(``),S=f.lines.map((e,t)=>N(_,y+14+t*f.lineHeight,e,`meta`)).join(``),C={x:h+A.pad,y:g+(A.titleLine-A.plate)/2},w=t+e.size.width-c-A.pad-p.width-l;return`${Qn(e,t,n,r,i,s)}${$n(e,C.x,C.y,A.plate,a)}${N(w+p.width/2,g+18,p.text,`stereotype`,` text-anchor="middle"`)}${b}${x}${S}`}let Qn=(e,t,n,r,i,a)=>P(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function $n(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:le(e)?i.accent:ce.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${er(e)}`}let er=e=>ce.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function tr(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Te({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>N(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>N(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Qn(e,t,n,r,i,s)}${$n(e,t+15+c,n+13,25,a)}${N(t+47+c,n+29,we(e,o).text,`stereotype`)}${d}${f}`}let nr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],rr=[[.08,0],[1,0],[.92,1],[0,1]];function ir(e,t,n){let{width:r,height:i}=e.size;if(In(e))return F(e,t,n,16);if(e.kind===`external`)return Ne(e,t,n,Me);if(e.kind===`security`)return F(e,t,n,22);if(e.kind===`failure`)return Ne(e,t,n,nr);if(e.kind===`config`)return Ne(e,t,n,rr);if(e.kind===`business`)return F(e,t,n,Math.min(28,i/2));let a=F(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?je(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ar=(e,t,n)=>In(e)?Le(e,t,n,16):e.kind===`external`?ze(e,t,n,Me):e.kind===`security`?Le(e,t,n,22):e.kind===`failure`?ze(e,t,n,nr):e.kind===`config`?ze(e,t,n,rr):e.kind===`business`?Le(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?I(e,t,n,{left:12,right:12,top:2,bottom:2}):I(e,t,n),or=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var sr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>In(e)?Jn(e,t,n,a,r,i):Zn(e,t,n,r,i,a,o,ir,or(e)),outline:ir,anchor:ar,cardLayout:!0,contentInset:or};let cr=.12,lr=(e,t,n)=>e.kind===`decision`?Pe(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*cr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:F(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),ur=(e,t,n)=>e.kind===`decision`?ze(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?ze(e,t,n,[[cr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Le(e,t,n,e.size.height/2):I(e,t,n),dr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*cr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function fr(e,t,n,r,i){let{width:a,height:o}=e.size,s=dr(e),c=Ae(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${P(lr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var pr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:fr,outline:lr,anchor:ur,textArea:dr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?D(t,e.kind):``)};let mr=(e,t,n)=>F(e,t,n,9);function hr(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=de(e),u=M(e.subtitle??D(o,`Entity`),e.size.width-60),d=e.subtitle?E.body:E.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,k(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?N(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${N(t+45,u,M(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${N(t+e.size.width-10,u-1,M(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${P(mr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${N(t+13,n+s*.43,M(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(E.title,s*.38)}px;fill:${a.ink}"`)}${N(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${N(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var gr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:hr,outline:mr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let _r=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function vr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Ne(e,t,n,_r),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...F(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?je(e,t,n):e.kind===`external`?Ne(e,t,n,Me):e.kind===`service`?F(e,t,n,16):F(e,t,n,10)}let yr=(e,t,n)=>e.kind===`device`?I(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?ze(e,t,n,_r):e.kind===`database`?I(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?ze(e,t,n,Me):e.kind===`service`?Le(e,t,n,16):I(e,t,n),br=e=>({container:24,artifact:18,node:20})[e.kind]??0,xr=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Sr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Zn(e,...t,vr,xr(e),br(e)),outline:vr,anchor:yr,cardLayout:!0,contentInset:xr,cardCorner:br};let Cr=(e,t,n)=>F(e,t,n,9);function wr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=de(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>N(t+13,d+6+l/2+E.body*.35+n*l,M(e,m),`member`)).join(``),g=s.map((e,n)=>N(t+13,f+6+l/2+E.body*.35+n*l,M(e,m),`member`)).join(``);return`${P(Cr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?N(t+13,n+24,p,`stereotype`):``}${N(t+13,n+(p?50:E.classHeader/2+7),M(e.label,m),`shape-title`)}${e.subtitle?N(t+13,n+c-10,M(e.subtitle,m),`body`):``}${h}${g}`}var Tr={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:wr,outline:Cr,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?D(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=j(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let Er=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:F(e,t,n,e.kind===`process`?24:10),Dr=e=>({width:e.size.width-32,height:e.size.height-20});function Or(e,t,n,r,i){let a=Dr(e);return`${P(Er(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Ae(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let kr=[sr,pr,We,gr,Sr,Tr,ct,Xe,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Or,outline:Er,textArea:Dr,anchor:(e,t,n)=>e.kind===`process`?Le(e,t,n,24):I(e,t,n)}],Ar=kr.map(e=>e.id);Object.fromEntries(kr.map(e=>[e.id,e.label]));let jr=new Map(kr.map(e=>[e.id,e]));if(jr.size!==kr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>jr.get(e),Mr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Nr=(e,t,n,r=!1)=>t===`architecture`&&In(e)?Rn(e):Te({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),Pr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Nr(n,t,e.meta?.locale).minHeight)},Fr=(e,t)=>Math.ceil(k(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Ir=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Lr(e,t,n=`en`){if(t===`architecture`&&In(e))return{width:300,height:Rn(e,e.size?.width??300).minHeight};let r=X(t),i=Fr(e.label,E.title),a=Fr(e.subtitle,E.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Ir({width:t+50,height:Math.max(80,k(e.label,t,E.title,29).height+5+k(e.subtitle,t,E.body,23.2).height+16)})}if(t===`state`&&Qe.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Qe.filter(t=>e[t]).map(t=>Fr(e[t],E.small)+et)))),n=k(e.label,t-24,E.title,29),r=k(e.subtitle,t-24,E.body,23.2);return Ir({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+$e({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:He({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?He(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Fr(e.name,E.body),n=Fr(e.type,E.body);return Math.max(t+n+74,n/.55)});return Ir({width:Math.max(240,i+26,a+60,...t),height:Math.max(E.erHeader/.4,E.erHeader+e.fields.length*E.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Ir({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Fr(e,E.body)+26)),height:E.classHeader+(e.subtitle?24:0)+(t.length?t.length*E.classRow+13:30)+(n.length?n.length*E.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+we(e,n).width+A.tagGap+t,a,Fr(Se(e),E.small))+A.textX+A.pad,s=r.contentInset?.({...e,size:{width:Math.min(A.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(A.maxWidth,o+2*s)),height:0};return c.height=Te({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Ir(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=k(e.label,t.width,E.title,29),r=k(e.subtitle,t.width,E.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Ir(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Rr=e=>e.members.map(e=>e.kind),zr=(e,t)=>Rr(e).some(e=>t.includes(e)),Br=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Vr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function Hr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Ur(e,t){let n=Vr(e,t.edges);return n.length===1&&e.length>5?Hr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Wr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Gr(e,t){let n=t.layout?.primaryPath??[],r=Vr(e,Wr(t));return r.length===1&&e.length>5?Hr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Kr(e,t){let n=[...e].sort((e,n)=>Br(n,t.edges)-Br(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return Hr(r)}function qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Vr(e,t.edges))}function Jr(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Vr(r,n),o=Vr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>zr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function Yr(e,t){let n=e.filter(e=>zr(e,[`initial`])),r=e.filter(e=>zr(e,[`final`]));return[n,...Vr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Wr(t)),r].filter(e=>e.length)}function Xr(e,t,n=0){let r=e.filter(e=>zr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Kr(i,t)}function Zr(e,t){let n=e.filter(e=>zr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Vr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let Qr=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Ur},flowchart:{structure:`workflow-spine`,arrange:Gr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Kr},deployment:{structure:`runtime-tiers`,arrange:qr},class:{structure:`contract-hierarchy`,arrange:Jr},state:{structure:`lifecycle-branches`,arrange:Yr},usecase:{structure:`actor-system`,arrange:Xr},dataflow:{structure:`process-store`,arrange:Zr}}),$r=e=>Qr[u(e)];function ei(e,t=0){let n=$r(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=Lr(e,i,r.meta.locale)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Oe({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>zr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=Math.max(0,...S.map(e=>j(Et(e,i,r.meta.locale))[b])),w=Math.max(s.nodeGap,Math.min(C+2*o.labelGap,240))+t*24,ee=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+w,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*w,T=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>j(Et(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:T+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+w,0):ee[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),T+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>j(Et(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function ti(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ni(e,t){let n=structuredClone(e),r=n.groups??[],i=new Map(n.edges.map(e=>[e.id,e])),a=new Map;for(let e of[...n.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])a.has(t)||a.set(t,a.size);let o=(n.layout?.participantOrder??[...n.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||(a.get(e.id)??1/0)-(a.get(t.id)??1/0)||(e.ide.id)).map(e=>n.nodes.find(t=>t.id===e)),s=32+t*8,c=12+t*4,l=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,u=(e,t)=>k(l(e,t),f.labelWidth,14,20),p=e=>k(e.body,f.labelWidth,16,24),m=32;for(let e of o)e.size=Lr(e,`sequence`,n.meta.locale),e.position={x:m,y:48},m+=e.size.width+s;xt(n,o);for(let e of n.edges)e.route={messageY:200+e.order*100};let h=V(n),g=wt(n),_=new Set(r.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),v=e=>(e.operands??[]).flatMap((t,n)=>ft(e,t,n,r)).map(e=>i.get(e).order),y=e=>e.edge?e.edge.order:Math.min(1/0,...v(e.group)),b=e=>e.sort((e,t)=>y(e)-y(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),x=e=>(e.operands??[]).flatMap((t,n)=>ft(e,t,n,r)).map(e=>h.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),S=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=r.find(e=>e.id===n.parentId)){t.add(n.id);let e=x(n);if(e.length)return e}return[...h.values()].flatMap(e=>e.points)};for(let e of[...r].sort((e,t)=>mt(t,r)-mt(e,r)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=S(e),n=r.filter(t=>t.parentId===e.id),a=Math.max(ht({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[u(e,t).width,p(t).width])),s=e.operands.flatMap((t,n)=>ft(e,t,n,r)).map(e=>i.get(e).route.messageY),c=Math.min(...s),l=Math.max(...s),d=g.filter(e=>!s.length||e.y<=l&&e.y+e.height>=c).sort((e,t)=>e.x-t.x),f=t.length?Math.min(...t.map(e=>e.x)):o[0].position.x,m=Math.min(f,...d.filter(e=>e.x=f-8).map(e=>e.x))-a-40,h=Math.min(m,...n.map(e=>e.position.x-32)),_=Math.max(h+a+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of d)e.x<_+8&&e.x+e.width>_-56-16&&(_=Math.max(_,e.x+e.width+56));e.position={x:h,y:0},e.size={width:Math.ceil(_-h),height:0}}function C(e,t){let n=h.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+c}function w(e,t){for(let n of b(e))t=n.edge?C(n.edge,t):ee(n.group,t);return t}function ee(e,t){e.position.y=t;let n=t+Math.max(36,ht(e).height+20)+c;for(let[t,a]of e.operands.entries()){n+=u(e,a).height+16,a.body&&(n+=p(a).height+16);let o=r.filter(n=>n.parentId===e.id&&n.parentOperandId===R(a,t));n=w([...a.edgeIds.map(e=>({edge:i.get(e)})),...o.map(e=>({group:e}))],n),n+=c}return e.size.height=n-t+16,t+e.size.height+c}let te=w([...n.edges.filter(e=>!_.has(e.id)).map(e=>({edge:e})),...r.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...o.map(He))+d.labelGap),T=[...n.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...o.map(e=>e.position.x)));for(let e of[...o,...r])e.position.x+=ne;for(let e of n.nodes)e.size.height=te+32-e.position.y;return n}function ri(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Oe(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ii(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*ai(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eH(e,t)),...(e.groups??[]).flatMap(qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>j(Et(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let oi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function si(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function ci(e,t,n){$(e.file,`${t}.file`,n),si(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function fi(e,t){di(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function pi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])si(e.meta?.[t],`meta.${t}`,r);fi(e.meta?.notes,r),e.meta?.locale!==void 0&&!pe.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Ar.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),si(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),li(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(ci(c.source,`${e}.source`,r),c.source.kind!==void 0&&!oi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])di(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:di})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),li(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),si(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),oi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&ci(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>ui(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&ui(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Ln(e,{inputOnly:t,validateAnchor:ci,evidenceKinds:oi})),r.length===0&&r.push(...mi(e)),r.length===0&&r.push(...pt(e)),r.length===0&&r.push(...Ct(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...Xt(e).errors),r}function mi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let hi=e=>({...e.position,...e.size}),gi=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,_i=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function yi(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function bi(e,t={}){let n=pi(e,{inputOnly:!0}),r=n.length?[]:pi(e,{audit:!1}),i=n.length||r.length?null:xi(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw yi(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function xi(e,{strictEdgeIds:i=null}={}){e=S(e);let a=Xt(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,H(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!Pr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=Ut(n.box,t);r+.001U(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)gi(c,hi(e))||f(`group.member-inset`,[i.id,e.id],hi(e),c,[a,hi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&_i(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Ut(a,hi(e))+.001({node:e,probe:sn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=vi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001cn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[hi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Yn(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(hi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Ot(e,a.routes)}}let Si=(e,t)=>e.idt.id);function Ci(e,t=xi(e)){let n=[...t.routes.values()],r=Ot(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=H(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Mr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let wi=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Ei(e,t){if(!ti(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Si(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Di(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Si(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Oi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Di(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return ki(r),r}function ki(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Oe(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ai(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=Ti(u,t),f=[],p=structuredClone(e);o&&ki(p),o&&l&&(l=un(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=Ci(p,xi(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=un(p,e,a??m)),v++;try{if(s){let t=xi(e),n=Ci(e,t);if(!n.errors&&wi(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=un(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Nn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:bi}),r=t.graph,o=Ci(r,xi(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),wi(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Ei(u,n))&&!xi(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Si(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Si))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Ei(u,a)&&!xi(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:Ci(u),after:h,attempts:f};try{bi(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function ji(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ai(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||wi(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n;if(t.overview)n={graph:t.options?.relayout?Gn(t.graph,bi):Un(t.graph,t.reference??t.graph,bi)};else if(t.options?.relayout&&t.graph.meta.diagramType===`sequence`){let r=[];for(let n=0;n<6;n++)try{let i=ni(t.graph,n);i.layout={...i.layout,version:e},bi(i),r.push({graph:i})}catch{}if(r.sort((e,t)=>Ci(e.graph).cost-Ci(t.graph).cost),!r.length)throw Error(`No valid sequence layout`);n=r[0]}else if(t.options?.relayout&&ei(t.graph)){let r=[];for(let n=0;n<4;n++)try{let i=ei(t.graph,n);i.layout={...i.layout,version:e,strategy:`template-${$r(i).structure}-${n}`},r.push(Nn(i,{passes:3,accept:bi}))}catch{}if(r.sort((e,t)=>Ci(e.graph).cost-Ci(t.graph).cost),!r.length)throw Error(`No valid semantic layout`);n=ji(r[0].graph,t.graph,{global:!0,evaluations:60})}else n=Ai(t.options?.relayout?{...t.graph,layout:{...t.graph.layout,version:e}}:t.graph,{...t.options,global:!!t.options?.relayout});self.postMessage({result:{graph:n.graph,movedNodeIds:n.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Yg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Jg],{type:`text/javascript;charset=utf-8`});function Xg(e){let t;try{if(t=Yg&&(self.URL||self.webkitURL).createObjectURL(Yg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Jg),{name:e?.name})}}var Zg=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),Qg=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function $g(e,t,n=`en`){if(t===`architecture`&&bg(e))return{width:300,height:Sg(e,e.size?.width??300).minHeight};let r=$(t),i=Zg(e.label,X.title),a=Zg(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Qg({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Dm.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Dm.filter(t=>e[t]).map(t=>Zg(e[t],X.small)+Am)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return Qg({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+km({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:dm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?dm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Zg(e.name,X.body),n=Zg(e.type,X.body);return Math.max(t+n+74,n/.55)});return Qg({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Qg({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Zg(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+Sp(e,n).width+yp.tagGap+t,a,Zg(bp(e),X.small))+yp.textX+yp.pad,s=r.contentInset?.({...e,size:{width:Math.min(yp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(yp.maxWidth,o+2*s)),height:0};return c.height=Cp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Qg(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Qg(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var e_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function t_(e){return e.layout?.tier?e_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var n_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),r_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function i_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function a_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function o_(e,t,n){i_(e.file,`${t}.file`,n),a_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function u_(e,t){l_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function d_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!r_(e))return[`graph must be an object`];r_(e.meta)||r.push(`meta must be an object`),i_(e.meta?.title,`meta.title`,r),i_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&i_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])a_(e.meta?.[t],`meta.${t}`,r);u_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Zm(e);Ym.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!r_(c)){r.push(`${e} must be an object`);continue}i_(c?.id,`${e}.id`,r),i_(c?.label,`${e}.label`,r),a_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&i_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),s_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!r_(c.source)?r.push(`${e}.source must be an object`):c.source&&(o_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!n_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])l_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!r_(n)){r.push(`${i} must be an object`);continue}i_(n.name,`${i}.name`,r),i_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:i_,validateStringArray:l_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!r_(s)){r.push(`${e} must be an object`);continue}i_(s?.id,`${e}.id`,r),i_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),s_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!r_(o)){r.push(`${e} must be an object`);continue}i_(o?.id,`${e}.id`,r),a_(o.label,`${e}.label`,r),o.module!==void 0&&i_(o.module,`${e}.module`,r),i_(o?.source,`${e}.source`,r),i_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),n_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!r_(o.site)?r.push(`${e}.site must be an object`):o.site&&o_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>c_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&c_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:i_,sequenceOrders:l})}return r.length===0&&r.push(...xg(e,{inputOnly:t,validateAnchor:o_,evidenceKinds:n_})),r.length===0&&r.push(...f_(e)),r.length===0&&r.push(...fh(e)),r.length===0&&r.push(...Th(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...ig(e).errors),r}function f_(e){let t=[],n=Zm(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(r_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!e_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${e_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),r_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!r_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!jf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${jf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),r_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var p_=e=>({...e.position,...e.size}),m_=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,h_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function __(e,t,n,r=[]){return r.length||(r=(String(n).includes(` +`}function Xp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return em(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+xp.pad,v=g+xp.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*xp.chipLine;return`${Q(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>Q(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>Q(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>Q(v,b+14+t*f.lineHeight,e,`meta`)).join(``),E={x:g+xp.pad,y:_+(xp.titleLine-xp.plate)/2},D=t+e.size.width-c-xp.pad-p.width-l;return`${Zp(e,t,n,r,i,s)}${Qp(e,E.x,E.y,xp.plate,a)}${Q(D+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}var Zp=(e,t,n,r,i,a)=>Ip(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Qp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:Yf(e)?i.accent:Jf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${$p(e)}`}var $p=e=>Jf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function em(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Zp(e,t,n,r,i,s)}${Qp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,wp(e,o).text,`stereotype`)}${d}${f}`}var tm=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],nm=[[.08,0],[1,0],[.92,1],[0,1]];function rm(e,t,n){let{width:r,height:i}=e.size;if(Cg(e))return Lp(e,t,n,16);if(e.kind===`external`)return Bp(e,t,n,zp);if(e.kind===`security`)return Lp(e,t,n,22);if(e.kind===`failure`)return Bp(e,t,n,tm);if(e.kind===`config`)return Bp(e,t,n,nm);if(e.kind===`business`)return Lp(e,t,n,Math.min(28,i/2));let a=Lp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var im=(e,t,n)=>Cg(e)?Gp(e,t,n,16):e.kind===`external`?qp(e,t,n,zp):e.kind===`security`?Gp(e,t,n,22):e.kind===`failure`?qp(e,t,n,tm):e.kind===`config`?qp(e,t,n,nm):e.kind===`business`?Gp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):Wp(e,t,n),am=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,om={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Cg(e)?Mg(e,t,n,a,r,i):Xp(e,t,n,r,i,a,o,rm,am(e)),outline:rm,anchor:im,cardLayout:!0,contentInset:am},sm=.12,cm=(e,t,n)=>e.kind===`decision`?Vp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*sm},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Lp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),lm=(e,t,n)=>e.kind===`decision`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?qp(e,t,n,[[sm,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Gp(e,t,n,e.size.height/2):Wp(e,t,n),um=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*sm+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function dm(e,t,n,r,i){let{width:a,height:o}=e.size,s=um(e),c=Fp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Ip(cm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var fm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:dm,outline:cm,anchor:lm,textArea:um,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},pm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n):Lp(e,t,n,7,mm(e));function mm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function hm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=mm(e),u=Ip(pm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,up[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Np([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var gm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:hm,outline:pm,sequence:!0,selectionHeight:mm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},_m=(e,t,n)=>Lp(e,t,n,9);function vm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=dp(e),u=Pp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,Pp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,Pp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Ip(_m(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,Pp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var ym={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:vm,outline:_m,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},bm=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function xm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Bp(e,t,n,bm),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Lp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`external`?Bp(e,t,n,zp):e.kind===`service`?Lp(e,t,n,16):Lp(e,t,n,10)}var Sm=(e,t,n)=>e.kind===`device`?Wp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?qp(e,t,n,bm):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?qp(e,t,n,zp):e.kind===`service`?Gp(e,t,n,16):Wp(e,t,n),Cm=e=>({container:24,artifact:18,node:20})[e.kind]??0,wm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Tm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Xp(e,...t,xm,wm(e),Cm(e)),outline:xm,anchor:Sm,cardLayout:!0,contentInset:wm,cardCorner:Cm},Em=(e,t,n)=>Lp(e,t,n,9);function Dm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=dp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``);return`${Ip(Em(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),Pp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,Pp(e.subtitle,m),`body`):``}${h}${g}`}var Om={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:Dm,outline:Em,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=kp(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},km=e=>e.subtitle?14:e.size.width/2,Am=[`entry`,`do`,`exit`],jm={side:16,pad:8,line:20,keyWidth:64};function Mm(e){let t=e.kind===`state`?Am.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*jm.side-jm.keyWidth,X.small,jm.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*jm.line+2*jm.pad:0}}var Nm=2*jm.side+jm.keyWidth,Pm=e=>{let{height:t}=Mm(e);return t?{x:jm.side,y:e.size.height-t,width:e.size.width-2*jm.side,height:t}:null},Fm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+km(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Vp(e,t,n):Lp(e,t,n,12),Im=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=km(e)-e.size.width/2;return Kp({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Wp(e,t,n)},Lm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=Mm(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Rm(e,t,n,r,i){let{rows:a,height:o}=Mm(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+jm.pad+c++*jm.line+15;return(r?``:Q(t+jm.side,a,`${e.key} /`,`field-key`))+Q(t+jm.side+jm.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function zm(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Lm(e),o=e.kind===`final`;return`${Ip(Fm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Fp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Lm(e),l=n+(e.size.height-Mm(e).height)/2;return`${Ip(Fm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,l,e.label,c.width,c.height,e.subtitle)}${Rm(e,t,n,i,a)}`}var Bm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Vm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:zm,outline:Fm,anchor:Im,textArea:Lm,activityArea:Pm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Bm(e).map(e=>e.text).join(` `),edgeLabelParts:Bm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Am)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},Hm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Um=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Wm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n+Hm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Gm=(e,t,n)=>e.kind===`actor`?Jp(e,t,n,Hm(e)):Kp(e,t,n);function Km(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+Hm(e)+98,Pp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+Hm(e)+122,Pp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Um(e);return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var qm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Km,outline:Wm,anchor:Gm,textArea:Um,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Jm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Lp(e,t,n,e.kind===`process`?24:10),Ym=e=>({width:e.size.width-32,height:e.size.height-20});function Xm(e,t,n,r,i){let a=Ym(e);return`${Ip(Jm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Zm=[om,fm,gm,ym,Tm,Om,Vm,qm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Xm,outline:Jm,textArea:Ym,anchor:(e,t,n)=>e.kind===`process`?Gp(e,t,n,24):Wp(e,t,n)}],Qm=Zm.map(e=>e.id);Object.fromEntries(Zm.map(e=>[e.id,e.label]));var $m=new Map(Zm.map(e=>[e.id,e]));if($m.size!==Zm.length)throw Error(`Duplicate diagram type`);var eh=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>$m.get(e),th=(e,t,n,r=!1)=>t===`architecture`&&Cg(e)?Tg(e):Tp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),nh=e=>{let t=eh(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=th(n,t,e.meta?.locale).minHeight)},rh=(e,t)=>!($(t).undirected??[]).includes(e.kind),ih=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),ah=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),oh=(e,t)=>({start:null,end:rh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),sh=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ch=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),lh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var uh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,dh=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),fh=(e,t)=>e?.id??String(t);function ph(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(fh(i,t))}`);return n}function mh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===fh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>mh(e,t,n,r,a)))]}function hh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>fh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=fh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=mh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function gh(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function _h(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>gh(n,t)-gh(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var vh=e=>Z(e.label,Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function yh(e,t){let n={...e.position,...e.size},r=vh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>uh(e,t,4)))}function bh(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...dh(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>uh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:fh(null,0)}]}}function xh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;uh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=yh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=bh(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===fh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=mh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...dh(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Df.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1mh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...dh(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...dh(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${fh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Df.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>uh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=fh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${fh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function Sh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function Ch(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wh(e,t,n=Ch(e),r=ph(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Th=140,Eh=54,Dh=(e,t)=>(e.route?.messageY??Th+e.order*Eh)+(t===`receive`&&e.source===e.target?30:0);function Oh(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Dh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ph(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Dh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Dh(n.get(i.end.edgeId),i.end.at)-l}})}function Ah(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var jh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Mh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Nh(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ph(e,t=Yh(e)){e=Tf(e);let n=[...bg(e),...e.groups??[],...e.nodes,...kh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Nh(n.sourceCardinality,e.points[0],e.points[1]),Nh(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Fh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=jh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Ih(e,t,n=Ef.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Lh(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Rh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function zh(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Bh(e,t,n,r){let i={clearance:-1,length:-1,point:zh(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Vh(e,t){let n=jh(e),r=jh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Hh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?tg(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Ih(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Rh(f,e);return Rh(f,Ih(t,r,a)),f.push(t),Lh(f)}function Wh(e,t,n,r,i,a=Ef.endpoint,o=`architecture`){let s=Fh(e,n.sourceSide,r,o),c=Fh(t,n.targetSide,i,o),l=Ih(s,n.sourceSide,a),u=Ih(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Lh([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Lh([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Gh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Kh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var qh=(e,t=0,n=0)=>e.curved&&Kh(e,t,n)||Gh(e.points,t,n);function Jh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Dh(e,`send`),u=Dh(e,`receive`),d=Ah(o,t.id,e,`send`,l,s.get(e.id)),f=Ah(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||jh(t).x<=jh(n).x,m=d?d.x+(p?d.width:0):jh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):jh(n).x,g=wh(a,e,c,s),_=Dp(g,t.id===n.id?Df.labelWidth:Math.min(Df.labelWidth,Math.max(1,Math.abs(h-m)-32-12))),v={width:_.width,height:_.height};if(t.id===n.id){let t=48+r*Ef.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Uh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:_.lines,labelSize:v,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+v.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Uh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:_.lines,labelSize:v,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-v.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Yh(e){e=Tf(e);let t=eh(e),n=$(t).endpointStub??Ef.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Vh(t,n)}}),a=t===`sequence`?{graph:e,executions:kh(e),scopes:ph(e),pairs:Ch(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?jh(i).y:jh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*Ef.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Zh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,mm(e))}:{...e.position,...e.size}}function Qh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function $h(e,t,n,r){let i=tg(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=jh(t),o=Fh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function eg(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&eg(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=jh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Fh(n,`left`,o,r).x,c=Fh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Fh(n,`top`,o,r).y,c=Fh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function sg(e){e=Tf(e);let t=eh(e),n=[],r=Yh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...kh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightuh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!nh(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:xp.minHeight))continue;let{minHeight:r}=t===`architecture`&&Cg(n)?Tg(n):Tp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;eEf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${Ef.endpoint}px`);let f=og(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!$h(i.points[0],a,i.sourceSide,t)||!$h(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Ih(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(jh(a).x-jh(o).x),t=Math.max(160,i.labelBox.width+32);eXh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),rg(t).some(([e,t])=>eg(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Xh(i.labelBox,tg(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=rg(r);for(let i=1;ieg(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ag(a,o,e,t)>Ef.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var cg=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),lg=(e,t,n)=>Math.max(t,Math.min(n,e)),ug=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=lg(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function dg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(ug(e,n,r),ug(t,n,r),ug(n,e,t),ug(r,e,t))}function fg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function pg(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function mg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:lg(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:lg((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>ug({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>dg(e,t,r,n[(i+1)%n.length])))}var gg=new WeakMap;function _g(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=gg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Hm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,ug({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>dg(e,a,t,n)),...i.map(t=>fg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>mg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>hg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,ug({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>pg(e,t,c);else{let n=s===`rect`?c:tg(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,fg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),fg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},gg.set(e,{signature:n,probe:l}),l}function vg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return rg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function yg(e,t,n=[]){let r=new Set(n),i=eh(t),a=cg(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Zh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Yh(e),d=kf($(i)).labelGap,f=[...o.map(e=>Zh(e,i)),...l.flatMap(ig)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>eg(r,e,t))||l.some(n=>vg(r,e,n).distanceeg(r,e,t)))}))&&r.add(n.id)}return r}var bg=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},xg=e=>e&&typeof e==`object`&&!Array.isArray(e),Sg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Cg=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function wg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!zf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{xg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Sg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!xg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!xg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Sg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!xg(e.position)||!xg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Sg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!xg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Tg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Eg=e=>e.frame===`none`?0:Y.padding,Dg=(e,t)=>{let n=t-Eg(e)*2;return Eg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Og(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Eg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function kg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=bg(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Ag=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),jg=(e,t,n,r,i=``)=>`${Ag(n)}`;function Mg(e,t,n,r){let i=Hf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Tg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>jg(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>jg(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ng(e,t,n=0,r=0){let i=Hf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Eg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>jg(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>jg(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function Pg(e,t=new Map){if(!ff(e))return[];let n=[],r=bg(e);for(let t of r){let r=Dg(t,t.size.width)+Eg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Eg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Eg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Og(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Fg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=ip(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Ip(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` +`);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}function zg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Bg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(zg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Vg({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` +`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function ee(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function w(e){if(!x(e))return{...e,edges:ee(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:ee(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function T(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=w(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,Math.abs(_-g)-32-12))),b={width:y.width,height:y.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:y.lines,labelSize:b,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+b.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:y.lines,labelSize:b,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-b.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=w(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=w(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,ee=Math.max(...b.map(e=>e.x+e.width))+x,w=Math.min(...b.map(e=>e.y))-S,T=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,ee].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[w,T].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),ee=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},ee(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=T(r,Rn(w(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=T(e,Rn(w(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),ee=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),w=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),T={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,T.x,T.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${ee}${w}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],ee=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),w=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),T=Math.max(s.nodeGap,Math.min(ee+2*o.labelGap,240),w)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+T,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*T,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+T,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t){let n=structuredClone(e),r=n.groups??[],i=new Map(n.edges.map(e=>[e.id,e])),a=new Map;for(let e of[...n.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])a.has(t)||a.set(t,a.size);let o=(n.layout?.participantOrder??[...n.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||(a.get(e.id)??1/0)-(a.get(t.id)??1/0)||(e.ide.id)).map(e=>n.nodes.find(t=>t.id===e)),s=32+t*8,c=12+t*4,l=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,u=(e,t)=>A(l(e,t),f.labelWidth,14,20),p=e=>A(e.body,f.labelWidth,16,24),m=32;for(let e of o)e.size=Hr(e,`sequence`,n.meta.locale),e.position={x:m,y:48},m+=e.size.width+s;Tt(n,o);for(let e of n.edges)e.route={messageY:200+e.order*100};let h=H(n),g=Ot(n),_=new Set(r.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),v=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).order),y=e=>e.edge?e.edge.order:Math.min(1/0,...v(e.group)),b=e=>e.sort((e,t)=>y(e)-y(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>h.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),S=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=r.find(e=>e.id===n.parentId)){t.add(n.id);let e=x(n);if(e.length)return e}return[...h.values()].flatMap(e=>e.points)};for(let e of[...r].sort((e,t)=>vt(t,r)-vt(e,r)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=S(e),n=r.filter(t=>t.parentId===e.id),a=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[u(e,t).width,p(t).width])),s=e.operands.flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).route.messageY),c=Math.min(...s),l=Math.max(...s),d=g.filter(e=>!s.length||e.y<=l&&e.y+e.height>=c).sort((e,t)=>e.x-t.x),f=t.length?Math.min(...t.map(e=>e.x)):o[0].position.x,m=Math.min(f,...d.filter(e=>e.x=f-8).map(e=>e.x))-a-40,h=Math.min(m,...n.map(e=>e.position.x-32)),_=Math.max(h+a+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of d)e.x<_+8&&e.x+e.width>_-56-16&&(_=Math.max(_,e.x+e.width+56));e.position={x:h,y:0},e.size={width:Math.ceil(_-h),height:0}}function C(e,t){let n=h.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+c}function ee(e,t){for(let n of b(e))t=n.edge?C(n.edge,t):w(n.group,t);return t}function w(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+c;for(let[t,a]of e.operands.entries()){n+=u(e,a).height+16,a.body&&(n+=p(a).height+16);let o=r.filter(n=>n.parentId===e.id&&n.parentOperandId===z(a,t));n=ee([...a.edgeIds.map(e=>({edge:i.get(e)})),...o.map(e=>({group:e}))],n),n+=c}return e.size.height=n-t+16,t+e.size.height+c}let T=ee([...n.edges.filter(e=>!_.has(e.id)).map(e=>({edge:e})),...r.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...o.map(Ke))+d.labelGap),E=[...n.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...o.map(e=>e.position.x)));for(let e of[...o,...r])e.position.x+=te;for(let e of n.nodes)e.size.height=T+32-e.position.y;return n}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=w(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:w(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` - `)?String(n).split(` -- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(..._g(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Zm(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function v_(e,t={}){let n=d_(e,{inputOnly:!0}),r=n.length?[]:d_(e,{audit:!1}),i=n.length||r.length?null:y_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw __(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` -- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function y_(e,{strictEdgeIds:t=null}={}){e=Cf(e);let n=ig(e),r=Zm(e),i=$(r),a=ff(e)?{...Df(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:Df(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Jh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Mf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(oh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(t_(t)>=t_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!$m(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;tZh(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)m_(d,p_(e))||s(`group.member-inset`,[i.id,e.id],p_(e),d,[o,p_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&h_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Yh(o,p_(e))+.001({node:e,probe:mg(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=g_(l),d=ih(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001hg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[p_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of jg(e,n.routes)){let n=_g(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(p_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:jh(e,n.routes)}}function b_(e){return function(){return e}}var x_=1664525,S_=1013904223,C_=4294967296;function w_(){let e=1;return()=>(e=(x_*e+S_)%C_)/C_}var T_=10,E_=Math.PI*(3-Math.sqrt(5));function D_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=w_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function O_(e){var t=b_(.1),n,r,i;typeof e!=`function`&&(e=b_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),j_=e=>e.members.map(e=>e.kind),M_=(e,t)=>j_(e).some(e=>t.includes(e)),N_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function P_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(A_))}function F_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function I_(e,t){let n=P_(e,t.edges);return n.length===1&&e.length>5?F_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||A_(e,t)))}function L_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(A_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(A_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function R_(e,t){let n=t.layout?.primaryPath??[],r=P_(e,L_(t));return r.length===1&&e.length>5?F_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||A_(e,t)}))}function z_(e,t){let n=[...e].sort((e,n)=>N_(n,t.edges)-N_(e,t.edges)||A_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return F_(r)}function B_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(t_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>P_(e,t.edges))}function V_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=P_(r,n),o=P_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>M_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function H_(e,t){let n=e.filter(e=>M_(e,[`initial`])),r=e.filter(e=>M_(e,[`final`]));return[n,...P_(e.filter(e=>!n.includes(e)&&!r.includes(e)),L_(t)),r].filter(e=>e.length)}function U_(e,t,n=0){let r=e.filter(e=>M_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(A_),i.sort(A_)].filter(e=>e.length):n>=2?i.sort(A_).map(e=>[e]):z_(i,t)}function W_(e,t){let n=e.filter(e=>M_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=P_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(A_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:I_},flowchart:{structure:`workflow-spine`,arrange:R_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:z_},deployment:{structure:`runtime-tiers`,arrange:B_},class:{structure:`contract-hierarchy`,arrange:V_},state:{structure:`lifecycle-branches`,arrange:H_},usecase:{structure:`actor-system`,arrange:U_},dataflow:{structure:`process-store`,arrange:W_}});function G_(e,t){if(Zm(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var K_=156,q_=160,J_=(e,t,n)=>Math.max(t,Math.min(n,e));function Y_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function X_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function Z_(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-K_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+K_),minimumY:Math.max(t.position.y+Dp(t).height+r.groupHeadingGap+a,s-(n?0:K_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:K_))}}function Q_(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function $_(e,t=null){if(!t)try{return v_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=Df(n),a=Y_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=Z_(t,X_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=D_(o).velocityDecay(.42).force(`anchor-x`,O_(e=>e.anchorX).strength(.16)).force(`anchor-y`,k_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,Q_(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:J_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-K_),e.position.x+K_),y:r?e.position.y:J_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-K_),e.position.y+K_)};return t.bounds&&(n.x=J_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=J_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!G_(e,d))throw Error(`Arrange would invert template bands`);v_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var ev=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function tv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;ev(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function rv(e,t,n){let r=nv(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function iv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function av(e,t,n){let r=Math.min(2,Math.max(Of,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var ov=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(qf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]);function sv(e,t,n,r=Of,i=kf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var cv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,lv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function uv(e,t){if(!cv.test(e))throw Error(`page has no graph-data element`);return e.replace(cv,(e,n,r,i)=>`${n}${lv(t)}${i}`)}function dv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function fv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function pv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function mv(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function hv(e,t,n){let r=Zm(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=i.cardLayout?Qm(a,r,e.meta.locale,n).minHeight-a.size.height:0;if(o<=0)return new Map;let{groupInset:s,groupHeadingGap:c}=Df(i),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-o*e)},size:{width:a.size.width,height:a.size.height+o}},r=new Map([[t,n]]);for(let e=l.get(a.groupId),t=0;e&&t{try{return v_(mv(e,t)),!0}catch{return!1}},f=[.5,1,0].map(u);return f.find(d)??f[0]}function gv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=Zm(e),[o,s,c]=Ed(Wg(e,a)),[l,u]=Dd(Gg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:tv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>fv(_,o,l),[_,o,l]),x=e=>{v(e),s(Wg(e,a)),u(Gg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new Xg,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...gg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:__(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=_g(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(Eg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(pv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return v_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return v_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=_g(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=mv(i,hv(i,e,!$m(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!$m(o)||![`architecture`,`deployment`].includes(a)){let e=$g(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=jh(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&sv(a,ov(e),nv(i,o,s))||lo(a,i.clientWidth,i.clientHeight,.08,2,rv(i,o,s));return g(c,{duration:n,ease:tv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??_g(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:tv});return}let i=p.current;if(!i)return;let o=nv(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=av(Jh(r,a),o,m());g(s,{duration:t?0:420,ease:tv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(Wg(r,a)),u(Gg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=$_(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function _v(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function vv(e,t){return e.map(e=>({node:e,rank:_v(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function yv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(qf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,..._g(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?vv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function bv(e,t,n,r,i,a){let o=Zm(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Kh(u),[u]),v=(0,y.useMemo)(()=>bh(u),[u]),b=(0,y.useMemo)(()=>Eh(u),[u]),x=(0,y.useMemo)(()=>ep(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?vh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:rp(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&_v(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=th(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=ip(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:nh(o,i),labelSurface:e&&n.label?mh(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function xv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Sv(e,t,n,r,i,a){let{end:o}=rh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Kf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Cv(e,t){let{start:n}=rh(e,t);return n?` marker-start="url(#${n})"`:``}function wv(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=jp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Ap(e.label)}${kp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):Op(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function Tv(e,t,n,r,i,a,o,s,c,l,u){let d=ip(e,o,a,s,c,l),f=th(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Ah(e.sourceCardinality,t.points[0],t.points[1]),Ah(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:nh(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Ev={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function Dv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Ev.indent,X.body,Ev.line)),o=r+Ev.top+Ev.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Ev.indent,t+r*Ev.line,e,`body`)).join(``);return o+=e.length*Ev.line+Ev.gap,r}).join(``);return{height:o-r+Ev.bottom,svg:`${Q(n,r+Ev.top,bf(t,`Key points`),`group`)}${s}`}}function Ov(e,t=`light`,n){v_(e),e=Cf(e);let r=Wf[t]??Wf.light;n??=Zf([e],r);let i=ep(e.groups??[],r),a=Zm(e),o=Kh(e),s=bh(e),c=Eh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=jh(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?Dv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?vh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>ph(t,e.groups??[])-ph(n,e.groups??[])).map(e=>wv(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?yh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=_g(e).map(e=>Ag(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>yh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>Tv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?mh(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!$m(e),D=e.nodes.map(t=>Mg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:rp(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${If}-->\n${Ap(e.meta.title)}${Ap(a)} diagram for ${Ap(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Ym.join(`|`)}))?\\.svg$`);function kv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=Zf(n,Wf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${Zm(e)}.svg`:`diagram.svg`,svg:Ov(e,`light`,r)}))}function Av(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function jv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Mv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=uv(await(await s.getFile()).text(),e),l;try{l=kv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(jv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Nv(e,t){t=Cf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw __(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of _g(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=Eh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?vh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Dp(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Ah(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(rh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Jh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw __(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:Zm(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Pv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));jv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function Fv(e,t,n,r,i){e=structuredClone(e),i&&=Qf(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Ov(e,t,i),s=`${Av(e.meta.title)}.${n}`;await Nv(o,e),n===`svg`?jv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Pv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Iv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Wf[t],p=gv(e,s,d,i),[m,h]=o,g=m&&!s,_=xv(d,()=>p.readGraph(p.currentGraph,0)),v=yv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=bv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await Fv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Mv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:Zm(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:Sf(e).some(t=>eh(t,Zm(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Lv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Rv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Kh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Jh(d,r):f?.labelBox;if(!p)return;let m=iv(p,nv(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:tv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:tv})},[e,r,n,t,i,a,o])}var zv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Bv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:zv[e]})}function Vv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0||e.badges!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` +- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function x_(e,t={}){let n=m_(e,{inputOnly:!0}),r=n.length?[]:m_(e,{audit:!1}),i=n.length||r.length?null:S_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw b_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` +- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function S_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(i_(t)>=i_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)__(d,g_(e))||s(`group.member-inset`,[i.id,e.id],g_(e),d,[o,g_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&v_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,g_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=y_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[g_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(g_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function C_(e){return function(){return e}}var w_=1664525,T_=1013904223,E_=4294967296;function D_(){let e=1;return()=>(e=(w_*e+T_)%E_)/E_}var O_=10,k_=Math.PI*(3-Math.sqrt(5));function A_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=D_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function j_(e){var t=C_(.1),n,r,i;typeof e!=`function`&&(e=C_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),P_=e=>e.members.map(e=>e.kind),F_=(e,t)=>P_(e).some(e=>t.includes(e)),I_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function L_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(N_))}function R_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function z_(e,t){let n=L_(e,t.edges);return n.length===1&&e.length>5?R_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||N_(e,t)))}function B_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(N_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(N_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function V_(e,t){let n=t.layout?.primaryPath??[],r=L_(e,B_(t));return r.length===1&&e.length>5?R_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||N_(e,t)}))}function H_(e,t){let n=[...e].sort((e,n)=>I_(n,t.edges)-I_(e,t.edges)||N_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return R_(r)}function U_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(i_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>L_(e,t.edges))}function W_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=L_(r,n),o=L_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>F_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function G_(e,t){let n=e.filter(e=>F_(e,[`initial`])),r=e.filter(e=>F_(e,[`final`]));return[n,...L_(e.filter(e=>!n.includes(e)&&!r.includes(e)),B_(t)),r].filter(e=>e.length)}function K_(e,t,n=0){let r=e.filter(e=>F_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(N_),i.sort(N_)].filter(e=>e.length):n>=2?i.sort(N_).map(e=>[e]):H_(i,t)}function q_(e,t){let n=e.filter(e=>F_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=L_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(N_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:z_},flowchart:{structure:`workflow-spine`,arrange:V_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:H_},deployment:{structure:`runtime-tiers`,arrange:U_},class:{structure:`contract-hierarchy`,arrange:W_},state:{structure:`lifecycle-branches`,arrange:G_},usecase:{structure:`actor-system`,arrange:K_},dataflow:{structure:`process-store`,arrange:q_}});function J_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Y_=156,X_=160,Z_=(e,t,n)=>Math.max(t,Math.min(n,e));function Q_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function $_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function ev(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Y_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Y_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Y_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Y_))}}function tv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function nv(e,t=null){if(!t)try{return x_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=Q_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=ev(t,$_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=A_(o).velocityDecay(.42).force(`anchor-x`,j_(e=>e.anchorX).strength(.16)).force(`anchor-y`,M_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,tv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:Z_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Y_),e.position.x+Y_),y:r?e.position.y:Z_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Y_),e.position.y+Y_)};return t.bounds&&(n.x=Z_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=Z_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!J_(e,d))throw Error(`Arrange would invert template bands`);x_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var rv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function iv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;rv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function ov(e,t,n){let r=av(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function sv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function cv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var lv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]);function uv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var dv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,fv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function pv(e,t){if(!dv.test(e))throw Error(`page has no graph-data element`);return e.replace(dv,(e,n,r,i)=>`${n}${fv(t)}${i}`)}function mv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function hv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function gv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function _v(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function vv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return x_(_v(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function yv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(qg(e,a)),[l,u]=Dd(Jg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:iv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>hv(_,o,l),[_,o,l]),x=e=>{v(e),s(qg(e,a)),u(Jg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new $g,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:b_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(gv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return x_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return x_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=_v(i,vv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=n_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&uv(a,lv(e),av(i,o,s))||lo(a,i.clientWidth,i.clientHeight,.08,2,ov(i,o,s));return g(c,{duration:n,ease:iv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:iv});return}let i=p.current;if(!i)return;let o=av(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=cv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:iv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(qg(r,a)),u(Jg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=nv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function bv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function xv(e,t){return e.map(e=>({node:e,rank:bv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Sv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?xv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function Cv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&bv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function wv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Tv(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Ev(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Dv(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function Ov(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var kv={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function Av(e,t,n,r,i){let a=e.map(e=>Z(e,i-kv.indent,X.body,kv.line)),o=r+kv.top+kv.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+kv.indent,t+r*kv.line,e,`body`)).join(``);return o+=e.length*kv.line+kv.gap,r}).join(``);return{height:o-r+kv.bottom,svg:`${Q(n,r+kv.top,bf(t,`Key points`),`group`)}${s}`}}function jv(e,t=`light`,n){x_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?Av(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Dv(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>Ov(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Mv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:jv(e,`light`,r)}))}function Nv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Pv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Fv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=pv(await(await s.getFile()).text(),e),l;try{l=Mv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Pv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Iv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw b_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw b_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Lv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Pv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function Rv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=jv(e,t,i),s=`${Nv(e.meta.title)}.${n}`;await Iv(o,e),n===`svg`?Pv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Lv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function zv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=yv(e,s,d,i),[m,h]=o,g=m&&!s,_=wv(d,()=>p.readGraph(p.currentGraph,0)),v=Sv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=Cv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await Rv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Fv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Bv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Vv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=sv(p,av(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:iv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:iv})},[e,r,n,t,i,a,o])}var Hv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Uv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Hv[e]})}function Wv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` `),badges:structuredClone(e?.badges??[]),error:``,returnFocus:t});(0,y.useEffect)(()=>{u.current++,o(),p()},[c]);let m=e=>f(t=>({...t,...e}));return{...d,section:!!e?.section,overview:l,set:m,cancel:()=>{u.current++,o(),p(!0)},begin:()=>m({editing:!0,returnFocus:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` -`),badges:structuredClone(e?.badges??[]),error:``}),save:async a=>{if(a.preventDefault(),d.pending)return;let o=d.label.trim();if(!o){m({error:bf(i,`Name is required`)});return}if(d.badges.some(e=>!e.label.trim())){m({error:bf(i,`Name is required`)});return}let s=++u.current;m({pending:!0});let c=await(t?r(t.id,o):n(e.id,o,d.subtitle.trim(),l?{overviewText:d.overviewText.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),...e.section?{}:{badges:d.badges}}:{}));if(u.current===s){if(m({pending:!1}),c){m({error:c});return}m({editing:!1,error:``})}}}}function Hv({editor:e,relation:t,locked:n,locale:r}){let i=e=>bf(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&!e.section&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),!t&&e.overview&&(0,x.jsxs)(`label`,{children:[i(`Overview text`),(0,x.jsx)(`textarea`,{disabled:e.pending,"aria-label":i(`Overview text`),value:e.overviewText,onChange:t=>e.set({overviewText:t.target.value,error:``})})]}),!t&&e.overview&&!e.section&&(0,x.jsxs)(`fieldset`,{disabled:e.pending,children:[(0,x.jsx)(`legend`,{children:i(`Badges`)}),e.badges.map((t,n)=>{let r=t=>e.set({badges:e.badges.map((e,r)=>r===n?{...e,...t}:e)});return(0,x.jsxs)(`div`,{className:`badge-editor`,children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{"aria-label":`${i(`Badges`)} ${n+1}`,value:t.label,onChange:e=>{let{source:n,...i}=t;r({...i,source:void 0,label:e.target.value,evidence:`document`})}})]}),(0,x.jsxs)(`label`,{children:[i(`Badge type`),(0,x.jsx)(`select`,{value:t.role,onChange:e=>r({role:e.target.value}),children:[`status`,`version`,`requirement`].map(e=>(0,x.jsx)(`option`,{value:e,children:i({status:`Status`,version:`Version`,requirement:`Requirement`}[e])},e))})]}),(0,x.jsxs)(`label`,{children:[i(`Evidence`),(0,x.jsx)(`select`,{value:t.evidence,onChange:e=>r({evidence:e.target.value}),children:[`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`].map(e=>(0,x.jsx)(`option`,{value:e,children:i(op[e]??e)},e))})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:e.badges.filter((e,t)=>t!==n)}),children:i(`Remove badge`)})]},n)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:[...e.badges,{label:``,role:`status`,evidence:`document`}]}),children:i(`Add badge`)})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var Uv=292,Wv=232,Gv=14;function Kv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>bf(c,e,t),_=!!t,v=_?(Kh(d).get(t.id)?.label??kh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(Wv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??Wv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Jh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=nv(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Gv,y:N.top},{side:`left`,x:N.left-Gv-Uv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Gv},{side:`above`,x:N.left,y:N.top-Gv-C}],F=e=>e.x>=P.left&&e.x+Uv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Jh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Kh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...ch(e)]),n=Eh(d);for(let r of d.groups??[]){let i=vh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+Uv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-Uv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?sp(e.source):_&&t.site?sp(t.site):null,ae=_?ip(t,r,o,s,n,bh(d).get(t.id)):np(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:Uv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(Bv,{name:`close`})}),u.editing?(0,x.jsx)(Hv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(cp[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(op[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(Bv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(Hv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(Bv,{name:`arrowRight`})]})]})]})]})}var qv=[`system`,`light`,`dark`],Jv={system:`Follow system`,light:`Light`,dark:`Dark`};function Yv(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function Xv({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>bf(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,onOverviewKeyDown:ie,layoutPending:ae,cancelLayout:oe,updateNodeText:se,updateEdgeText:ce,readGraph:le,focusDiagram:ue,nudgeLayout:de,visibleNodes:fe,visibleEdges:pe,reset:me,exportDiagram:he,saveGraph:ge,exportStatus:_e,layoutProblem:ve,layoutWarnings:ye,focusProblem:be,boardRef:xe,fullscreenButtonRef:Se,isFullscreen:Ce,fullscreenPending:we,fullscreenSupported:Te,toggleFullscreen:Ee,toolbarOpen:De,drawerOpen:Oe,toolbarButtonRef:ke,drawerButtonRef:Ae,searchInputRef:je,inspectorRef:Me,panelRef:Ne,toggleToolbar:Pe,toggleDrawer:Fe,openDetails:Ie}=Iv(e,c,d,i,t,n,f),[Le,Re]=Yv(De,v,Ne),[ze,Be]=Yv(Oe,v,Me),Ve=(0,y.useRef)(null),He=Vv(w,T,se,ce,e.meta.locale,ff(e),oe),{open:Ue,toggle:We,close:Ge}=Lv(),Ke=e.meta.notes??[],[qe,Je]=(0,y.useState)(!0),Ye=Ke.length>0&&qe&&!ze,Xe=Oe||Ye&&!Ce,Ze=(0,y.useRef)(!1),Qe=(0,y.useRef)(null);(0,y.useEffect)(()=>{Ze.current&&Qe.current?.focus({preventScroll:!0})},[qe]);let $e=Rv(ne,z,L,g,v),[et,tt]=(0,y.useState)(!1),[nt,rt]=(0,y.useState)(``),[it,at]=(0,y.useState)(0);(0,y.useEffect)(()=>{(Oe||O===0)&&at(O)},[Oe,O]);let ot=(0,y.useMemo)(()=>{let e=new Map(fe.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:kp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=Pg(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,fe]);(0,y.useEffect)(()=>{if(!_e)return;rt(h(_e.message));let e=window.setTimeout(()=>rt(``),4500);return()=>window.clearTimeout(e)},[_e]);let st=O>0&&!Oe&&(g!==`sequence`||O!==it)&&!z.some(e=>e.dragging),ct=st?z.find(e=>e.id===E&&e.type===`diagram`):null,lt=st?pe.find(e=>e.id===D):null,ut=lt?L.edges.find(e=>e.id===lt.id):null,dt=lt?{position:lt.data.route.labelPoint,size:{width:0,height:0}}:null,ft=ut?L.nodes.find(e=>e.id===ut.source):null,pt=ut?L.nodes.find(e=>e.id===ut.target):null,mt=T?L.nodes.find(e=>e.id===T.source):null,ht=T?L.nodes.find(e=>e.id===T.target):null,gt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(cp[e.kind]??e.kind)})]},e.id),_t=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(Bv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:np(w,_,i).stroke}}),h(w.section?`Section`:cp[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.overviewText?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Overview text`)}),(0,x.jsx)(`ul`,{children:w.overviewText.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(op[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:sp(e.source)})]},t))})]}),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(op[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:sp(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:pe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Kh(L).get(T.id)?.label??kh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[mt?.label,` → `,ht?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(op[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:sp(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(Bv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:He.editing?``:`card-actions`,children:(0,x.jsx)(Hv,{editor:He,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return Oe&&(Ve.current=_t),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||$e(E,D,!0,Xe)},"aria-controls":`graph-tools`,"aria-expanded":De,"aria-pressed":De,"aria-label":h(De?`Hide graph navigation`:`Show graph navigation`),title:h(De?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(Bv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(gf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>tt(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tt(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(Bv,{name:`search`}),(0,x.jsx)(`input`,{ref:je,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),et&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(cp[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>We(`views`),"aria-haspopup":`menu`,"aria-expanded":Ue===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(Bv,{name:`views`}),(0,x.jsx)(`span`,{children:h(gf(e))}),(0,x.jsx)(Bv,{name:`chevron`})]}),Ue===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{Zm(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(Bv,{name:`check`}):null}),`${h(gf(t))}${r.filter(e=>hf(e)===hf(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(Bv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>We(`more`),"aria-haspopup":`menu`,"aria-expanded":Ue===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(Bv,{name:`more`})}),Ue===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`svg`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`png`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{ge(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{me(),Ge()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{de(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Bv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":qv.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${qv.indexOf(l)*100}%)`}}),qv.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(Jv[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:Ae,onClick:()=>{Fe(),Oe||$e(E,D,De,!0)},"aria-controls":`node-inspector`,"aria-expanded":Oe,"aria-pressed":Oe,title:h(Oe?`Hide details`:`Show details`),"aria-label":h(Oe?`Hide details`:`Show details`),children:(0,x.jsx)(Bv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${De?`nav-open`:``} ${Oe?`drawer-open`:``}`,children:[Le&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Ne,tabIndex:-1,className:`sidebar nav${Re}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Pe,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(Bv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(gt)})]}),(0,x.jsxs)(`figure`,{ref:xe,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:Kp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ae,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":De,"data-drawer-open":Xe,onKeyDownCapture:e=>{ie(e),e.defaultPrevented||F(e)},"aria-label":h(`Interactive {type}`,{type:h(gf(e))}),children:[(0,x.jsxs)(Sd,{nodes:fe,edges:pe,nodeTypes:Hg,edgeTypes:Ug,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),Ge()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>le(L,0)),nodesDraggable:!I&&!ae,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:ue,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(Bv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:Se,onClick:Ee,"aria-pressed":Ce,"aria-busy":we,"aria-disabled":we||!Te&&!Ce,"aria-label":h(Ce?`Exit fullscreen`:`Enter fullscreen`),title:h(!Te&&!Ce?`Fullscreen is not available in this browser or page`:Ce?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(Bv,{name:Ce?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ot,nodeStrokeColor:e=>e.type===`boundary`?`none`:np(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:np(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>We(`legend`),"aria-expanded":Ue===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(Bv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),Ue===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:qg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:Kg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Ke.length>0&&!ze&&(Ye?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":h(`Key points`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[h(`Key points`),` · `,Ke.length]}),(0,x.jsx)(`button`,{className:`side-close`,ref:Qe,onClick:()=>{Ze.current=!0,Je(!1)},"aria-label":h(`Hide key points`),title:h(`Hide key points`),children:(0,x.jsx)(Bv,{name:`close`})})]}),(0,x.jsx)(`ul`,{children:Ke.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:Qe,"aria-expanded":`false`,onClick:()=>{Ze.current=!0,Je(!0),Ce||$e(E,D,De,!0)},"aria-label":h(`Show key points`),title:h(`Show key points`),children:[(0,x.jsx)(Bv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[h(`Key points`),` · `,Ke.length]})]})),ct&&(0,x.jsx)(Kv,{node:{...ct.data,position:ct.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),ut&&(0,x.jsx)(Kv,{node:dt,edge:{...ut,diagramType:g},source:ft,target:pt,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),!ve&&ye.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ye.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>be(ye.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),ve&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:ve.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>be(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:ve.message})]}),(0,x.jsx)(`div`,{className:`toast ${nt?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:nt})]})]}),ze&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:Me,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${Be}`,"aria-label":h(`Details`),children:Ve.current})]})]})}function Zv(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var Qv=JSON.parse(document.querySelector(`#graph-data`).textContent),$v=[...Array.isArray(Qv.diagrams)?Qv.diagrams:[Qv]].sort(_f),ey=window.matchMedia(`(prefers-color-scheme: dark)`);function ty(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(ey.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return ey.addEventListener(`change`,e),()=>ey.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function ny(){let[e,t]=(0,y.useState)(uf($v[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=ty(),s=Zv(),c=$v.find(t=>uf(t)===e)??$v[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>dv(Qv,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=Zf($v,Wf[o]);return f?e:$f(e,Wf[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(ap(Wf[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)(Xv,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:$v,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(ny,{})); - diff --git a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx index 00211e3..c831dc9 100644 --- a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx +++ b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx @@ -1,4 +1,4 @@ -import { visibleEdges } from './presentation-graph.js'; +import { presentationGraph, visibleEdges } from './presentation-graph.js'; import { overviewSections, sectionSvg } from './architecture-overview.js'; import React, { useId } from 'react'; import { BaseEdge, EdgeLabelRenderer, Handle, MarkerType, Position } from '@xyflow/react'; @@ -101,13 +101,13 @@ export function initialNodes(graph, diagramType) { connectable: false, zIndex: -(graph.groups?.length ?? 0) + fragmentDepth(group, graph.groups ?? []) })); - const classicCard = !compactCards(graph); + const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])); return [...overviewSections(graph).map((section, index) => ({ id: section.id, type: 'overview', position: section.position, data: { ...section }, style: { width: section.size.width, height: section.size.height, pointerEvents: 'none' }, draggable: false, selectable: false, zIndex: -100 + index })), ...boundaries, ...graph.nodes.map(node => ({ id: node.id, type: 'diagram', className: diagramType === 'sequence' ? 'sequence-column' : undefined, position: node.position, - data: { ...node, diagramType, locale: graph.meta.locale, classicCard }, + data: { ...drawn.get(node.id), diagramType, locale: graph.meta.locale, classicCard }, style: { width: node.size.width, height: node.size.height, ...(diagramType === 'sequence' ? { pointerEvents: 'none' } : {}) }, zIndex: 2 }))]; diff --git a/skills/q-flow/assets/viewer/src/TextEditor.jsx b/skills/q-flow/assets/viewer/src/TextEditor.jsx index 1650235..74879d1 100644 --- a/skills/q-flow/assets/viewer/src/TextEditor.jsx +++ b/skills/q-flow/assets/viewer/src/TextEditor.jsx @@ -4,7 +4,7 @@ import { translate } from './i18n.js'; export function useTextEditor(node, edge, onSaveNode, onSaveEdge, locale, overviewView = false, onCancel = () => {}) { const object = edge ?? node, key = object ? `${edge ? 'edge' : 'node'}:${object.id}` : null; - const overview = Boolean(node && (overviewView || node.section || node.overviewText !== undefined || node.badges !== undefined)); + const overview = Boolean(node && (overviewView || node.section || node.overviewText !== undefined)); const saveToken = useRef(0); const [draft, setDraft] = useState({ editing: false, pending: false, label: '', subtitle: '', overviewText: '', badges: [], error: '' }); const reset = (returnFocus = false) => setDraft({ editing: false, pending: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', overviewText: (node?.overviewText ?? []).join('\n'), badges: structuredClone(node?.badges ?? []), error: '', returnFocus }); diff --git a/skills/q-flow/assets/viewer/src/ViewerShell.jsx b/skills/q-flow/assets/viewer/src/ViewerShell.jsx index d7d6d78..8302850 100644 --- a/skills/q-flow/assets/viewer/src/ViewerShell.jsx +++ b/skills/q-flow/assets/viewer/src/ViewerShell.jsx @@ -8,6 +8,7 @@ import { diagramLabels, diagramTypeOf } from './diagrams/registry.js'; import { visibleEdgeLabel, createEdgeRoutes } from './edge-routing.js'; import { svgStyles, groupFrameSvg } from './diagrams/drawing.js'; import { anchorText, evidenceLabels, kindLabels, nodeAppearance } from './visual-style.js'; +import { foldedEdges } from './presentation-graph.js'; import { graphLegend, rampGradient } from './legend.js'; import { useViewerController } from './features/useViewerController.js'; import { usePopover } from './features/usePopover.js'; @@ -108,6 +109,7 @@ export default function ViewerShell({ graph, originalGraph, graphForSave, allDia

{inspectedNode.subtitle}

{inspectedNode.overviewText?.length > 0 && <>

{t('Overview text')}

    {inspectedNode.overviewText.map((line, i) =>
  • {line}
  • )}
} {inspectedNode.badges?.length > 0 && <>

{t('Badges')}

    {inspectedNode.badges.map((badge, i) =>
  • {badge.label} · {t(evidenceLabels[badge.evidence])}{badge.source && {anchorText(badge.source)}}
  • )}
} + {(folded => folded.length > 0 && <>

{t('Shared dependencies')}

    {folded.map(edge =>
  • {edge.site && {anchorText(edge.site)}}
  • )}
)(foldedEdges(currentGraph).filter(edge => edge.source === inspectedNode.id))} {inspectedNode.fields?.length > 0 && <>

{t('Fields')}

    {inspectedNode.fields.map(field =>
  • {field.key} {field.name}: {field.type}{field.nullable === false ? ' · NOT NULL' : field.nullable === true ? ' · NULL' : ''}
  • )}
} {inspectedNode.attributes?.length > 0 && <>

{t('Attributes')}

    {inspectedNode.attributes.map(item =>
  • {item}
  • )}
} {inspectedNode.methods?.length > 0 && <>

{t('Methods')}

    {inspectedNode.methods.map(item =>
  • {item}
  • )}
} diff --git a/skills/q-flow/assets/viewer/src/architecture-overview.js b/skills/q-flow/assets/viewer/src/architecture-overview.js index 968087b..2fdbf40 100644 --- a/skills/q-flow/assets/viewer/src/architecture-overview.js +++ b/skills/q-flow/assets/viewer/src/architecture-overview.js @@ -12,7 +12,8 @@ export const overviewSections = graph => { }; const object = value => value && typeof value === 'object' && !Array.isArray(value); const strings = value => Array.isArray(value) && value.every(item => typeof item === 'string' && item.trim()); -export const hasOverviewContent = node => node.overviewText !== undefined || node.badges !== undefined || node.overviewTone !== undefined; +// Badges alone do not make an overview card: relations and deployment cards draw them as tags under the source line. +export const hasOverviewContent = node => node.overviewText !== undefined || node.overviewTone !== undefined; export function validateOverview(graph, { inputOnly = true, validateAnchor, evidenceKinds } = {}) { const errors = [], overview = isArchitectureOverview(graph); diff --git a/skills/q-flow/assets/viewer/src/diagrams/card.js b/skills/q-flow/assets/viewer/src/diagrams/card.js index 8798e51..f620f5e 100644 --- a/skills/q-flow/assets/viewer/src/diagrams/card.js +++ b/skills/q-flow/assets/viewer/src/diagrams/card.js @@ -3,15 +3,17 @@ import { cardTextLayout, text, coreNode, dataKinds, paint } from './drawing.js'; export function genericCard(node, x, y, fill, stroke, palette, locale, outline, contentInset = 0, corner = 0) { if (node.classicCard) return classicCard(node, x, y, fill, stroke, palette, locale, outline, contentInset); - const { title, subtitle, source, tag, contentHeight } = cardTextLayout({ ...node, size: { ...node.size, width: node.size.width - contentInset * 2 } }, locale, false, corner); + const { title, subtitle, source, tag, chips, contentHeight } = cardTextLayout({ ...node, size: { ...node.size, width: node.size.width - contentInset * 2 } }, locale, false, corner); // Baselines sit 20/17/14px below the top of their 26/24/20px lines. const left = x + contentInset, row = y + Math.max(0, (node.size.height - contentHeight) / 2) + CARD.pad, column = left + CARD.textX; const subtitleTop = row + title.height + (subtitle.height ? 4 : 0), sourceTop = subtitleTop + subtitle.height + (source.height ? 6 : 0); + const chipsTop = sourceTop + source.height + (chips.length ? 6 : 0); + const chipText = chips.map(chip => { const top = chipsTop + chip.row * CARD.chipLine; return `${text(column + chip.x + chip.width / 2, top + 15, chip.text, 'stereotype', ' text-anchor="middle"')}`; }).join(''); const titleText = title.lines.map((line, index) => text(column, row + 20 + index * title.lineHeight, line, 'title')).join(''); const subtitleText = subtitle.lines.map((line, index) => text(column, subtitleTop + 17 + index * subtitle.lineHeight, line, 'body')).join(''); const sourceText = source.lines.map((line, index) => text(column, sourceTop + 14 + index * source.lineHeight, line, 'meta')).join(''); const plate = { x: left + CARD.pad, y: row + (CARD.titleLine - CARD.plate) / 2 }, tagX = x + node.size.width - contentInset - CARD.pad - tag.width - corner; - return `${frame(node, x, y, fill, stroke, outline)}${iconPlate(node, plate.x, plate.y, CARD.plate, palette)}${text(tagX + tag.width / 2, row + 18, tag.text, 'stereotype', ' text-anchor="middle"')}${titleText}${subtitleText}${sourceText}`; + return `${frame(node, x, y, fill, stroke, outline)}${iconPlate(node, plate.x, plate.y, CARD.plate, palette)}${text(tagX + tag.width / 2, row + 18, tag.text, 'stereotype', ' text-anchor="middle"')}${titleText}${subtitleText}${sourceText}${chipText}`; } const frame = (node, x, y, fill, stroke, outline) => paint(outline(node, x, y), { fill, stroke, 'stroke-width': node.appearance?.moduleColor || node.appearance?.ring ? 1.5 : 1 }); diff --git a/skills/q-flow/assets/viewer/src/graph-validation.js b/skills/q-flow/assets/viewer/src/graph-validation.js index 5333d75..d08cb87 100644 --- a/skills/q-flow/assets/viewer/src/graph-validation.js +++ b/skills/q-flow/assets/viewer/src/graph-validation.js @@ -209,6 +209,13 @@ function validateLayoutSemantics(graph) { if (graph.layout !== undefined && !isObject(graph.layout)) errors.push('layout must be an object'); else if (graph.layout?.direction !== undefined && !layeredDirections(type).includes(graph.layout.direction)) errors.push(`layout.direction must be one of ${layeredDirections(type).join(', ')} for ${type}`); if (graph.layout?.overviewConnections !== undefined && (!isArchitectureOverview(graph) || !['within-category', 'all'].includes(graph.layout.overviewConnections))) errors.push('layout.overviewConnections requires an architecture overview and within-category or all'); + if (graph.layout?.sharedDependencies !== undefined) { + // Edges into these nodes are drawn as tags on their source cards; a path through one would lose its line. + const list = graph.layout.sharedDependencies; + if (type !== 'architecture' || isArchitectureOverview(graph)) errors.push('layout.sharedDependencies requires an architecture relations view'); + else if (!Array.isArray(list) || !list.length || list.some(id => typeof id !== 'string' || !nodes.has(id)) || new Set(list).size !== list.length) errors.push('layout.sharedDependencies must be a non-empty list of distinct node IDs'); + else if (Array.isArray(graph.layout.primaryPath) && graph.layout.primaryPath.slice(1).some(id => list.includes(id))) errors.push('layout.primaryPath cannot enter a shared dependency'); + } if (isObject(graph.layout)) for (const key of ['primaryPath', 'participantOrder']) { const list = graph.layout?.[key]; if (list === undefined) continue; @@ -250,17 +257,15 @@ export function validateGraphInput(input, options = {}) { return [`diagrams must contain between 1 and 32 graphs`]; } - const errors = []; - const types = new Set(), viewIds = new Set(); - const architectureCount = input.diagrams.filter(graph => diagramTypeOf(graph) === 'architecture').length; + // Any type may repeat (a long flow split by phase, two architecture templates); repeated views name themselves. + const errors = [], viewIds = new Set(), counts = new Map(); + for (const graph of input.diagrams) counts.set(diagramTypeOf(graph), (counts.get(diagramTypeOf(graph)) ?? 0) + 1); input.diagrams.forEach((graph, index) => { const type = diagramTypeOf(graph); - if (types.has(type) && type !== 'architecture') errors.push(`diagrams[${index}].meta.diagramType duplicates ${type}`); - if (type === 'architecture' && architectureCount > 1 && !graph?.meta?.viewId) errors.push(`diagrams[${index}].meta.viewId is required for repeated architecture views`); + if (counts.get(type) > 1 && !graph?.meta?.viewId) errors.push(`diagrams[${index}].meta.viewId is required for repeated ${type} views`); const viewId = viewIdOf(graph); if (viewIds.has(viewId)) errors.push(`diagrams[${index}].meta.viewId duplicates ${viewId}`); viewIds.add(viewId); - types.add(type); errors.push(...authored(graph).map(error => `diagrams[${index}].${error}`)); }); return errors; diff --git a/skills/q-flow/assets/viewer/src/i18n-messages.json b/skills/q-flow/assets/viewer/src/i18n-messages.json index a3f637c..bb02dc1 100644 --- a/skills/q-flow/assets/viewer/src/i18n-messages.json +++ b/skills/q-flow/assets/viewer/src/i18n-messages.json @@ -183,7 +183,8 @@ "Cancelled": "已取消", "Component relationship architecture": "组件关系架构图", "Platform capability architecture": "平台能力架构图", - "Engineering layer architecture": "工程分层架构图" + "Engineering layer architecture": "工程分层架构图", + "Shared dependencies": "公共依赖" }, "ja": { "Architecture": "アーキテクチャ", @@ -369,7 +370,8 @@ "Platform capability architecture": "プラットフォーム機能アーキテクチャ図", "Engineering layer architecture": "プロジェクト階層アーキテクチャ図", "Layout suggestions": "レイアウトの提案", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。" + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。", + "Shared dependencies": "共通の依存先" }, "ko": { "Architecture": "아키텍처", @@ -555,7 +557,8 @@ "Platform capability architecture": "플랫폼 기능 아키텍처", "Engineering layer architecture": "엔지니어링 계층 아키텍처", "Layout suggestions": "레이아웃 제안", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다." + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.", + "Shared dependencies": "공통 의존성" }, "de": { "Architecture": "Architektur", @@ -741,7 +744,8 @@ "Platform capability architecture": "Plattformfähigkeitsarchitektur", "Engineering layer architecture": "Schichtenarchitektur", "Layout suggestions": "Layoutvorschläge", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten." + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.", + "Shared dependencies": "Gemeinsame Abhängigkeiten" }, "fr": { "Architecture": "Architecture", @@ -927,7 +931,8 @@ "Platform capability architecture": "Architecture des capacités", "Engineering layer architecture": "Architecture en couches", "Layout suggestions": "Suggestions de disposition", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là." + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.", + "Shared dependencies": "Dépendances partagées" }, "es": { "Architecture": "Arquitectura", @@ -1113,7 +1118,8 @@ "Platform capability architecture": "Arquitectura de capacidades", "Engineering layer architecture": "Arquitectura por capas", "Layout suggestions": "Sugerencias de diseño", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces." + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.", + "Shared dependencies": "Dependencias compartidas" }, "ru": { "Architecture": "Архитектура", @@ -1299,7 +1305,8 @@ "Platform capability architecture": "Архитектура возможностей платформы", "Engineering layer architecture": "Слоистая архитектура", "Layout suggestions": "Рекомендации по размещению", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются." + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.", + "Shared dependencies": "Общие зависимости" }, "pt": { "Architecture": "Arquitetura", @@ -1485,6 +1492,7 @@ "Platform capability architecture": "Arquitetura de capacidades", "Engineering layer architecture": "Arquitetura em camadas", "Layout suggestions": "Sugestões de disposição", - "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá." + "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.", + "Shared dependencies": "Dependências compartilhadas" } } diff --git a/skills/q-flow/assets/viewer/src/layout-browser-worker.js b/skills/q-flow/assets/viewer/src/layout-browser-worker.js index d01e4e6..f584bb0 100644 --- a/skills/q-flow/assets/viewer/src/layout-browser-worker.js +++ b/skills/q-flow/assets/viewer/src/layout-browser-worker.js @@ -6,10 +6,13 @@ import { layoutMetrics } from './layout-refinement.js'; import { refineDiagramLayout, refineWithLegacySeed } from './layout-refinement.js'; import { fitArchitectureOverview, maintainArchitectureOverview } from './architecture-overview.js'; import { requireDiagramQuality } from './layout-quality.js'; +import { hasSharedDependencies, presentationGraph, restorePresentation } from './presentation-graph.js'; // Bundled inline into the offline page. The algorithm is exactly the generator's pure source. -self.onmessage = ({ data }) => { +self.onmessage = ({ data: message }) => { try { + // Shared dependencies: lay out the drawn graph, then hand back the authored model (every edge, no display tags). + const folded = !message.overview && hasSharedDependencies(message.graph), data = folded ? { ...message, graph: presentationGraph(message.graph) } : message; let result; if (data.overview) result = { graph: data.options?.relayout ? fitArchitectureOverview(data.graph, requireDiagramQuality) : maintainArchitectureOverview(data.graph, data.reference ?? data.graph, requireDiagramQuality) }; else if (data.options?.relayout && data.graph.meta.diagramType === 'sequence') { @@ -28,7 +31,7 @@ self.onmessage = ({ data }) => { if (!candidates.length) throw new Error('No valid semantic layout'); result = refineWithLegacySeed(candidates[0].graph, data.graph, { global: true, evaluations: 60 }); } else result = refineDiagramLayout(data.options?.relayout ? { ...data.graph, layout: { ...data.graph.layout, version: LAYOUT_VERSION } } : data.graph, { ...data.options, global: Boolean(data.options?.relayout) }); - self.postMessage({ result: { graph: result.graph, movedNodeIds: result.movedNodeIds ?? [] } }); + self.postMessage({ result: { graph: folded ? restorePresentation(message.graph, result.graph) : result.graph, movedNodeIds: result.movedNodeIds ?? [] } }); } catch (error) { self.postMessage({ error: { message: error.message, diagnostics: error.diagnostics ?? [], routingReport: error.routingReport } }); } diff --git a/skills/q-flow/assets/viewer/src/layout-templates.js b/skills/q-flow/assets/viewer/src/layout-templates.js index 7b005c8..f0254c8 100644 --- a/skills/q-flow/assets/viewer/src/layout-templates.js +++ b/skills/q-flow/assets/viewer/src/layout-templates.js @@ -141,6 +141,16 @@ export const LAYOUT_TEMPLATES = Object.freeze({ }); export const templateOf = graph => LAYOUT_TEMPLATES[viewTypeOf(graph)]; +// The size a node is laid out at: its text minimum, made tall enough for a self-transition's label to sit on the +// side loop (orthogonal-routing selfCorridor keeps the loop 12px inside the node's side; the label needs 4px at +// each end of that leg). Taller than the text minimum, so the quality gate's minimum still holds. +export function layoutNodeSize(node, graph, type = diagramTypeOf(graph)) { + const size = minimumNodeSize(node, type, graph.meta?.locale); + const loops = graph.edges.filter(edge => edge.source === node.id && edge.target === node.id); + const room = Math.max(0, ...loops.map(edge => estimateLabelSize(visibleEdgeLabel(edge, type, graph.meta?.locale)).height + 32)); + return room > size.height ? { ...size, height: Math.ceil(room) } : size; +} + // A measured template supplies positions only. Routing and acceptance are the same as for ELK and browser edits. // No virtual groups, rank hints, inferred relationships or shortened text are persisted into the semantic model. export function templateDraft(input, variant = 0) { @@ -149,7 +159,7 @@ export function templateDraft(input, variant = 0) { const linear = input.edges.length === input.nodes.length - 1 && input.nodes.every(node => input.edges.filter(edge => edge.source === node.id).length <= 1 && input.edges.filter(edge => edge.target === node.id).length <= 1); if (linear && !['flowchart', 'class', 'state', 'deployment', 'dataflow', 'usecase'].includes(viewTypeOf(input))) return null; const graph = structuredClone(input), type = diagramTypeOf(graph), diagram = getDiagram(type), limits = layoutLimits(diagram), target = layoutTargets(diagram); - graph.nodes.forEach(node => { node.size = minimumNodeSize(node, type, graph.meta.locale); }); + graph.nodes.forEach(node => { node.size = layoutNodeSize(node, graph, type); }); graph.edges.forEach(edge => { delete edge.route; }); const allGroups = graph.groups ?? []; function compose(parentId) { @@ -190,9 +200,16 @@ export function templateDraft(input, variant = 0) { const along = sideways ? 'x' : 'y', across = sideways ? 'y' : 'x', height = sideways ? 'width' : 'height', width = sideways ? 'height' : 'width'; // Shared column tracks and row baselines are measured once for the whole ownership scope. const columnWidths = Array.from({ length: Math.max(0, ...rows.map(row => row.length)) }, (_, column) => Math.max(0, ...rows.map(row => row[column]?.size[width] ?? 0))); - const lateral = graph.edges.filter(edge => rows.some(row => row.some(item => item.ids.has(edge.source)) && row.some(item => item.ids.has(edge.target)) && !row.some(item => item.ids.has(edge.source) && item.ids.has(edge.target)))); - const widestLabel = Math.max(0, ...lateral.map(edge => estimateLabelSize(visibleEdgeLabel(edge, type, graph.meta.locale))[width])); - const gap = Math.max(target.nodeGap, Math.min(widestLabel + 2 * limits.labelGap, 240)) + variant * 24; + // Labels between row neighbours need the column gap; so does a self-transition beside a neighbour, whose loop + // and label leave its node sideways (orthogonal-routing selfCorridor) and must clear the next column. + const lateral = graph.edges.filter(edge => edge.source === edge.target + ? rows.some(row => row.length > 1 && row.some(item => item.ids.has(edge.source))) + : rows.some(row => row.some(item => item.ids.has(edge.source)) && row.some(item => item.ids.has(edge.target)) && !row.some(item => item.ids.has(edge.source) && item.ids.has(edge.target)))); + const labelSpan = edge => estimateLabelSize(visibleEdgeLabel(edge, type, graph.meta.locale))[width]; + const widestLabel = Math.max(0, ...lateral.filter(edge => edge.source !== edge.target).map(labelSpan)); + // A side loop's label sits on the loop's outer leg, so it needs its whole width plus clearance; never capped. + const loopRoom = Math.max(0, ...lateral.filter(edge => edge.source === edge.target).map(edge => labelSpan(edge) + 2 * limits.labelGap + 8)); + const gap = Math.max(target.nodeGap, Math.min(widestLabel + 2 * limits.labelGap, 240), loopRoom) + variant * 24; const tracks = columnWidths.map((_, column) => columnWidths.slice(0, column).reduce((sum, size) => sum + size + gap, 0)); const extent = columnWidths.reduce((sum, size) => sum + size, 0) + Math.max(0, columnWidths.length - 1) * gap; let cursor = 0; diff --git a/skills/q-flow/assets/viewer/src/presentation-graph.js b/skills/q-flow/assets/viewer/src/presentation-graph.js index 6c091c6..0724d14 100644 --- a/skills/q-flow/assets/viewer/src/presentation-graph.js +++ b/skills/q-flow/assets/viewer/src/presentation-graph.js @@ -17,15 +17,50 @@ export function overviewCategoryMap(graph) { (graph.layout?.sections ?? []).forEach(visit); return categories; } + +// A relations view may name components nearly everything depends on (configuration, data access). Edges into them are +// drawn as a tag on the source card instead of a line; the edges, their sites and details stay in the model. +const sharedOf = graph => !isArchitectureOverview(graph) && (graph.meta?.diagramType ?? 'architecture') === 'architecture' + && Array.isArray(graph.layout?.sharedDependencies) && graph.layout.sharedDependencies.length ? new Set(graph.layout.sharedDependencies) : null; +export const hasSharedDependencies = graph => Boolean(sharedOf(graph)); +export function foldedEdges(graph) { + const shared = sharedOf(graph); + return shared ? graph.edges.filter(edge => shared.has(edge.target) && edge.source !== edge.target) : []; +} + export function visibleEdges(graph) { + const shared = sharedOf(graph); + if (shared) return graph.edges.filter(edge => !shared.has(edge.target) || edge.source === edge.target); if (!isArchitectureOverview(graph) || graph.layout?.overviewConnections === 'all') return graph.edges; const categories = overviewCategoryMap(graph); return graph.edges.filter(edge => categories.has(edge.source) && categories.get(edge.source) === categories.get(edge.target)); } -export const presentationGraph = graph => ({ ...graph, edges: visibleEdges(graph) }); + +// The graph as drawn and laid out. With shared dependencies it also drops layout.sharedDependencies and gives each source +// card a display-only `dependencyTags` list, so presenting an already presented graph changes nothing. +export function presentationGraph(graph) { + const shared = sharedOf(graph); + if (!shared) return { ...graph, edges: visibleEdges(graph) }; + const labels = new Map(graph.nodes.map(node => [node.id, node.label])), tags = new Map(); + for (const edge of foldedEdges(graph)) tags.set(edge.source, [...new Set([...(tags.get(edge.source) ?? []), `→ ${labels.get(edge.target)}`])]); + const { sharedDependencies, ...layout } = graph.layout; + return { ...graph, layout, edges: visibleEdges(graph), nodes: graph.nodes.map(node => tags.has(node.id) ? { ...node, dependencyTags: tags.get(node.id) } : node) }; +} // Reinstall routed visible edges in their original semantic order; hidden facts remain available in details and JSON. export function mergePresentationEdges(graph, routed) { const byId = new Map(routed.edges.map(edge => [edge.id, edge])); return graph.edges.map(edge => byId.get(edge.id) ?? edge); } + +// A laid-out presentation back as the authored model: every edge (folded ones without a route), nodes without their +// display tags, and the authored shared-dependency list. +export function restorePresentation(graph, laid) { + const nodes = new Map(laid.nodes.map(node => [node.id, node])), edges = new Map(laid.edges.map(edge => [edge.id, edge])); + return { + ...laid, + layout: { ...laid.layout, sharedDependencies: graph.layout.sharedDependencies }, + nodes: graph.nodes.map(node => { const { dependencyTags, ...placed } = nodes.get(node.id) ?? node; return placed; }), + edges: graph.edges.map(edge => { if (edges.has(edge.id)) return edges.get(edge.id); const { route, ...folded } = edge; return folded; }) + }; +} diff --git a/skills/q-flow/assets/viewer/src/session-graph.js b/skills/q-flow/assets/viewer/src/session-graph.js index bae5856..cb49408 100644 --- a/skills/q-flow/assets/viewer/src/session-graph.js +++ b/skills/q-flow/assets/viewer/src/session-graph.js @@ -3,6 +3,7 @@ import { cardText, diagramTypeOf, getDiagram } from './diagrams/registry.js'; import { layoutLimits } from './layout-spacing.js'; import { requireDiagramQuality } from './layout-quality.js'; import { groupHeadingLayout } from './text-layout.js'; +import { presentationGraph } from './presentation-graph.js'; // The generator embeds the graph as escaped JSON inside this script element; saving from the page rewrites the same // element, so the saved page reopens with its edits and the generator and the page never disagree about the encoding. @@ -65,7 +66,9 @@ export function placed(graph, boxes) { // (compactCards of the graph before the edit). Returns id -> { position, size } for every box that changed. export function fitCard(graph, id, classic) { const type = diagramTypeOf(graph), diagram = getDiagram(type), node = graph.nodes.find(item => item.id === id); - const grow = diagram.cardLayout ? cardText(node, type, graph.meta.locale, classic).minHeight - node.size.height : 0; + // Measure the card as drawn, with its folded shared-dependency tags. + const drawn = presentationGraph(graph).nodes.find(item => item.id === id); + const grow = diagram.cardLayout ? cardText(drawn, type, graph.meta.locale, classic).minHeight - node.size.height : 0; if (grow <= 0) return new Map(); const { groupInset, groupHeadingGap } = layoutLimits(diagram), groups = new Map((graph.groups ?? []).map(group => [group.id, group])); // `above` is the share of the extra height that goes over the card's top edge; each boundary then takes in its member's box. diff --git a/skills/q-flow/assets/viewer/src/styles.css b/skills/q-flow/assets/viewer/src/styles.css index 9224612..691c6b0 100644 --- a/skills/q-flow/assets/viewer/src/styles.css +++ b/skills/q-flow/assets/viewer/src/styles.css @@ -345,6 +345,8 @@ button:disabled { cursor: not-allowed; } .drawer li + li { margin-top: 5px; } .drawer li::marker { color: var(--accent); } .drawer code { white-space: normal; overflow-wrap: anywhere; font-family: ui-monospace, SFMono-Regular, monospace; font-size: 12px; } +.folded-edge { padding: 0; border: 0; background: none; color: var(--label); font: inherit; text-align: left; cursor: pointer; } +.folded-edge:hover, .folded-edge:focus-visible { color: var(--accent); text-decoration: underline; } .source-path { max-width: 100%; display: block; padding: 8px 10px; border-radius: var(--r-field); color: var(--accent); background: var(--fill); font-size: 12px; line-height: 1.55; overflow-wrap: anywhere; } .symbol { margin-top: 6px !important; color: var(--label-2); font: 12px/1.55 ui-monospace, SFMono-Regular, monospace; } .tags { margin-top: 14px; display: flex; flex-wrap: wrap; gap: 5px; } diff --git a/skills/q-flow/assets/viewer/src/text-layout.js b/skills/q-flow/assets/viewer/src/text-layout.js index b2ff670..210b9cf 100644 --- a/skills/q-flow/assets/viewer/src/text-layout.js +++ b/skills/q-flow/assets/viewer/src/text-layout.js @@ -82,7 +82,7 @@ export function layoutText(value, maxWidth, fontSize = TYPOGRAPHY.body, lineHeig // Component card: the icon plate, the title and the kind tag share the first row; the subtitle and the source anchor (file // name and lines) follow in the same text column. The whole block is centred vertically in a taller card. -export const CARD = Object.freeze({ pad: 14, plate: 24, textX: 48, tagGap: 8, tagPad: 8, titleLine: 26, subtitleLine: 24, sourceLine: 20, minHeight: 64, maxWidth: 360 }); +export const CARD = Object.freeze({ pad: 14, plate: 24, textX: 48, tagGap: 8, tagPad: 8, titleLine: 26, subtitleLine: 24, sourceLine: 20, chipLine: 24, chipGap: 6, minHeight: 64, maxWidth: 360 }); // The card shows where a component is defined (file name and first line); the quick look and Inspector give the full path and range. export const cardSourceText = node => node.source?.file ? `${node.source.file.split('/').at(-1)}:${node.source.lineStart}` : ''; // A source line never wraps: a file name too long for the column keeps its start and end around an ellipsis. @@ -109,8 +109,24 @@ export function cardTextLayout(node, locale, classic = false, corner = 0) { const title = layoutText(node.label, column - tag.width - CARD.tagGap - corner, TYPOGRAPHY.title, CARD.titleLine); const subtitle = layoutText(node.subtitle ?? '', column, TYPOGRAPHY.body, CARD.subtitleLine); const source = layoutText(oneLine(cardSourceText(node), column, TYPOGRAPHY.small), column, TYPOGRAPHY.small, CARD.sourceLine); - const contentHeight = CARD.pad + title.height + (subtitle.height ? 4 + subtitle.height : 0) + (source.height ? 6 + source.height : 0) + CARD.pad; - return { title, subtitle, source, tag, contentHeight, minHeight: Math.max(CARD.minHeight, contentHeight) }; + const chips = cardChips(node, column), chipsHeight = chips.length ? (chips.at(-1).row + 1) * CARD.chipLine : 0; + const contentHeight = CARD.pad + title.height + (subtitle.height ? 4 + subtitle.height : 0) + (source.height ? 6 + source.height : 0) + (chipsHeight ? 6 + chipsHeight : 0) + CARD.pad; + return { title, subtitle, source, tag, chips, contentHeight, minHeight: Math.max(CARD.minHeight, contentHeight) }; +} + +// Badges and folded shared dependencies (dependencyTags, display only) as tags under the source line, wrapped to the +// text column; a tag wider than the column keeps the column width. +function cardChips(node, column) { + const chips = []; + let x = 0, row = 0; + for (const value of [...(node.badges ?? []).map(badge => badge.label), ...(node.dependencyTags ?? [])]) { + // Same measure as the kind tag: stereotype letter spacing .6px per character. + const width = Math.min(column, Math.ceil(textWidth(value, TYPOGRAPHY.small) + value.length * .6) + 2 * CARD.tagPad); + if (x && x + width > column) { row++; x = 0; } + chips.push({ text: value, x, row, width }); + x += width + CARD.chipGap; + } + return chips; } export function edgeLabelLayout(value, maxWidth = LAYOUT_TARGETS.labelWidth) { diff --git a/skills/q-flow/assets/viewer/src/view-identity.js b/skills/q-flow/assets/viewer/src/view-identity.js index cab7c5a..a99c44a 100644 --- a/skills/q-flow/assets/viewer/src/view-identity.js +++ b/skills/q-flow/assets/viewer/src/view-identity.js @@ -1,4 +1,4 @@ -// Legacy collections use their unique diagram type as identity. Repeated architecture views require authored IDs. +// A view without an ID is known by its diagram type; repeated views of any type require authored IDs. export const viewIdOf = graph => graph?.meta?.viewId ?? graph?.meta?.diagramType ?? 'architecture'; export const architectureViewOf = graph => graph?.meta?.architectureView ?? 'relations'; export const isArchitectureOverview = graph => (graph?.meta?.diagramType ?? 'architecture') === 'architecture' && architectureViewOf(graph) !== 'relations'; diff --git a/skills/q-flow/assets/viewer/src/visual-style.js b/skills/q-flow/assets/viewer/src/visual-style.js index d88e48f..3d609c0 100644 --- a/skills/q-flow/assets/viewer/src/visual-style.js +++ b/skills/q-flow/assets/viewer/src/visual-style.js @@ -109,7 +109,7 @@ const STATE_TONE_LABELS = { goal: 'Core state', ended: 'Ended state', failed: 'F // Text never follows either: titles stay ink. A failure keeps its red frame over any module. A state in a state // diagram wears its lifecycle tone instead of the module's frame and wash; the ring and the module's lines stay. export function nodeAppearance(node, palette, moduleColors) { - if (node.overviewText !== undefined || node.badges !== undefined || node.overviewTone !== undefined) return overviewAppearance(node, palette); + if (node.overviewText !== undefined || node.overviewTone !== undefined) return overviewAppearance(node, palette); const tone = moduleColors?.get(node.module); const stateRole = node.kind === 'state' ? moduleColors?.stateTones?.get(node.id) : undefined; if (stateRole) { diff --git a/skills/q-flow/references/graph-common.md b/skills/q-flow/references/graph-common.md index 28926f9..5e3f7b7 100644 --- a/skills/q-flow/references/graph-common.md +++ b/skills/q-flow/references/graph-common.md @@ -12,7 +12,7 @@ Before Evidence, honor the user's scope, depth, required facts, node budget and Other defaults: module → components/classes; flow → steps/functions; entity set → tables. Preserve type semantics: sequence nodes are lifelines, calls are messages. Keep peers at comparable levels; show broader context as boundaries/external participants. Record level, coverage and exclusions in `meta.scope`. If a strict user limit conflicts with required coverage, explain the tradeoff; never silently omit facts or invent aggregation. -Default to one graph; overview plus detail requests multiple views. Propose splits at real boundaries; honor explicit single-view requests. Repeated architecture needs unique `meta.viewId`; repeated other types need separate outputs. Together, views cover all requested facts with stable IDs and boundary handoffs. +Default to one graph; overview plus detail requests multiple views. Propose splits at real boundaries; honor explicit single-view requests. Repeated views of any type need unique `meta.viewId`. Together, views cover all requested facts with stable IDs and boundary handoffs. Before layout, map every explicit requirement to visible elements and evidence. Minimal: every element serves the question. Detailed: audit coverage at the requested depth. Report evidence gaps. Simplify during scoped authoring; never remove chosen facts to pass layout/validation. @@ -20,7 +20,7 @@ Before layout, map every explicit requirement to visible elements and evidence. - Required: `meta.title`, `meta.sourceRef`, `meta.diagramType`, non-empty `nodes`, and an `edges` array (may be empty). Optional `groups` hold boundaries. Collections: `{ "diagrams": [graph, graph] }`, 1–32 views. - `meta.locale`: user's language, `zh-CN` (default), `en`, `ru`, `pt`, `ja`, `de`, `es`. It translates only the UI: author all prose, labels and guards in that language. Keep identifiers, literal values and standard notation verbatim; samples are placeholders. -- Facts only: **no `position`, `size` or `route`**. Node `layout.rank` / `layout.order`, graph `layout.primaryPath` / `layout.participantOrder` express existing source order only. +- Facts only: **no `position`, `size` or `route`**. Node `layout.order`, graph `layout.primaryPath` / `layout.participantOrder` express source order; `layout.rank` (0, 1, …) also sets reading columns with `layout.direction: "right"`. - IDs are unique, stable and non-empty; edge `source` / `target` name nodes. ## Nodes diff --git a/skills/q-flow/references/graph-schema.md b/skills/q-flow/references/graph-schema.md index 0269baf..07ad367 100644 --- a/skills/q-flow/references/graph-schema.md +++ b/skills/q-flow/references/graph-schema.md @@ -67,7 +67,7 @@ Flowchart main paths must run top-to-bottom, with left/right branches and outsid } ``` -Use one graph by default; a standalone page has no diagram-type menu. For a requested multi-diagram viewer, wrap 1–32 graphs in `diagrams`. Other types keep a unique `meta.diagramType`; repeated architecture views require unique `meta.viewId` values. The toolbar menu follows the fixed presentation order `capabilities`, `engineering`, `relations`, `flowchart`, `sequence`, `er`, `deployment`, `class`, `state`, `usecase`, `dataflow` regardless of input order. The three architecture entries retain the `architecture` semantic type. The view menu lists the requested types vertically. +Use one graph by default; a standalone page has no diagram-type menu. For a requested multi-diagram viewer, wrap 1–32 graphs in `diagrams`. Repeated views of one type require unique `meta.viewId` values. The toolbar menu follows the fixed presentation order `capabilities`, `engineering`, `relations`, `flowchart`, `sequence`, `er`, `deployment`, `class`, `state`, `usecase`, `dataflow` regardless of input order. The three architecture entries retain the `architecture` semantic type. The view menu lists the requested types vertically. ```json { @@ -231,6 +231,8 @@ Template placement never creates ownership, relationships or evidence. Authored Architecture overviews default to `layout.overviewConnections: "within-category"`: edges only draw when their endpoints belong to the same deepest presentation section. Cross-category edges remain in JSON, source evidence and relationship details. Set `"all"` to draw all relations. Viewer and SVG/PNG export use the same projection. +Relations views may set `layout.sharedDependencies`: a non-empty list of distinct node IDs for components nearly every card depends on (configuration, data access). Edges into those nodes are presentation-only folded: they are not laid out or drawn, and each source card shows a tag `→ ` under its source line instead. The edges keep their `site`, evidence and source-drift checks, the node details list them and open each edge, and layout output restores them without a route; the shared nodes themselves are still drawn. The list is rejected outside a relations view, for unknown or repeated IDs, and when `layout.primaryPath` enters a shared node. Relations and deployment cards also draw node `badges` as tags; badges alone no longer turn a node into an overview card. Collections may repeat any diagram type (for example a long sequence split by phase); every repeated view needs a unique `meta.viewId`. + Deployment nodes may declare `layout.tier`: `external`, `application`, `infrastructure`, or `data`. Auto layout orders these tiers from top to bottom within real runtime boundaries. Without a hint, databases use data, external nodes use external, queues/caches use infrastructure and other runtime nodes use application. This hint never adds a host, service or dependency. Measured templates preserve the component dependency path, vertical workflow spine, contract hierarchy, lifecycle notation, actor/system boundary and processing stages with adjacent stores. These rules take precedence over aspect ratio and space cost. `--layout preserve` keeps valid user geometry unchanged; invalid geometry returns diagnostics. diff --git a/skills/q-flow/references/guided-intake.md b/skills/q-flow/references/guided-intake.md index b657c1c..a364f9d 100644 --- a/skills/q-flow/references/guided-intake.md +++ b/skills/q-flow/references/guided-intake.md @@ -14,7 +14,7 @@ Structure questions accept a system, module or entity set. Behaviour questions n Ask only for missing information. Never ask for type, language, granularity, graph count or CodeGraph setup merely to fill a default. Document-only output uses the current project's `docs/qgraphflow/-/`; honor a supplied directory. If no suitable project or supplied directory exists, ask only for the output location when that is all that is missing. Never output into the plugin cache. -Explicit multiple-view requests retain **every view**: keep shared subject/preferences and resolve only each view's missing scope. "Architecture and sequence, both" is not indecision; "architecture or sequence, which helps?" invites a recommendation. Default to one graph otherwise. Repeated architecture needs unique `meta.viewId`; repeated other types use separate outputs, as specified by [graph-common.md](graph-common.md#granularity). +Explicit multiple-view requests retain **every view**: keep shared subject/preferences and resolve only each view's missing scope. "Architecture and sequence, both" is not indecision; "architecture or sequence, which helps?" invites a recommendation. Default to one graph otherwise. Repeated views of any type need unique `meta.viewId`, as specified by [graph-common.md](graph-common.md#granularity). ## Repository inventory diff --git a/skills/q-flow/references/types/architecture.md b/skills/q-flow/references/types/architecture.md index 20061f3..66d5a23 100644 --- a/skills/q-flow/references/types/architecture.md +++ b/skills/q-flow/references/types/architecture.md @@ -28,7 +28,7 @@ Either overview requires non-empty `layout.sections`. Each section has a unique Optional section `text` contains paragraph strings and `source` uses the common anchor. A note requires non-empty text and no items. Nodes accept `overviewText` paragraph strings and `badges`: `{ "label": "JDK 17", "role": "version", "evidence": "document", "source": { ... } }`. Roles: `status`, `version`, `requirement`; evidence kinds and optional anchors follow common rules. Empty arrays are valid on nodes. Reference-image status/version/rules are document claims, not verified source. -Repeated architecture views require distinct `meta.viewId`; all identities must be unique, including legacy type IDs. Collections have 1–32 views; other types stay unique. Menus show capabilities/engineering/relations as independent architecture types, adding titles for repeated templates. +Repeated views of any type require distinct `meta.viewId`; all identities must be unique, including legacy type IDs. Collections have 1–32 views. Use reference bands/cards/badges. Section `tone` / node `overviewTone`: `white`, `subtle`, `blue`, `green`, `lavender`, `plain`; section `frame`: `solid`, `dashed`, `none`; grid `columns`: 1–16; row `weights`: positive numbers per item (detail/support `[2,1]`); node `overviewAccent`: boolean stripe. Use tones and grids to clarify each fictional or public model. Style is not evidence. @@ -50,7 +50,7 @@ Use reference bands/cards/badges. Section `tone` / node `overviewTone`: `white`, } ``` -For relations, omit `architectureView` and `layout.sections`. +For relations, omit `architectureView` and `layout.sections`. List components nearly every card uses in `layout.sharedDependencies`: edges into them become caller tags, kept in data. Cards show `badges`; `layout.rank` sets columns. Generation measures full text. Unlock to reorder peers within the same section/group. Details edit body/badges/sections; apply relayouts, failure keeps the draft/valid canvas, cancel discards. Save keeps order/style; switch keeps each view; reset affects only the current view. diff --git a/skills/q-flow/scripts/compile-layout.mjs b/skills/q-flow/scripts/compile-layout.mjs index 435050c..447c2fc 100644 --- a/skills/q-flow/scripts/compile-layout.mjs +++ b/skills/q-flow/scripts/compile-layout.mjs @@ -7,13 +7,13 @@ import { createHash } from 'node:crypto'; import { validateGraph, diagramTypeOf } from './validate-graph.mjs'; import { getDiagram, canvasBudgetFor } from '../assets/viewer/src/diagrams/registry.js'; import { stateSymbolX } from '../assets/viewer/src/diagrams/state.js'; -import { minimumNodeSize } from '../assets/viewer/src/layout-measure.js'; import { graphBounds, occupiedBox, visibleEdgeLabel, groupHeadingBoxes, segmentCrossesBox, createEdgeRoutes } from '../assets/viewer/src/edge-routing.js'; import { groupHeadingLayout, estimateLabelSize } from '../assets/viewer/src/text-layout.js'; import { ASPECT_SLACK, LAYOUT_LIMITS, LAYOUT_TARGETS, OVERVIEW_AREA, layeredDirections, layeredDown, layoutLimits, layoutTargets, ratioExcess } from '../assets/viewer/src/layout-spacing.js'; import { auditLayoutQuality, qualityFailure, requireDiagramQuality } from '../assets/viewer/src/layout-quality.js'; import { compileSequence } from './compile-sequence.mjs'; -import { templateDraft, templateOf } from '../assets/viewer/src/layout-templates.js'; +import { layoutNodeSize, templateDraft, templateOf } from '../assets/viewer/src/layout-templates.js'; +import { hasSharedDependencies, presentationGraph, restorePresentation } from '../assets/viewer/src/presentation-graph.js'; import { LAYOUT_VERSION } from '../assets/viewer/src/layout-policy.js'; export { LAYOUT_VERSION }; @@ -109,7 +109,7 @@ function elkInput(graph, candidate, hints = {}) { 'elk.nodeSize.constraints': 'MINIMUM_SIZE', 'elk.nodeSize.minimum': `(${heading.width + 64},0)` } }]; })); const ordered = items => hints.nodes ? [...items].sort((a, b) => hints.nodes.indexOf(a.id) - hints.nodes.indexOf(b.id)) : stable(items); - const nodes = new Map(ordered(graph.nodes).map(node => [node.id, { id: `n:${node.id}`, ...minimumNodeSize(node, type, graph.meta.locale), ports: [], layoutOptions: { 'elk.portConstraints': 'FIXED_POS', ...(node.layout?.rank === undefined ? {} : { 'elk.partitioning.partition': String(node.layout.rank) }) } }])); + const nodes = new Map(ordered(graph.nodes).map(node => [node.id, { id: `n:${node.id}`, ...layoutNodeSize(node, graph, type), ports: [], layoutOptions: { 'elk.portConstraints': 'FIXED_POS', ...(node.layout?.rank === undefined ? {} : { 'elk.partitioning.partition': String(node.layout.rank) }) } }])); if (type === 'state') for (const node of graph.nodes) { if (node.kind === 'initial' || node.kind === 'final') nodes.get(node.id).layoutOptions['elk.layered.layering.layerConstraint'] = node.kind === 'initial' ? 'FIRST_SEPARATE' : 'LAST_SEPARATE'; if (node.kind === 'initial') for (const edge of graph.edges.filter(edge => edge.source === node.id)) { @@ -432,6 +432,12 @@ export async function compileGraphLayout(input, { layout = 'auto', timeoutMs = L try { output = fitArchitectureOverview(graph, requireDiagramQuality); } catch (error) { throw error.diagnostics ? error : Object.assign(qualityFailure(graph, 'geometry', error.message), { routingReport: error.routingReport }); } return { graph: output, report: { version: LAYOUT_VERSION, mode: layout, template: { structure: templateOf(graph).structure, applied: true, fallback: null }, refinement: overviewLayoutReports.get(output), semantics: semanticReport(output) } }; } + // Shared dependencies: lay out the drawn graph (folded edges out, their tags on source cards), then restore the model. + if (hasSharedDependencies(graph)) { + const { graph: laid, report } = await compileGraphLayout(presentationGraph(graph), { layout, timeoutMs }); + const output = restorePresentation(graph, laid); + return { graph: output, report: { ...report, semantics: semanticReport(output) } }; + } const sequence = getDiagram(diagramTypeOf(graph)).sequence; const worker = new Worker(new URL('../assets/layout-dist/worker.mjs', import.meta.url), { execArgv: [] }); let pending, expired = false; diff --git a/skills/q-flow/scripts/composition-review.test.mjs b/skills/q-flow/scripts/composition-review.test.mjs index 15db0b5..582322a 100644 --- a/skills/q-flow/scripts/composition-review.test.mjs +++ b/skills/q-flow/scripts/composition-review.test.mjs @@ -6,6 +6,8 @@ import { spawnSync } from 'node:child_process'; import test from 'node:test'; import { reviewComposition, validateGraphInput } from './validate-graph.mjs'; import { compileViews } from './generate-viewer.mjs'; +import { compileGraphLayout } from './compile-layout.mjs'; +import { requireDiagramQuality } from '../assets/viewer/src/layout-quality.js'; const script = path.join(import.meta.dirname, 'validate-graph.mjs'); const skillDir = path.join(import.meta.dirname, '..'); @@ -178,3 +180,63 @@ test('the authoring pages and the skill carry the card-identity rules the review assert.match(read('SKILL.md'), /never rename a module for colour/); assert.match(read('references/graph-common.md'), /never renamed for colour/); }); + +test('a collection may hold several views of one type when each names itself, and each gets its own SVG', t => { + const phase = (viewId, offset) => ({ ...longSequence(3, 4), meta: { ...meta('sequence'), ...(viewId ? { viewId } : {}), title: `phase ${offset}` } }); + assert.deepEqual(validateGraphInput({ diagrams: [phase(undefined, 1), phase(undefined, 2)] }, { inputOnly: true }), [ + 'diagrams[0].meta.viewId is required for repeated sequence views', + 'diagrams[1].meta.viewId is required for repeated sequence views', + 'diagrams[1].meta.viewId duplicates sequence' + ]); + const collection = { diagrams: [phase('order', 1), phase('callback', 2)] }; + assert.deepEqual(validateGraphInput(collection, { inputOnly: true }), []); + const output = fs.mkdtempSync(path.join(os.tmpdir(), 'qgraphflow-repeated-')); + t.after(() => fs.rmSync(output, { recursive: true, force: true })); + const result = spawnSync(process.execPath, [path.join(skillDir, 'scripts/generate-viewer.mjs'), temp(t, collection), output, '--force'], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(fs.readdirSync(output).filter(name => name.endsWith('.svg')).sort(), ['diagram-1-sequence.svg', 'diagram-2-sequence.svg']); +}); + +test('authored ranks lay a relations view out in reading columns from left to right', async () => { + const node = (id, rank, kind = 'component') => ({ id, label: id, kind, module: 'mq', layout: { rank } }); + const graph = { meta: meta('architecture'), layout: { direction: 'right' }, + nodes: [node('order-api', 0, 'service'), node('notify-service', 0), node('queue', 1, 'data'), node('notify-consumer', 2), node('reissue-consumer', 2)], + edges: [['order-api', 'queue'], ['notify-service', 'queue'], ['queue', 'notify-consumer'], ['queue', 'reissue-consumer']].map(([source, target], i) => ({ id: `e${i}`, source, target, kind: 'data', label: 'send', evidence: 'inference' })) }; + const { graph: laid } = await compileGraphLayout(graph); + requireDiagramQuality(laid); + const column = rank => laid.nodes.filter(item => item.layout.rank === rank).map(item => [item.position.x, item.position.x + item.size.width]); + for (const rank of [0, 1]) assert.ok(Math.max(...column(rank).map(([, right]) => right)) < Math.min(...column(rank + 1).map(([left]) => left)), `column ${rank} ends before column ${rank + 1} starts`); +}); + +const hubGraph = () => ({ meta: meta('architecture'), layout: { sharedDependencies: ['config'] }, + nodes: [ + { id: 'api', label: 'Order API', kind: 'service', module: 'order', badges: [{ label: 'v2', role: 'version', evidence: 'document' }] }, + { id: 'worker', label: 'Notify worker', kind: 'component', module: 'order' }, + { id: 'config', label: 'Config service', kind: 'config', module: 'platform' }, + { id: 'store', label: 'Order store', kind: 'database', module: 'platform' }], + edges: [['api', 'worker', 'call'], ['worker', 'store', 'data'], ['api', 'config', 'call'], ['worker', 'config', 'call']] + .map(([source, target, kind], i) => ({ id: `e${i}`, source, target, kind, label: 'uses', evidence: 'inference' })) }); + +test('shared dependencies are only for relations views, name real nodes and never sit inside a primary path', () => { + const errors = graph => validateGraphInput(graph, { inputOnly: true }); + assert.deepEqual(errors(hubGraph()), []); + assert.match(errors({ ...hubGraph(), layout: { sharedDependencies: ['missing'] } }).join('\n'), /sharedDependencies must be a non-empty list of distinct node IDs/); + assert.match(errors({ ...hubGraph(), layout: { sharedDependencies: ['config'], primaryPath: ['api', 'config'] } }).join('\n'), /primaryPath cannot enter a shared dependency/); + const flow = { meta: meta('flowchart'), layout: { sharedDependencies: ['a'] }, nodes: [{ id: 'a', label: 'A', kind: 'start' }, { id: 'b', label: 'B', kind: 'end' }], edges: [{ id: 'f', source: 'a', target: 'b', kind: 'flow', evidence: 'inference' }] }; + assert.match(errors(flow).join('\n'), /sharedDependencies requires an architecture relations view/); +}); + +test('folded shared dependencies keep every edge in the model and draw as tags on the source cards', async () => { + const { createDiagramSvg } = await import('../assets/viewer/src/export-svg.js'); + const { graph } = await compileGraphLayout(hubGraph()); + requireDiagramQuality(graph); + assert.deepEqual(graph.edges.map(edge => edge.id), ['e0', 'e1', 'e2', 'e3'], 'no edge is dropped'); + for (const id of ['e2', 'e3']) assert.equal(graph.edges.find(edge => edge.id === id).route, undefined, `${id} is folded, not drawn`); + for (const id of ['e0', 'e1']) assert.ok(graph.edges.find(edge => edge.id === id).route, `${id} stays a line`); + assert.deepEqual(graph.layout.sharedDependencies, ['config']); + assert.ok(graph.nodes.every(node => node.dependencyTags === undefined), 'display tags never reach the saved model'); + const svg = createDiagramSvg(graph); + assert.equal(svg.match(/→ Config service/g)?.length, 2, 'both callers carry the tag'); + assert.match(svg, />v2 { + const { jeepay } = await import('../../../tests/jeepay.mjs'); + const { templateDraft, layoutNodeSize } = await import('../assets/viewer/src/layout-templates.js'); + const { routeOrthogonal } = await import('../assets/viewer/src/orthogonal-routing.js'); + const graph = jeepay('state'); delete graph.layout; + graph.nodes.push({ id: 'refund', label: 'REFUND', kind: 'state', module: 'payment' }, { id: 'cancel', label: 'CANCEL', kind: 'state', module: 'payment' }); + graph.edges.push({ id: 's6', source: 'success', target: 'refund', kind: 'transition', label: '退款单成功', evidence: 'source', guard: '累计退款 ≥ 订单金额', action: 'refund_state=2' }, + { id: 's7', source: 'success', target: 'success', kind: 'transition', label: '退款单成功', evidence: 'source', guard: 'refund_amount + 本次 < amount', action: 'refund_state=1,refund_times+1,累加 refund_amount' }); + const success = graph.nodes.find(node => node.id === 'success'); + assert.ok(layoutNodeSize(success, graph).height > minimumNodeSize(success, 'state').height, 'a long loop label makes its state taller than its text needs'); + for (let variant = 0; variant < 4; variant++) assert.doesNotThrow(() => routeOrthogonal(templateDraft(graph, variant), { passes: 3, accept: requireDiagramQuality }), `template variant ${variant}`); +}); From 0a61ba20ffa414df5ba82f63020e4bb664dd368b Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 08:55:20 +0800 Subject: [PATCH 03/16] =?UTF-8?q?docs(skill):=20=E8=A6=81=E6=B1=82?= =?UTF-8?q?=E7=9A=84=E5=9B=BE=E6=8C=89=E4=B8=BB=E9=A2=98=E7=90=86=E8=A7=A3?= =?UTF-8?q?=EF=BC=8C=E8=B6=85=E8=BF=87=2012=20=E8=8A=82=E7=82=B9=E3=80=814?= =?UTF-8?q?=20=E6=A0=8F=E3=80=8120=20=E6=9D=A1=E6=B6=88=E6=81=AF=E6=88=96?= =?UTF-8?q?=204=20=E5=B1=8F=E6=97=B6=E5=9C=A8=E5=90=8C=E4=B8=80=E5=90=88?= =?UTF-8?q?=E9=9B=86=E9=87=8C=E6=8B=86=E6=88=90=E5=90=8C=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E8=A7=86=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/q-flow/SKILL.md | 2 +- skills/q-flow/references/graph-common.md | 6 +++--- skills/q-flow/references/guided-intake.md | 2 +- skills/q-flow/references/types/sequence.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index e713e1f..5d7426a 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -47,7 +47,7 @@ node scripts/validate-graph.mjs "/graph.json" --repo- - Execute the scripts; do not read them, the bundled HTML, the Viewer source or tests. `--help` lists every option. Failures report elements, rule, measurement and remediation; `--verbose` prints the receipt. - On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and moved anchors, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. -- Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: split into same-type views or fold shared dependencies; keep requested detail and graph count. A failing collection names every failing view. +- Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: split into same-type views or fold shared dependencies; keep requested detail and topics. A failing collection names every failing view. - If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. Generation defaults to `--layout auto`; `--layout preserve` keeps existing geometry under the same gate. - For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local files (existence, line range, symbol) and report `sourceEvidence` with `relations` coverage. Generation records `meta.sourceFiles`: moved lines pass, changed code fails as drift. Neither proves a claim. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. - Outputs are `index.html`, `graph.json` and one SVG per view (`diagram.svg`, or `diagram--.svg` in a collection), built from the prebuilt viewer; no rebuild or install. Use `--force` only with approval to replace the named outputs. All collection views must pass before replacing output. diff --git a/skills/q-flow/references/graph-common.md b/skills/q-flow/references/graph-common.md index 5e3f7b7..517b52b 100644 --- a/skills/q-flow/references/graph-common.md +++ b/skills/q-flow/references/graph-common.md @@ -4,15 +4,15 @@ Read this and `types/.md` for authoring; `graph-schema.md` is for m ## Granularity -Before Evidence, honor the user's scope, depth, required facts, node budget and view count. Minimal styling does not reduce content; "minimal styling, every call" keeps every requested call. +Before Evidence, honor the user's scope, depth, required facts, node budget and topics. Minimal styling does not reduce content; "minimal styling, every call" keeps every requested call. -- **Default system overview:** for system/repository architecture, use business modules (monolith) or services (distributed), one level below the system, plus relevant callers, external systems and shared infrastructure. Aim for **8–12 visible nodes**; **over 15** prompts review of real domain boundaries or a proposed split. Soft targets only: never pad small systems or drop necessary nodes. +- **Default system overview:** for system/repository architecture, use business modules (monolith) or services (distributed), one level below the system, plus relevant callers, external systems and shared infrastructure. Aim for **8–12 visible nodes**. Soft targets only: never pad small systems or drop necessary nodes. - **Minimal:** use the fewest elements that answer the question. Aggregate real modules/responsibilities only; retain required dependencies, boundaries, decisions and outcomes. Put supporting explanation in `facts`. State aggregation/exclusions in `meta.scope`; never turn an indirect path into a direct-call claim. An explicit success-path-only request may exclude failure paths. - **Detailed:** follow the requested depth; if unspecified, expand relevant units one level beyond the default. Include in-scope branches, errors, retries, guards, calls, fields or members as the type requires. Overview/type size suggestions do not cap detail. Requested topology must be visible, not only in `facts` or notes. Other defaults: module → components/classes; flow → steps/functions; entity set → tables. Preserve type semantics: sequence nodes are lifelines, calls are messages. Keep peers at comparable levels; show broader context as boundaries/external participants. Record level, coverage and exclusions in `meta.scope`. If a strict user limit conflicts with required coverage, explain the tradeoff; never silently omit facts or invent aggregation. -Default to one graph; overview plus detail requests multiple views. Propose splits at real boundaries; honor explicit single-view requests. Repeated views of any type need unique `meta.viewId`. Together, views cover all requested facts with stable IDs and boundary handoffs. +A requested diagram is a topic: past 12 nodes, 4 columns, 20 messages or 4 screens, split at real boundaries (sync/async, phases) into same-type views in one collection unless told not to. Overview plus detail requests multiple views. Repeated views need unique `meta.viewId`. Together, views cover all requested facts with stable IDs and boundary handoffs. Before layout, map every explicit requirement to visible elements and evidence. Minimal: every element serves the question. Detailed: audit coverage at the requested depth. Report evidence gaps. Simplify during scoped authoring; never remove chosen facts to pass layout/validation. diff --git a/skills/q-flow/references/guided-intake.md b/skills/q-flow/references/guided-intake.md index a364f9d..31e2098 100644 --- a/skills/q-flow/references/guided-intake.md +++ b/skills/q-flow/references/guided-intake.md @@ -77,4 +77,4 @@ Apply [Granularity](graph-common.md#granularity), including when intake is skipp After scope is ready, determine the evidence path using [evidence-sources.md](evidence-sources.md#codegraph-preflight). A directory alone never proves CodeGraph availability. Use document evidence for document-only work; report CodeGraph only after checking the tool and current index, otherwise direct tracing. If not checked yet, say evidence preflight is pending rather than claiming either tool was used. -Give one compact recap covering all requested views, subject/question, granularity/coverage, output directory and the actual evidence status, then start without another confirmation. Do not present internal schema fields as questions for the user. If bounded layout fails, report the blockers and propose views covering the original facts; never silently reduce detail or change an explicit graph count. +Give one compact recap covering all requested views, subject/question, granularity/coverage, output directory and the actual evidence status, then start without another confirmation. Do not present internal schema fields as questions for the user. If bounded layout fails, report the blockers and propose views covering the original facts; never silently reduce detail or drop a requested topic. diff --git a/skills/q-flow/references/types/sequence.md b/skills/q-flow/references/types/sequence.md index 234953b..b18a12c 100644 --- a/skills/q-flow/references/types/sequence.md +++ b/skills/q-flow/references/types/sequence.md @@ -10,7 +10,7 @@ Calls and returns along one flow, with activation bars and fragments. Read with - One node per lifeline: `actor` for the human or caller, `service` / `participant` for code you read, `external` for systems outside the repository, `database` for a store. Participants never have `groupId`. - Left-to-right order follows first appearance in the messages; `layout.participantOrder` (all ids, once) only reproduces an existing convention. -- 8 participants / 20 messages is advisory; user detail wins. Follow common splitting rules. +- Over 8 participants / 20 messages: split by phase into sequence views; keep every message. ## Messages (edges) From 99329a6f9f693b5a2ac75c6794367f134ca7bf2f Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 09:39:31 +0800 Subject: [PATCH 04/16] =?UTF-8?q?perf(sequence):=20=E5=80=99=E9=80=89?= =?UTF-8?q?=E9=97=B4=E8=B7=9D=E4=BB=8E=E9=97=A8=E7=A6=81=E4=B8=8B=E9=99=90?= =?UTF-8?q?=E8=B5=B7=E6=AD=A5=EF=BC=8C=E8=B7=A8=E5=AE=BD=E9=97=B4=E9=9A=99?= =?UTF-8?q?=E7=9A=84=E6=B6=88=E6=81=AF=E6=A0=87=E7=AD=BE=E5=B0=91=E6=8D=A2?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/q-flow/assets/viewer-dist/index.html | 4 +-- .../q-flow/assets/viewer/src/edge-routing.js | 10 ++++++-- skills/q-flow/scripts/compile-sequence.mjs | 3 ++- .../scripts/sequence-execution.test.mjs | 25 +++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index 1173dfa..1fbb468 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -275,9 +275,9 @@ ${t}.entity-meta{font:500 ${X.small}px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;fill:${e.ink2}} ${t}.member{font:500 ${X.body}px ui-monospace,monospace;fill:${e.ink2}} ${t}.field-type{font:400 ${X.body}px ui-monospace,monospace;fill:${e.ink3}} -`}function Xp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return em(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+xp.pad,v=g+xp.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*xp.chipLine;return`${Q(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>Q(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>Q(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>Q(v,b+14+t*f.lineHeight,e,`meta`)).join(``),E={x:g+xp.pad,y:_+(xp.titleLine-xp.plate)/2},D=t+e.size.width-c-xp.pad-p.width-l;return`${Zp(e,t,n,r,i,s)}${Qp(e,E.x,E.y,xp.plate,a)}${Q(D+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}var Zp=(e,t,n,r,i,a)=>Ip(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Qp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:Yf(e)?i.accent:Jf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${$p(e)}`}var $p=e=>Jf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function em(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Zp(e,t,n,r,i,s)}${Qp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,wp(e,o).text,`stereotype`)}${d}${f}`}var tm=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],nm=[[.08,0],[1,0],[.92,1],[0,1]];function rm(e,t,n){let{width:r,height:i}=e.size;if(Cg(e))return Lp(e,t,n,16);if(e.kind===`external`)return Bp(e,t,n,zp);if(e.kind===`security`)return Lp(e,t,n,22);if(e.kind===`failure`)return Bp(e,t,n,tm);if(e.kind===`config`)return Bp(e,t,n,nm);if(e.kind===`business`)return Lp(e,t,n,Math.min(28,i/2));let a=Lp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var im=(e,t,n)=>Cg(e)?Gp(e,t,n,16):e.kind===`external`?qp(e,t,n,zp):e.kind===`security`?Gp(e,t,n,22):e.kind===`failure`?qp(e,t,n,tm):e.kind===`config`?qp(e,t,n,nm):e.kind===`business`?Gp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):Wp(e,t,n),am=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,om={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Cg(e)?Mg(e,t,n,a,r,i):Xp(e,t,n,r,i,a,o,rm,am(e)),outline:rm,anchor:im,cardLayout:!0,contentInset:am},sm=.12,cm=(e,t,n)=>e.kind===`decision`?Vp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*sm},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Lp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),lm=(e,t,n)=>e.kind===`decision`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?qp(e,t,n,[[sm,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Gp(e,t,n,e.size.height/2):Wp(e,t,n),um=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*sm+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function dm(e,t,n,r,i){let{width:a,height:o}=e.size,s=um(e),c=Fp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Ip(cm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var fm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:dm,outline:cm,anchor:lm,textArea:um,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},pm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n):Lp(e,t,n,7,mm(e));function mm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function hm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=mm(e),u=Ip(pm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,up[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Np([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var gm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:hm,outline:pm,sequence:!0,selectionHeight:mm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},_m=(e,t,n)=>Lp(e,t,n,9);function vm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=dp(e),u=Pp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,Pp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,Pp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Ip(_m(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,Pp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var ym={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:vm,outline:_m,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},bm=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function xm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Bp(e,t,n,bm),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Lp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`external`?Bp(e,t,n,zp):e.kind===`service`?Lp(e,t,n,16):Lp(e,t,n,10)}var Sm=(e,t,n)=>e.kind===`device`?Wp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?qp(e,t,n,bm):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?qp(e,t,n,zp):e.kind===`service`?Gp(e,t,n,16):Wp(e,t,n),Cm=e=>({container:24,artifact:18,node:20})[e.kind]??0,wm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Tm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Xp(e,...t,xm,wm(e),Cm(e)),outline:xm,anchor:Sm,cardLayout:!0,contentInset:wm,cardCorner:Cm},Em=(e,t,n)=>Lp(e,t,n,9);function Dm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=dp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``);return`${Ip(Em(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),Pp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,Pp(e.subtitle,m),`body`):``}${h}${g}`}var Om={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:Dm,outline:Em,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=kp(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},km=e=>e.subtitle?14:e.size.width/2,Am=[`entry`,`do`,`exit`],jm={side:16,pad:8,line:20,keyWidth:64};function Mm(e){let t=e.kind===`state`?Am.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*jm.side-jm.keyWidth,X.small,jm.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*jm.line+2*jm.pad:0}}var Nm=2*jm.side+jm.keyWidth,Pm=e=>{let{height:t}=Mm(e);return t?{x:jm.side,y:e.size.height-t,width:e.size.width-2*jm.side,height:t}:null},Fm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+km(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Vp(e,t,n):Lp(e,t,n,12),Im=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=km(e)-e.size.width/2;return Kp({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Wp(e,t,n)},Lm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=Mm(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Rm(e,t,n,r,i){let{rows:a,height:o}=Mm(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+jm.pad+c++*jm.line+15;return(r?``:Q(t+jm.side,a,`${e.key} /`,`field-key`))+Q(t+jm.side+jm.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function zm(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Lm(e),o=e.kind===`final`;return`${Ip(Fm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Fp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Lm(e),l=n+(e.size.height-Mm(e).height)/2;return`${Ip(Fm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,l,e.label,c.width,c.height,e.subtitle)}${Rm(e,t,n,i,a)}`}var Bm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Vm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:zm,outline:Fm,anchor:Im,textArea:Lm,activityArea:Pm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Bm(e).map(e=>e.text).join(` `),edgeLabelParts:Bm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Am)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},Hm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Um=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Wm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n+Hm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Gm=(e,t,n)=>e.kind===`actor`?Jp(e,t,n,Hm(e)):Kp(e,t,n);function Km(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+Hm(e)+98,Pp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+Hm(e)+122,Pp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Um(e);return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var qm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Km,outline:Wm,anchor:Gm,textArea:Um,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Jm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Lp(e,t,n,e.kind===`process`?24:10),Ym=e=>({width:e.size.width-32,height:e.size.height-20});function Xm(e,t,n,r,i){let a=Ym(e);return`${Ip(Jm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Zm=[om,fm,gm,ym,Tm,Om,Vm,qm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Xm,outline:Jm,textArea:Ym,anchor:(e,t,n)=>e.kind===`process`?Gp(e,t,n,24):Wp(e,t,n)}],Qm=Zm.map(e=>e.id);Object.fromEntries(Zm.map(e=>[e.id,e.label]));var $m=new Map(Zm.map(e=>[e.id,e]));if($m.size!==Zm.length)throw Error(`Duplicate diagram type`);var eh=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>$m.get(e),th=(e,t,n,r=!1)=>t===`architecture`&&Cg(e)?Tg(e):Tp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),nh=e=>{let t=eh(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=th(n,t,e.meta?.locale).minHeight)},rh=(e,t)=>!($(t).undirected??[]).includes(e.kind),ih=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),ah=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),oh=(e,t)=>({start:null,end:rh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),sh=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ch=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),lh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var uh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,dh=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),fh=(e,t)=>e?.id??String(t);function ph(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(fh(i,t))}`);return n}function mh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===fh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>mh(e,t,n,r,a)))]}function hh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>fh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=fh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=mh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function gh(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function _h(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>gh(n,t)-gh(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var vh=e=>Z(e.label,Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function yh(e,t){let n={...e.position,...e.size},r=vh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>uh(e,t,4)))}function bh(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...dh(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>uh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:fh(null,0)}]}}function xh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;uh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=yh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=bh(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===fh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=mh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...dh(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Df.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1mh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...dh(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...dh(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${fh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Df.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>uh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=fh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${fh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function Sh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function Ch(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wh(e,t,n=Ch(e),r=ph(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Th=140,Eh=54,Dh=(e,t)=>(e.route?.messageY??Th+e.order*Eh)+(t===`receive`&&e.source===e.target?30:0);function Oh(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Dh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ph(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Dh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Dh(n.get(i.end.edgeId),i.end.at)-l}})}function Ah(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var jh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Mh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Nh(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ph(e,t=Yh(e)){e=Tf(e);let n=[...bg(e),...e.groups??[],...e.nodes,...kh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Nh(n.sourceCardinality,e.points[0],e.points[1]),Nh(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Fh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=jh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Ih(e,t,n=Ef.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Lh(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Rh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function zh(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Bh(e,t,n,r){let i={clearance:-1,length:-1,point:zh(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Vh(e,t){let n=jh(e),r=jh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Hh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?tg(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Ih(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Rh(f,e);return Rh(f,Ih(t,r,a)),f.push(t),Lh(f)}function Wh(e,t,n,r,i,a=Ef.endpoint,o=`architecture`){let s=Fh(e,n.sourceSide,r,o),c=Fh(t,n.targetSide,i,o),l=Ih(s,n.sourceSide,a),u=Ih(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Lh([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Lh([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Gh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Kh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var qh=(e,t=0,n=0)=>e.curved&&Kh(e,t,n)||Gh(e.points,t,n);function Jh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Dh(e,`send`),u=Dh(e,`receive`),d=Ah(o,t.id,e,`send`,l,s.get(e.id)),f=Ah(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||jh(t).x<=jh(n).x,m=d?d.x+(p?d.width:0):jh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):jh(n).x,g=wh(a,e,c,s),_=Dp(g,t.id===n.id?Df.labelWidth:Math.min(Df.labelWidth,Math.max(1,Math.abs(h-m)-32-12))),v={width:_.width,height:_.height};if(t.id===n.id){let t=48+r*Ef.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Uh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:_.lines,labelSize:v,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+v.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Uh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:_.lines,labelSize:v,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-v.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Yh(e){e=Tf(e);let t=eh(e),n=$(t).endpointStub??Ef.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Vh(t,n)}}),a=t===`sequence`?{graph:e,executions:kh(e),scopes:ph(e),pairs:Ch(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?jh(i).y:jh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*Ef.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Zh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,mm(e))}:{...e.position,...e.size}}function Qh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function $h(e,t,n,r){let i=tg(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=jh(t),o=Fh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function eg(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&eg(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=jh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Fh(n,`left`,o,r).x,c=Fh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Fh(n,`top`,o,r).y,c=Fh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function sg(e){e=Tf(e);let t=eh(e),n=[],r=Yh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...kh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightuh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!nh(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:xp.minHeight))continue;let{minHeight:r}=t===`architecture`&&Cg(n)?Tg(n):Tp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;eEf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${Ef.endpoint}px`);let f=og(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!$h(i.points[0],a,i.sourceSide,t)||!$h(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Ih(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(jh(a).x-jh(o).x),t=Math.max(160,i.labelBox.width+32);eXh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),rg(t).some(([e,t])=>eg(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Xh(i.labelBox,tg(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=rg(r);for(let i=1;ieg(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ag(a,o,e,t)>Ef.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var cg=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),lg=(e,t,n)=>Math.max(t,Math.min(n,e)),ug=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=lg(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function dg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(ug(e,n,r),ug(t,n,r),ug(n,e,t),ug(r,e,t))}function fg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function pg(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function mg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:lg(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:lg((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>ug({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>dg(e,t,r,n[(i+1)%n.length])))}var gg=new WeakMap;function _g(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=gg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Hm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,ug({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>dg(e,a,t,n)),...i.map(t=>fg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>mg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>hg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,ug({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>pg(e,t,c);else{let n=s===`rect`?c:tg(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,fg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),fg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},gg.set(e,{signature:n,probe:l}),l}function vg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return rg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function yg(e,t,n=[]){let r=new Set(n),i=eh(t),a=cg(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Zh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Yh(e),d=kf($(i)).labelGap,f=[...o.map(e=>Zh(e,i)),...l.flatMap(ig)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>eg(r,e,t))||l.some(n=>vg(r,e,n).distanceeg(r,e,t)))}))&&r.add(n.id)}return r}var bg=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},xg=e=>e&&typeof e==`object`&&!Array.isArray(e),Sg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Cg=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function wg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!zf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{xg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Sg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!xg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!xg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Sg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!xg(e.position)||!xg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Sg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!xg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Tg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Eg=e=>e.frame===`none`?0:Y.padding,Dg=(e,t)=>{let n=t-Eg(e)*2;return Eg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Og(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Eg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function kg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=bg(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Ag=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),jg=(e,t,n,r,i=``)=>`${Ag(n)}`;function Mg(e,t,n,r){let i=Hf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Tg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>jg(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>jg(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ng(e,t,n=0,r=0){let i=Hf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Eg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>jg(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>jg(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function Pg(e,t=new Map){if(!ff(e))return[];let n=[],r=bg(e);for(let t of r){let r=Dg(t,t.size.width)+Eg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Eg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Eg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Og(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Fg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=ip(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Ip(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` +`}function Xp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return em(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+xp.pad,v=g+xp.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*xp.chipLine;return`${Q(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>Q(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>Q(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>Q(v,b+14+t*f.lineHeight,e,`meta`)).join(``),E={x:g+xp.pad,y:_+(xp.titleLine-xp.plate)/2},D=t+e.size.width-c-xp.pad-p.width-l;return`${Zp(e,t,n,r,i,s)}${Qp(e,E.x,E.y,xp.plate,a)}${Q(D+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}var Zp=(e,t,n,r,i,a)=>Ip(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Qp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:Yf(e)?i.accent:Jf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${$p(e)}`}var $p=e=>Jf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function em(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Zp(e,t,n,r,i,s)}${Qp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,wp(e,o).text,`stereotype`)}${d}${f}`}var tm=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],nm=[[.08,0],[1,0],[.92,1],[0,1]];function rm(e,t,n){let{width:r,height:i}=e.size;if(Cg(e))return Lp(e,t,n,16);if(e.kind===`external`)return Bp(e,t,n,zp);if(e.kind===`security`)return Lp(e,t,n,22);if(e.kind===`failure`)return Bp(e,t,n,tm);if(e.kind===`config`)return Bp(e,t,n,nm);if(e.kind===`business`)return Lp(e,t,n,Math.min(28,i/2));let a=Lp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var im=(e,t,n)=>Cg(e)?Gp(e,t,n,16):e.kind===`external`?qp(e,t,n,zp):e.kind===`security`?Gp(e,t,n,22):e.kind===`failure`?qp(e,t,n,tm):e.kind===`config`?qp(e,t,n,nm):e.kind===`business`?Gp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):Wp(e,t,n),am=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,om={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Cg(e)?Mg(e,t,n,a,r,i):Xp(e,t,n,r,i,a,o,rm,am(e)),outline:rm,anchor:im,cardLayout:!0,contentInset:am},sm=.12,cm=(e,t,n)=>e.kind===`decision`?Vp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*sm},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Lp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),lm=(e,t,n)=>e.kind===`decision`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?qp(e,t,n,[[sm,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Gp(e,t,n,e.size.height/2):Wp(e,t,n),um=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*sm+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function dm(e,t,n,r,i){let{width:a,height:o}=e.size,s=um(e),c=Fp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Ip(cm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var fm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:dm,outline:cm,anchor:lm,textArea:um,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},pm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n):Lp(e,t,n,7,mm(e));function mm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function hm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=mm(e),u=Ip(pm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,up[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Np([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var gm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:hm,outline:pm,sequence:!0,selectionHeight:mm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},_m=(e,t,n)=>Lp(e,t,n,9);function vm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=dp(e),u=Pp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,Pp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,Pp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Ip(_m(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,Pp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var ym={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:vm,outline:_m,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},bm=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function xm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Bp(e,t,n,bm),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Lp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`external`?Bp(e,t,n,zp):e.kind===`service`?Lp(e,t,n,16):Lp(e,t,n,10)}var Sm=(e,t,n)=>e.kind===`device`?Wp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?qp(e,t,n,bm):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?qp(e,t,n,zp):e.kind===`service`?Gp(e,t,n,16):Wp(e,t,n),Cm=e=>({container:24,artifact:18,node:20})[e.kind]??0,wm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Tm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Xp(e,...t,xm,wm(e),Cm(e)),outline:xm,anchor:Sm,cardLayout:!0,contentInset:wm,cardCorner:Cm},Em=(e,t,n)=>Lp(e,t,n,9);function Dm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=dp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``);return`${Ip(Em(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),Pp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,Pp(e.subtitle,m),`body`):``}${h}${g}`}var Om={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:Dm,outline:Em,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=kp(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},km=e=>e.subtitle?14:e.size.width/2,Am=[`entry`,`do`,`exit`],jm={side:16,pad:8,line:20,keyWidth:64};function Mm(e){let t=e.kind===`state`?Am.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*jm.side-jm.keyWidth,X.small,jm.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*jm.line+2*jm.pad:0}}var Nm=2*jm.side+jm.keyWidth,Pm=e=>{let{height:t}=Mm(e);return t?{x:jm.side,y:e.size.height-t,width:e.size.width-2*jm.side,height:t}:null},Fm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+km(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Vp(e,t,n):Lp(e,t,n,12),Im=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=km(e)-e.size.width/2;return Kp({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Wp(e,t,n)},Lm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=Mm(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Rm(e,t,n,r,i){let{rows:a,height:o}=Mm(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+jm.pad+c++*jm.line+15;return(r?``:Q(t+jm.side,a,`${e.key} /`,`field-key`))+Q(t+jm.side+jm.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function zm(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Lm(e),o=e.kind===`final`;return`${Ip(Fm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Fp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Lm(e),l=n+(e.size.height-Mm(e).height)/2;return`${Ip(Fm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,l,e.label,c.width,c.height,e.subtitle)}${Rm(e,t,n,i,a)}`}var Bm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Vm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:zm,outline:Fm,anchor:Im,textArea:Lm,activityArea:Pm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Bm(e).map(e=>e.text).join(` `),edgeLabelParts:Bm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Am)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},Hm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Um=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Wm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n+Hm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Gm=(e,t,n)=>e.kind===`actor`?Jp(e,t,n,Hm(e)):Kp(e,t,n);function Km(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+Hm(e)+98,Pp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+Hm(e)+122,Pp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Um(e);return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var qm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Km,outline:Wm,anchor:Gm,textArea:Um,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Jm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Lp(e,t,n,e.kind===`process`?24:10),Ym=e=>({width:e.size.width-32,height:e.size.height-20});function Xm(e,t,n,r,i){let a=Ym(e);return`${Ip(Jm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Zm=[om,fm,gm,ym,Tm,Om,Vm,qm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Xm,outline:Jm,textArea:Ym,anchor:(e,t,n)=>e.kind===`process`?Gp(e,t,n,24):Wp(e,t,n)}],Qm=Zm.map(e=>e.id);Object.fromEntries(Zm.map(e=>[e.id,e.label]));var $m=new Map(Zm.map(e=>[e.id,e]));if($m.size!==Zm.length)throw Error(`Duplicate diagram type`);var eh=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>$m.get(e),th=(e,t,n,r=!1)=>t===`architecture`&&Cg(e)?Tg(e):Tp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),nh=e=>{let t=eh(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=th(n,t,e.meta?.locale).minHeight)},rh=(e,t)=>!($(t).undirected??[]).includes(e.kind),ih=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),ah=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),oh=(e,t)=>({start:null,end:rh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),sh=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ch=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),lh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var uh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,dh=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),fh=(e,t)=>e?.id??String(t);function ph(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(fh(i,t))}`);return n}function mh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===fh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>mh(e,t,n,r,a)))]}function hh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>fh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=fh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=mh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function gh(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function _h(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>gh(n,t)-gh(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var vh=e=>Z(e.label,Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function yh(e,t){let n={...e.position,...e.size},r=vh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>uh(e,t,4)))}function bh(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...dh(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>uh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:fh(null,0)}]}}function xh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;uh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=yh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=bh(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===fh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=mh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...dh(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Df.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1mh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...dh(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...dh(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${fh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Df.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>uh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=fh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${fh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function Sh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function Ch(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wh(e,t,n=Ch(e),r=ph(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Th=140,Eh=54,Dh=(e,t)=>(e.route?.messageY??Th+e.order*Eh)+(t===`receive`&&e.source===e.target?30:0);function Oh(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Dh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ph(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Dh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Dh(n.get(i.end.edgeId),i.end.at)-l}})}function Ah(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var jh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Mh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Nh(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ph(e,t=Yh(e)){e=Tf(e);let n=[...bg(e),...e.groups??[],...e.nodes,...kh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Nh(n.sourceCardinality,e.points[0],e.points[1]),Nh(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Fh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=jh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Ih(e,t,n=Ef.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Lh(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Rh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function zh(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Bh(e,t,n,r){let i={clearance:-1,length:-1,point:zh(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Vh(e,t){let n=jh(e),r=jh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Hh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?tg(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Ih(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Rh(f,e);return Rh(f,Ih(t,r,a)),f.push(t),Lh(f)}function Wh(e,t,n,r,i,a=Ef.endpoint,o=`architecture`){let s=Fh(e,n.sourceSide,r,o),c=Fh(t,n.targetSide,i,o),l=Ih(s,n.sourceSide,a),u=Ih(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Lh([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Lh([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Gh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Kh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var qh=(e,t=0,n=0)=>e.curved&&Kh(e,t,n)||Gh(e.points,t,n);function Jh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Dh(e,`send`),u=Dh(e,`receive`),d=Ah(o,t.id,e,`send`,l,s.get(e.id)),f=Ah(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||jh(t).x<=jh(n).x,m=d?d.x+(p?d.width:0):jh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):jh(n).x,g=wh(a,e,c,s),_=Math.abs(h-m),v=Dp(g,t.id===n.id?Df.labelWidth:Math.min(Df.labelWidth,Math.max(1,_-32-12))),y=t.id===n.id?null:Dp(g,Math.max(1,_-64)),b=y&&(e.route?.labelAt??{x:(m+h)/2,y:l-6-y.height/2}),x=y&&y.lines.lengthuh({x:b.x-y.width/2,y:b.y-y.height/2,width:y.width,height:y.height},e,2))?y:v,S={width:x.width,height:x.height};if(t.id===n.id){let t=48+r*Ef.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Uh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+S.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Uh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-S.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Yh(e){e=Tf(e);let t=eh(e),n=$(t).endpointStub??Ef.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Vh(t,n)}}),a=t===`sequence`?{graph:e,executions:kh(e),scopes:ph(e),pairs:Ch(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?jh(i).y:jh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*Ef.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Zh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,mm(e))}:{...e.position,...e.size}}function Qh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function $h(e,t,n,r){let i=tg(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=jh(t),o=Fh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function eg(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&eg(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=jh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Fh(n,`left`,o,r).x,c=Fh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Fh(n,`top`,o,r).y,c=Fh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function sg(e){e=Tf(e);let t=eh(e),n=[],r=Yh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...kh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightuh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!nh(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:xp.minHeight))continue;let{minHeight:r}=t===`architecture`&&Cg(n)?Tg(n):Tp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;eEf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${Ef.endpoint}px`);let f=og(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!$h(i.points[0],a,i.sourceSide,t)||!$h(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Ih(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(jh(a).x-jh(o).x),t=Math.max(160,i.labelBox.width+32);eXh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),rg(t).some(([e,t])=>eg(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Xh(i.labelBox,tg(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=rg(r);for(let i=1;ieg(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ag(a,o,e,t)>Ef.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var cg=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),lg=(e,t,n)=>Math.max(t,Math.min(n,e)),ug=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=lg(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function dg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(ug(e,n,r),ug(t,n,r),ug(n,e,t),ug(r,e,t))}function fg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function pg(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function mg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:lg(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:lg((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>ug({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>dg(e,t,r,n[(i+1)%n.length])))}var gg=new WeakMap;function _g(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=gg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Hm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,ug({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>dg(e,a,t,n)),...i.map(t=>fg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>mg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>hg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,ug({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>pg(e,t,c);else{let n=s===`rect`?c:tg(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,fg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),fg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},gg.set(e,{signature:n,probe:l}),l}function vg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return rg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function yg(e,t,n=[]){let r=new Set(n),i=eh(t),a=cg(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Zh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Yh(e),d=kf($(i)).labelGap,f=[...o.map(e=>Zh(e,i)),...l.flatMap(ig)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>eg(r,e,t))||l.some(n=>vg(r,e,n).distanceeg(r,e,t)))}))&&r.add(n.id)}return r}var bg=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},xg=e=>e&&typeof e==`object`&&!Array.isArray(e),Sg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Cg=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function wg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!zf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{xg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Sg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!xg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!xg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Sg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!xg(e.position)||!xg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Sg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!xg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Tg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Eg=e=>e.frame===`none`?0:Y.padding,Dg=(e,t)=>{let n=t-Eg(e)*2;return Eg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Og(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Eg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function kg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=bg(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Ag=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),jg=(e,t,n,r,i=``)=>`${Ag(n)}`;function Mg(e,t,n,r){let i=Hf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Tg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>jg(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>jg(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ng(e,t,n=0,r=0){let i=Hf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Eg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>jg(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>jg(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function Pg(e,t=new Map){if(!ff(e))return[];let n=[],r=bg(e);for(let t of r){let r=Dg(t,t.size.width)+Eg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Eg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Eg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Og(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Fg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=ip(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Ip(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` `);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}function zg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Bg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(zg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Vg({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` -`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function ee(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function w(e){if(!x(e))return{...e,edges:ee(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:ee(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function T(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=w(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,Math.abs(_-g)-32-12))),b={width:y.width,height:y.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:y.lines,labelSize:b,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+b.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:y.lines,labelSize:b,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-b.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=w(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=w(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,ee=Math.max(...b.map(e=>e.x+e.width))+x,w=Math.min(...b.map(e=>e.y))-S,T=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,ee].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[w,T].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),ee=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},ee(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=T(r,Rn(w(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=T(e,Rn(w(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),ee=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),w=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),T={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,T.x,T.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${ee}${w}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],ee=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),w=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),T=Math.max(s.nodeGap,Math.min(ee+2*o.labelGap,240),w)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+T,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*T,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+T,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t){let n=structuredClone(e),r=n.groups??[],i=new Map(n.edges.map(e=>[e.id,e])),a=new Map;for(let e of[...n.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])a.has(t)||a.set(t,a.size);let o=(n.layout?.participantOrder??[...n.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||(a.get(e.id)??1/0)-(a.get(t.id)??1/0)||(e.ide.id)).map(e=>n.nodes.find(t=>t.id===e)),s=32+t*8,c=12+t*4,l=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,u=(e,t)=>A(l(e,t),f.labelWidth,14,20),p=e=>A(e.body,f.labelWidth,16,24),m=32;for(let e of o)e.size=Hr(e,`sequence`,n.meta.locale),e.position={x:m,y:48},m+=e.size.width+s;Tt(n,o);for(let e of n.edges)e.route={messageY:200+e.order*100};let h=H(n),g=Ot(n),_=new Set(r.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),v=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).order),y=e=>e.edge?e.edge.order:Math.min(1/0,...v(e.group)),b=e=>e.sort((e,t)=>y(e)-y(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>h.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),S=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=r.find(e=>e.id===n.parentId)){t.add(n.id);let e=x(n);if(e.length)return e}return[...h.values()].flatMap(e=>e.points)};for(let e of[...r].sort((e,t)=>vt(t,r)-vt(e,r)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=S(e),n=r.filter(t=>t.parentId===e.id),a=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[u(e,t).width,p(t).width])),s=e.operands.flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).route.messageY),c=Math.min(...s),l=Math.max(...s),d=g.filter(e=>!s.length||e.y<=l&&e.y+e.height>=c).sort((e,t)=>e.x-t.x),f=t.length?Math.min(...t.map(e=>e.x)):o[0].position.x,m=Math.min(f,...d.filter(e=>e.x=f-8).map(e=>e.x))-a-40,h=Math.min(m,...n.map(e=>e.position.x-32)),_=Math.max(h+a+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of d)e.x<_+8&&e.x+e.width>_-56-16&&(_=Math.max(_,e.x+e.width+56));e.position={x:h,y:0},e.size={width:Math.ceil(_-h),height:0}}function C(e,t){let n=h.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+c}function ee(e,t){for(let n of b(e))t=n.edge?C(n.edge,t):w(n.group,t);return t}function w(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+c;for(let[t,a]of e.operands.entries()){n+=u(e,a).height+16,a.body&&(n+=p(a).height+16);let o=r.filter(n=>n.parentId===e.id&&n.parentOperandId===z(a,t));n=ee([...a.edgeIds.map(e=>({edge:i.get(e)})),...o.map(e=>({group:e}))],n),n+=c}return e.size.height=n-t+16,t+e.size.height+c}let T=ee([...n.edges.filter(e=>!_.has(e.id)).map(e=>({edge:e})),...r.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...o.map(Ke))+d.labelGap),E=[...n.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...o.map(e=>e.position.x)));for(let e of[...o,...r])e.position.x+=te;for(let e of n.nodes)e.size.height=T+32-e.position.y;return n}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=w(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:w(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` +`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t){let n=structuredClone(e),r=n.groups??[],i=new Map(n.edges.map(e=>[e.id,e])),a=new Map;for(let e of[...n.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])a.has(t)||a.set(t,a.size);let o=(n.layout?.participantOrder??[...n.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||(a.get(e.id)??1/0)-(a.get(t.id)??1/0)||(e.ide.id)).map(e=>n.nodes.find(t=>t.id===e)),s=d.nodeGap+t*8,c=12+t*4,l=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,u=(e,t)=>A(l(e,t),f.labelWidth,14,20),p=e=>A(e.body,f.labelWidth,16,24),m=32;for(let e of o)e.size=Hr(e,`sequence`,n.meta.locale),e.position={x:m,y:48},m+=e.size.width+s;Tt(n,o);for(let e of n.edges)e.route={messageY:200+e.order*100};let h=H(n),g=Ot(n),_=new Set(r.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),v=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).order),y=e=>e.edge?e.edge.order:Math.min(1/0,...v(e.group)),b=e=>e.sort((e,t)=>y(e)-y(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>h.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),S=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=r.find(e=>e.id===n.parentId)){t.add(n.id);let e=x(n);if(e.length)return e}return[...h.values()].flatMap(e=>e.points)};for(let e of[...r].sort((e,t)=>vt(t,r)-vt(e,r)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=S(e),n=r.filter(t=>t.parentId===e.id),a=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[u(e,t).width,p(t).width])),s=e.operands.flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).route.messageY),c=Math.min(...s),l=Math.max(...s),d=g.filter(e=>!s.length||e.y<=l&&e.y+e.height>=c).sort((e,t)=>e.x-t.x),f=t.length?Math.min(...t.map(e=>e.x)):o[0].position.x,m=Math.min(f,...d.filter(e=>e.x=f-8).map(e=>e.x))-a-40,h=Math.min(m,...n.map(e=>e.position.x-32)),_=Math.max(h+a+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of d)e.x<_+8&&e.x+e.width>_-56-16&&(_=Math.max(_,e.x+e.width+56));e.position={x:h,y:0},e.size={width:Math.ceil(_-h),height:0}}function C(e,t){let n=h.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+c}function w(e,t){for(let n of b(e))t=n.edge?C(n.edge,t):T(n.group,t);return t}function T(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+c;for(let[t,a]of e.operands.entries()){n+=u(e,a).height+16,a.body&&(n+=p(a).height+16);let o=r.filter(n=>n.parentId===e.id&&n.parentOperandId===z(a,t));n=w([...a.edgeIds.map(e=>({edge:i.get(e)})),...o.map(e=>({group:e}))],n),n+=c}return e.size.height=n-t+16,t+e.size.height+c}let ee=w([...n.edges.filter(e=>!_.has(e.id)).map(e=>({edge:e})),...r.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...o.map(Ke))+d.labelGap),E=[...n.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...o.map(e=>e.position.x)));for(let e of[...o,...r])e.position.x+=te;for(let e of n.nodes)e.size.height=ee+32-e.position.y;return n}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` - `)?String(n).split(` - `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function x_(e,t={}){let n=m_(e,{inputOnly:!0}),r=n.length?[]:m_(e,{audit:!1}),i=n.length||r.length?null:S_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw b_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` - `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function S_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(i_(t)>=i_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)__(d,g_(e))||s(`group.member-inset`,[i.id,e.id],g_(e),d,[o,g_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&v_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,g_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=y_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[g_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(g_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function C_(e){return function(){return e}}var w_=1664525,T_=1013904223,E_=4294967296;function D_(){let e=1;return()=>(e=(w_*e+T_)%E_)/E_}var O_=10,k_=Math.PI*(3-Math.sqrt(5));function A_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=D_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function j_(e){var t=C_(.1),n,r,i;typeof e!=`function`&&(e=C_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),P_=e=>e.members.map(e=>e.kind),F_=(e,t)=>P_(e).some(e=>t.includes(e)),I_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function L_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(N_))}function R_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function z_(e,t){let n=L_(e,t.edges);return n.length===1&&e.length>5?R_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||N_(e,t)))}function B_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(N_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(N_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function V_(e,t){let n=t.layout?.primaryPath??[],r=L_(e,B_(t));return r.length===1&&e.length>5?R_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||N_(e,t)}))}function H_(e,t){let n=[...e].sort((e,n)=>I_(n,t.edges)-I_(e,t.edges)||N_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return R_(r)}function U_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(i_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>L_(e,t.edges))}function W_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=L_(r,n),o=L_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>F_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function G_(e,t){let n=e.filter(e=>F_(e,[`initial`])),r=e.filter(e=>F_(e,[`final`]));return[n,...L_(e.filter(e=>!n.includes(e)&&!r.includes(e)),B_(t)),r].filter(e=>e.length)}function K_(e,t,n=0){let r=e.filter(e=>F_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(N_),i.sort(N_)].filter(e=>e.length):n>=2?i.sort(N_).map(e=>[e]):H_(i,t)}function q_(e,t){let n=e.filter(e=>F_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=L_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(N_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:z_},flowchart:{structure:`workflow-spine`,arrange:V_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:H_},deployment:{structure:`runtime-tiers`,arrange:U_},class:{structure:`contract-hierarchy`,arrange:W_},state:{structure:`lifecycle-branches`,arrange:G_},usecase:{structure:`actor-system`,arrange:K_},dataflow:{structure:`process-store`,arrange:q_}});function J_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Y_=156,X_=160,Z_=(e,t,n)=>Math.max(t,Math.min(n,e));function Q_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function $_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function ev(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Y_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Y_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Y_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Y_))}}function tv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function nv(e,t=null){if(!t)try{return x_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=Q_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=ev(t,$_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=A_(o).velocityDecay(.42).force(`anchor-x`,j_(e=>e.anchorX).strength(.16)).force(`anchor-y`,M_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,tv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:Z_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Y_),e.position.x+Y_),y:r?e.position.y:Z_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Y_),e.position.y+Y_)};return t.bounds&&(n.x=Z_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=Z_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!J_(e,d))throw Error(`Arrange would invert template bands`);x_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var rv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function iv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;rv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function ov(e,t,n){let r=av(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function sv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function cv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var lv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]);function uv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var dv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,fv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function pv(e,t){if(!dv.test(e))throw Error(`page has no graph-data element`);return e.replace(dv,(e,n,r,i)=>`${n}${fv(t)}${i}`)}function mv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function hv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function gv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function _v(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function vv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return x_(_v(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function yv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(qg(e,a)),[l,u]=Dd(Jg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:iv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>hv(_,o,l),[_,o,l]),x=e=>{v(e),s(qg(e,a)),u(Jg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new $g,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:b_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(gv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return x_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return x_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=_v(i,vv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=n_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&uv(a,lv(e),av(i,o,s))||lo(a,i.clientWidth,i.clientHeight,.08,2,ov(i,o,s));return g(c,{duration:n,ease:iv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:iv});return}let i=p.current;if(!i)return;let o=av(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=cv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:iv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(qg(r,a)),u(Jg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=nv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function bv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function xv(e,t){return e.map(e=>({node:e,rank:bv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Sv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?xv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function Cv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&bv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function wv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Tv(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Ev(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Dv(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function Ov(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var kv={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function Av(e,t,n,r,i){let a=e.map(e=>Z(e,i-kv.indent,X.body,kv.line)),o=r+kv.top+kv.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+kv.indent,t+r*kv.line,e,`body`)).join(``);return o+=e.length*kv.line+kv.gap,r}).join(``);return{height:o-r+kv.bottom,svg:`${Q(n,r+kv.top,bf(t,`Key points`),`group`)}${s}`}}function jv(e,t=`light`,n){x_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?Av(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Dv(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>Ov(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Mv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:jv(e,`light`,r)}))}function Nv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Pv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Fv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=pv(await(await s.getFile()).text(),e),l;try{l=Mv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Pv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Iv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw b_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw b_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Lv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Pv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function Rv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=jv(e,t,i),s=`${Nv(e.meta.title)}.${n}`;await Iv(o,e),n===`svg`?Pv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Lv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function zv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=yv(e,s,d,i),[m,h]=o,g=m&&!s,_=wv(d,()=>p.readGraph(p.currentGraph,0)),v=Sv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=Cv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await Rv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Fv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Bv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Vv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=sv(p,av(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:iv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:iv})},[e,r,n,t,i,a,o])}var Hv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Uv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Hv[e]})}function Wv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` diff --git a/skills/q-flow/assets/viewer/src/edge-routing.js b/skills/q-flow/assets/viewer/src/edge-routing.js index aee39df..86922d3 100644 --- a/skills/q-flow/assets/viewer/src/edge-routing.js +++ b/skills/q-flow/assets/viewer/src/edge-routing.js @@ -227,8 +227,14 @@ function routeSequenceEdge(edge, source, target, selfIndex, context) { const sourceX = sourceExecution ? sourceExecution.x + (forward ? sourceExecution.width : 0) : center(source).x; const targetX = targetExecution ? targetExecution.x + (source.id === target.id || !forward ? targetExecution.width : 0) : center(target).x; const label = sequenceMessageLabel(graph, edge, pairs, scopes); - const available = source.id === target.id ? LAYOUT_TARGETS.labelWidth : Math.min(LAYOUT_TARGETS.labelWidth, Math.max(1, Math.abs(targetX - sourceX) - 32 - 12)); - const layout = edgeLabelLayout(label, available); + const span = Math.abs(targetX - sourceX); + const narrow = edgeLabelLayout(label, source.id === target.id ? LAYOUT_TARGETS.labelWidth : Math.min(LAYOUT_TARGETS.labelWidth, Math.max(1, span - 32 - 12))); + // Spacing reserves a 320px label; a message across a wider gap uses that room when it saves lines and still passes the + // participant-gap and label-execution checks below, so stored layouts stay valid. + const wide = source.id === target.id ? null : edgeLabelLayout(label, Math.max(1, span - 64)); + const wideAt = wide && (edge.route?.labelAt ?? { x: (sourceX + targetX) / 2, y: y - 6 - wide.height / 2 }); + const layout = wide && wide.lines.length < narrow.lines.length && wide.width + 32 <= Math.abs(center(target).x - center(source).x) + && !executions.some(bar => intersects({ x: wideAt.x - wide.width / 2, y: wideAt.y - wide.height / 2, width: wide.width, height: wide.height }, bar, 2)) ? wide : narrow; const labelSize = { width: layout.width, height: layout.height }; if (source.id === target.id) { const extent = 48 + selfIndex * LAYOUT_LIMITS.parallelGap; diff --git a/skills/q-flow/scripts/compile-sequence.mjs b/skills/q-flow/scripts/compile-sequence.mjs index 65c4bbd..a2fa1cc 100644 --- a/skills/q-flow/scripts/compile-sequence.mjs +++ b/skills/q-flow/scripts/compile-sequence.mjs @@ -13,7 +13,8 @@ export function compileSequence(input, candidate) { for (const edge of [...graph.edges].sort((a, b) => a.order - b.order)) for (const id of [edge.source, edge.target]) if (!firstSeen.has(id)) firstSeen.set(id, firstSeen.size); const ordered = graph.layout?.participantOrder ?? [...graph.nodes].sort((a, b) => (a.layout?.order ?? 0) - (b.layout?.order ?? 0) || (firstSeen.get(a.id) ?? Infinity) - (firstSeen.get(b.id) ?? Infinity) || (a.id < b.id ? -1 : 1)).map(node => node.id); const nodes = ordered.map(id => graph.nodes.find(node => node.id === id)); - const spacing = 32 + candidate * 8, gap = 12 + candidate * 4; + // Participant spacing starts at the quality floor, so the tightest message gap is not discarded with a too-narrow row. + const spacing = LAYOUT_LIMITS.nodeGap + candidate * 8, gap = 12 + candidate * 4; const guardText = (group, operand) => group.kind === 'par' ? operand.label : `${group.kind === 'loop' ? `${group.loop.min}..${group.loop.max} ` : ''}[${operand.guard}]`; const guardLayout = (group, operand) => layoutText(guardText(group, operand), LAYOUT_TARGETS.labelWidth, 14, 20); const bodyLayout = operand => layoutText(operand.body, LAYOUT_TARGETS.labelWidth, 16, 24); diff --git a/skills/q-flow/scripts/sequence-execution.test.mjs b/skills/q-flow/scripts/sequence-execution.test.mjs index 2163ee3..2b79426 100644 --- a/skills/q-flow/scripts/sequence-execution.test.mjs +++ b/skills/q-flow/scripts/sequence-execution.test.mjs @@ -9,6 +9,8 @@ import { createDiagramSvg } from '../assets/viewer/src/export-svg.js'; import { PALETTES, sequenceGroupColor, edgeColor } from '../assets/viewer/src/visual-style.js'; import { currentGraphFromFlow, graphInputWithEdits } from '../assets/viewer/src/session-graph.js'; import { isDashed } from '../assets/viewer/src/diagrams/registry.js'; +import { edgeLabelLayout } from '../assets/viewer/src/text-layout.js'; +import { compileGraphLayout } from './compile-layout.mjs'; test('fragments with and without operands share crossing checks and the final heading obstacle', () => { @@ -67,3 +69,26 @@ test('pair numbers follow message order even when call ids sort differently as s assert.equal(pairs.get('m2').label, 'C1'); assert.equal(pairs.get('m3').label, '↩ C1'); assert.equal(pairs.get('m12').label, 'C2'); assert.equal(pairs.get('m13').label, '↩ C2'); }); + +test('a message across a wide idle gap uses it; a bar under the wide label keeps the reserved width', () => { + const label = 'chargeAccount(merchantNo, appId, wayCode, amount): create the order'; + const graph = { meta: { title: 'Wide gap', sourceRef: 'test', diagramType: 'sequence', locale: 'en' }, + nodes: [['a', 100], ['b', 900], ['c', 1100]].map(([id, x]) => ({ id, label: id, kind: 'service', position: { x, y: 0 }, size: { width: 120, height: 600 } })), + edges: [ + { id: 'e1', source: 'a', target: 'b', kind: 'sync', label: 'start()', order: 1, evidence: 'test', route: { messageY: 200 } }, + { id: 'e2', source: 'a', target: 'c', kind: 'async', label, order: 2, evidence: 'test', route: { messageY: 320 } }, + { id: 'e3', source: 'b', target: 'a', kind: 'return', label: 'ok', order: 3, replyTo: 'e1', evidence: 'test', route: { messageY: 440 } }] }; + const reserved = edgeLabelLayout(`02 · ${label}`, 320).lines.length; + assert.ok(reserved > 1, 'The reserved width wraps this label.'); + assert.equal(createEdgeRoutes(graph).get('e2').labelLines.length, 1, 'An idle wide gap holds the label on one line.'); + graph.executions = [{ id: 'b-work', participantId: 'b', start: { edgeId: 'e1', at: 'receive' }, end: { edgeId: 'e3', at: 'send' } }]; + assert.equal(createEdgeRoutes(graph).get('e2').labelLines.length, reserved, 'A bar under the wide label keeps the reserved wrap.'); +}); + +test('the tightest message gap is kept when participants need only the minimum spacing', async () => { + const graph = { meta: { title: 'Compact', sourceRef: 'test', diagramType: 'sequence', locale: 'en' }, + nodes: ['a', 'b', 'c'].map(id => ({ id, label: id, kind: 'service' })), + edges: [['a', 'b'], ['b', 'c'], ['c', 'a']].map(([source, target], i) => ({ id: `m${i}`, source, target, kind: 'async', label: `m${i}()`, order: i + 1, evidence: 'test' })) }; + const { graph: output } = await compileGraphLayout(graph); + assert.equal(output.layout.strategy, 'sequence-0'); +}); From 52cd1cc5d53bb729693a7699aee7218b06c91837 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 10:01:44 +0800 Subject: [PATCH 05/16] =?UTF-8?q?fix(viewer):=20=E6=97=B6=E5=BA=8F?= =?UTF-8?q?=E5=9B=BE=E5=8F=AA=E5=9C=A8=E9=98=85=E8=AF=BB=E5=80=8D=E7=8E=87?= =?UTF-8?q?=E8=83=BD=E6=95=B4=E5=9B=BE=E6=94=BE=E4=B8=8B=E6=97=B6=E6=89=8D?= =?UTF-8?q?=E6=95=B4=E5=9B=BE=E6=89=93=E5=BC=80=EF=BC=8C=E5=90=A6=E5=88=99?= =?UTF-8?q?=E4=BB=8E=E9=A1=B6=E9=83=A8=E6=8C=89=E9=98=85=E8=AF=BB=E5=80=8D?= =?UTF-8?q?=E7=8E=87=E6=89=93=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/q-flow/assets/viewer-dist/index.html | 4 ++-- skills/q-flow/assets/viewer/src/features/useGraphLayout.js | 4 ++-- skills/q-flow/assets/viewer/src/reading-area.js | 3 +++ skills/q-flow/scripts/generate-viewer.test.mjs | 3 ++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index 1fbb468..0d8711f 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -280,9 +280,9 @@ `)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t){let n=structuredClone(e),r=n.groups??[],i=new Map(n.edges.map(e=>[e.id,e])),a=new Map;for(let e of[...n.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])a.has(t)||a.set(t,a.size);let o=(n.layout?.participantOrder??[...n.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||(a.get(e.id)??1/0)-(a.get(t.id)??1/0)||(e.ide.id)).map(e=>n.nodes.find(t=>t.id===e)),s=d.nodeGap+t*8,c=12+t*4,l=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,u=(e,t)=>A(l(e,t),f.labelWidth,14,20),p=e=>A(e.body,f.labelWidth,16,24),m=32;for(let e of o)e.size=Hr(e,`sequence`,n.meta.locale),e.position={x:m,y:48},m+=e.size.width+s;Tt(n,o);for(let e of n.edges)e.route={messageY:200+e.order*100};let h=H(n),g=Ot(n),_=new Set(r.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),v=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).order),y=e=>e.edge?e.edge.order:Math.min(1/0,...v(e.group)),b=e=>e.sort((e,t)=>y(e)-y(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>h.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),S=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=r.find(e=>e.id===n.parentId)){t.add(n.id);let e=x(n);if(e.length)return e}return[...h.values()].flatMap(e=>e.points)};for(let e of[...r].sort((e,t)=>vt(t,r)-vt(e,r)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=S(e),n=r.filter(t=>t.parentId===e.id),a=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[u(e,t).width,p(t).width])),s=e.operands.flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).route.messageY),c=Math.min(...s),l=Math.max(...s),d=g.filter(e=>!s.length||e.y<=l&&e.y+e.height>=c).sort((e,t)=>e.x-t.x),f=t.length?Math.min(...t.map(e=>e.x)):o[0].position.x,m=Math.min(f,...d.filter(e=>e.x=f-8).map(e=>e.x))-a-40,h=Math.min(m,...n.map(e=>e.position.x-32)),_=Math.max(h+a+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of d)e.x<_+8&&e.x+e.width>_-56-16&&(_=Math.max(_,e.x+e.width+56));e.position={x:h,y:0},e.size={width:Math.ceil(_-h),height:0}}function C(e,t){let n=h.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+c}function w(e,t){for(let n of b(e))t=n.edge?C(n.edge,t):T(n.group,t);return t}function T(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+c;for(let[t,a]of e.operands.entries()){n+=u(e,a).height+16,a.body&&(n+=p(a).height+16);let o=r.filter(n=>n.parentId===e.id&&n.parentOperandId===z(a,t));n=w([...a.edgeIds.map(e=>({edge:i.get(e)})),...o.map(e=>({group:e}))],n),n+=c}return e.size.height=n-t+16,t+e.size.height+c}let ee=w([...n.edges.filter(e=>!_.has(e.id)).map(e=>({edge:e})),...r.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...o.map(Ke))+d.labelGap),E=[...n.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...o.map(e=>e.position.x)));for(let e of[...o,...r])e.position.x+=te;for(let e of n.nodes)e.size.height=ee+32-e.position.y;return n}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` - `)?String(n).split(` - `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function x_(e,t={}){let n=m_(e,{inputOnly:!0}),r=n.length?[]:m_(e,{audit:!1}),i=n.length||r.length?null:S_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw b_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` -- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function S_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(i_(t)>=i_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)__(d,g_(e))||s(`group.member-inset`,[i.id,e.id],g_(e),d,[o,g_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&v_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,g_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=y_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[g_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(g_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function C_(e){return function(){return e}}var w_=1664525,T_=1013904223,E_=4294967296;function D_(){let e=1;return()=>(e=(w_*e+T_)%E_)/E_}var O_=10,k_=Math.PI*(3-Math.sqrt(5));function A_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=D_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function j_(e){var t=C_(.1),n,r,i;typeof e!=`function`&&(e=C_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),P_=e=>e.members.map(e=>e.kind),F_=(e,t)=>P_(e).some(e=>t.includes(e)),I_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function L_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(N_))}function R_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function z_(e,t){let n=L_(e,t.edges);return n.length===1&&e.length>5?R_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||N_(e,t)))}function B_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(N_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(N_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function V_(e,t){let n=t.layout?.primaryPath??[],r=L_(e,B_(t));return r.length===1&&e.length>5?R_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||N_(e,t)}))}function H_(e,t){let n=[...e].sort((e,n)=>I_(n,t.edges)-I_(e,t.edges)||N_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return R_(r)}function U_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(i_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>L_(e,t.edges))}function W_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=L_(r,n),o=L_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>F_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function G_(e,t){let n=e.filter(e=>F_(e,[`initial`])),r=e.filter(e=>F_(e,[`final`]));return[n,...L_(e.filter(e=>!n.includes(e)&&!r.includes(e)),B_(t)),r].filter(e=>e.length)}function K_(e,t,n=0){let r=e.filter(e=>F_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(N_),i.sort(N_)].filter(e=>e.length):n>=2?i.sort(N_).map(e=>[e]):H_(i,t)}function q_(e,t){let n=e.filter(e=>F_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=L_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(N_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:z_},flowchart:{structure:`workflow-spine`,arrange:V_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:H_},deployment:{structure:`runtime-tiers`,arrange:U_},class:{structure:`contract-hierarchy`,arrange:W_},state:{structure:`lifecycle-branches`,arrange:G_},usecase:{structure:`actor-system`,arrange:K_},dataflow:{structure:`process-store`,arrange:q_}});function J_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Y_=156,X_=160,Z_=(e,t,n)=>Math.max(t,Math.min(n,e));function Q_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function $_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function ev(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Y_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Y_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Y_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Y_))}}function tv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function nv(e,t=null){if(!t)try{return x_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=Q_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=ev(t,$_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=A_(o).velocityDecay(.42).force(`anchor-x`,j_(e=>e.anchorX).strength(.16)).force(`anchor-y`,M_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,tv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:Z_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Y_),e.position.x+Y_),y:r?e.position.y:Z_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Y_),e.position.y+Y_)};return t.bounds&&(n.x=Z_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=Z_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!J_(e,d))throw Error(`Arrange would invert template bands`);x_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var rv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function iv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;rv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function ov(e,t,n){let r=av(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function sv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function cv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var lv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]);function uv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var dv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,fv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function pv(e,t){if(!dv.test(e))throw Error(`page has no graph-data element`);return e.replace(dv,(e,n,r,i)=>`${n}${fv(t)}${i}`)}function mv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function hv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function gv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function _v(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function vv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return x_(_v(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function yv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(qg(e,a)),[l,u]=Dd(Jg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:iv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>hv(_,o,l),[_,o,l]),x=e=>{v(e),s(qg(e,a)),u(Jg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new $g,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:b_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(gv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return x_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return x_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=_v(i,vv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=n_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&uv(a,lv(e),av(i,o,s))||lo(a,i.clientWidth,i.clientHeight,.08,2,ov(i,o,s));return g(c,{duration:n,ease:iv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:iv});return}let i=p.current;if(!i)return;let o=av(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=cv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:iv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(qg(r,a)),u(Jg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=nv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function bv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function xv(e,t){return e.map(e=>({node:e,rank:bv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Sv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?xv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function Cv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&bv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function wv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Tv(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Ev(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Dv(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function Ov(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var kv={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function Av(e,t,n,r,i){let a=e.map(e=>Z(e,i-kv.indent,X.body,kv.line)),o=r+kv.top+kv.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+kv.indent,t+r*kv.line,e,`body`)).join(``);return o+=e.length*kv.line+kv.gap,r}).join(``);return{height:o-r+kv.bottom,svg:`${Q(n,r+kv.top,bf(t,`Key points`),`group`)}${s}`}}function jv(e,t=`light`,n){x_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?Av(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Dv(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>Ov(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Mv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:jv(e,`light`,r)}))}function Nv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Pv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Fv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=pv(await(await s.getFile()).text(),e),l;try{l=Mv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Pv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Iv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw b_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw b_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Lv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Pv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function Rv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=jv(e,t,i),s=`${Nv(e.meta.title)}.${n}`;await Iv(o,e),n===`svg`?Pv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Lv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function zv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=yv(e,s,d,i),[m,h]=o,g=m&&!s,_=wv(d,()=>p.readGraph(p.currentGraph,0)),v=Sv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=Cv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await Rv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Fv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Bv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Vv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=sv(p,av(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:iv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:iv})},[e,r,n,t,i,a,o])}var Hv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Uv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Hv[e]})}function Wv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` +- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function S_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(i_(t)>=i_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)__(d,g_(e))||s(`group.member-inset`,[i.id,e.id],g_(e),d,[o,g_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&v_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,g_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=y_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[g_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(g_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function C_(e){return function(){return e}}var w_=1664525,T_=1013904223,E_=4294967296;function D_(){let e=1;return()=>(e=(w_*e+T_)%E_)/E_}var O_=10,k_=Math.PI*(3-Math.sqrt(5));function A_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=D_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function j_(e){var t=C_(.1),n,r,i;typeof e!=`function`&&(e=C_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),P_=e=>e.members.map(e=>e.kind),F_=(e,t)=>P_(e).some(e=>t.includes(e)),I_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function L_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(N_))}function R_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function z_(e,t){let n=L_(e,t.edges);return n.length===1&&e.length>5?R_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||N_(e,t)))}function B_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(N_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(N_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function V_(e,t){let n=t.layout?.primaryPath??[],r=L_(e,B_(t));return r.length===1&&e.length>5?R_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||N_(e,t)}))}function H_(e,t){let n=[...e].sort((e,n)=>I_(n,t.edges)-I_(e,t.edges)||N_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return R_(r)}function U_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(i_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>L_(e,t.edges))}function W_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=L_(r,n),o=L_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>F_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function G_(e,t){let n=e.filter(e=>F_(e,[`initial`])),r=e.filter(e=>F_(e,[`final`]));return[n,...L_(e.filter(e=>!n.includes(e)&&!r.includes(e)),B_(t)),r].filter(e=>e.length)}function K_(e,t,n=0){let r=e.filter(e=>F_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(N_),i.sort(N_)].filter(e=>e.length):n>=2?i.sort(N_).map(e=>[e]):H_(i,t)}function q_(e,t){let n=e.filter(e=>F_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=L_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(N_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:z_},flowchart:{structure:`workflow-spine`,arrange:V_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:H_},deployment:{structure:`runtime-tiers`,arrange:U_},class:{structure:`contract-hierarchy`,arrange:W_},state:{structure:`lifecycle-branches`,arrange:G_},usecase:{structure:`actor-system`,arrange:K_},dataflow:{structure:`process-store`,arrange:q_}});function J_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Y_=156,X_=160,Z_=(e,t,n)=>Math.max(t,Math.min(n,e));function Q_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function $_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function ev(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Y_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Y_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Y_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Y_))}}function tv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function nv(e,t=null){if(!t)try{return x_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=Q_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=ev(t,$_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=A_(o).velocityDecay(.42).force(`anchor-x`,j_(e=>e.anchorX).strength(.16)).force(`anchor-y`,M_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,tv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:Z_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Y_),e.position.x+Y_),y:r?e.position.y:Z_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Y_),e.position.y+Y_)};return t.bounds&&(n.x=Z_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=Z_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!J_(e,d))throw Error(`Arrange would invert template bands`);x_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var rv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function iv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;rv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function ov(e,t,n){let r=av(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function sv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function cv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var lv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]),uv=e=>e.meta?.diagramType===`sequence`?Af:jf;function dv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var fv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,pv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function mv(e,t){if(!fv.test(e))throw Error(`page has no graph-data element`);return e.replace(fv,(e,n,r,i)=>`${n}${pv(t)}${i}`)}function hv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function gv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function _v(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function vv(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function yv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return x_(vv(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function bv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(qg(e,a)),[l,u]=Dd(Jg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:iv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>gv(_,o,l),[_,o,l]),x=e=>{v(e),s(qg(e,a)),u(Jg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new $g,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:b_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(_v(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return x_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return x_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=vv(i,yv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=n_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&dv(a,lv(e),av(i,o,s),void 0,uv(e))||lo(a,i.clientWidth,i.clientHeight,.08,2,ov(i,o,s));return g(c,{duration:n,ease:iv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:iv});return}let i=p.current;if(!i)return;let o=av(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=cv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:iv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(qg(r,a)),u(Jg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=nv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function xv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function Sv(e,t){return e.map(e=>({node:e,rank:xv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Cv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?Sv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function wv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&xv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function Tv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Ev(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Dv(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Ov(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function kv(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Av={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function jv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Av.indent,X.body,Av.line)),o=r+Av.top+Av.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Av.indent,t+r*Av.line,e,`body`)).join(``);return o+=e.length*Av.line+Av.gap,r}).join(``);return{height:o-r+Av.bottom,svg:`${Q(n,r+Av.top,bf(t,`Key points`),`group`)}${s}`}}function Mv(e,t=`light`,n){x_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?jv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Ov(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>kv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Nv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:Mv(e,`light`,r)}))}function Pv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Fv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Iv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=mv(await(await s.getFile()).text(),e),l;try{l=Nv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Fv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Lv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw b_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw b_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Rv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Fv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function zv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Mv(e,t,i),s=`${Pv(e.meta.title)}.${n}`;await Lv(o,e),n===`svg`?Fv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Rv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Bv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=bv(e,s,d,i),[m,h]=o,g=m&&!s,_=Tv(d,()=>p.readGraph(p.currentGraph,0)),v=Cv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=wv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await zv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Iv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Vv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Hv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=sv(p,av(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:iv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:iv})},[e,r,n,t,i,a,o])}var Uv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Wv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Uv[e]})}function Gv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` `),badges:structuredClone(e?.badges??[]),error:``,returnFocus:t});(0,y.useEffect)(()=>{u.current++,o(),p()},[c]);let m=e=>f(t=>({...t,...e}));return{...d,section:!!e?.section,overview:l,set:m,cancel:()=>{u.current++,o(),p(!0)},begin:()=>m({editing:!0,returnFocus:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` -`),badges:structuredClone(e?.badges??[]),error:``}),save:async a=>{if(a.preventDefault(),d.pending)return;let o=d.label.trim();if(!o){m({error:bf(i,`Name is required`)});return}if(d.badges.some(e=>!e.label.trim())){m({error:bf(i,`Name is required`)});return}let s=++u.current;m({pending:!0});let c=await(t?r(t.id,o):n(e.id,o,d.subtitle.trim(),l?{overviewText:d.overviewText.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),...e.section?{}:{badges:d.badges}}:{}));if(u.current===s){if(m({pending:!1}),c){m({error:c});return}m({editing:!1,error:``})}}}}function Gv({editor:e,relation:t,locked:n,locale:r}){let i=e=>bf(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&!e.section&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),!t&&e.overview&&(0,x.jsxs)(`label`,{children:[i(`Overview text`),(0,x.jsx)(`textarea`,{disabled:e.pending,"aria-label":i(`Overview text`),value:e.overviewText,onChange:t=>e.set({overviewText:t.target.value,error:``})})]}),!t&&e.overview&&!e.section&&(0,x.jsxs)(`fieldset`,{disabled:e.pending,children:[(0,x.jsx)(`legend`,{children:i(`Badges`)}),e.badges.map((t,n)=>{let r=t=>e.set({badges:e.badges.map((e,r)=>r===n?{...e,...t}:e)});return(0,x.jsxs)(`div`,{className:`badge-editor`,children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{"aria-label":`${i(`Badges`)} ${n+1}`,value:t.label,onChange:e=>{let{source:n,...i}=t;r({...i,source:void 0,label:e.target.value,evidence:`document`})}})]}),(0,x.jsxs)(`label`,{children:[i(`Badge type`),(0,x.jsx)(`select`,{value:t.role,onChange:e=>r({role:e.target.value}),children:[`status`,`version`,`requirement`].map(e=>(0,x.jsx)(`option`,{value:e,children:i({status:`Status`,version:`Version`,requirement:`Requirement`}[e])},e))})]}),(0,x.jsxs)(`label`,{children:[i(`Evidence`),(0,x.jsx)(`select`,{value:t.evidence,onChange:e=>r({evidence:e.target.value}),children:[`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`].map(e=>(0,x.jsx)(`option`,{value:e,children:i(cp[e]??e)},e))})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:e.badges.filter((e,t)=>t!==n)}),children:i(`Remove badge`)})]},n)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:[...e.badges,{label:``,role:`status`,evidence:`document`}]}),children:i(`Add badge`)})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var Kv=292,qv=232,Jv=14;function Yv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>bf(c,e,t),_=!!t,v=_?(Yh(d).get(t.id)?.label??Mh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(qv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??qv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Zh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=av(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Jv,y:N.top},{side:`left`,x:N.left-Jv-Kv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Jv},{side:`above`,x:N.left,y:N.top-Jv-C}],F=e=>e.x>=P.left&&e.x+Kv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Zh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Yh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...dh(e)]),n=kh(d);for(let r of d.groups??[]){let i=xh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+Kv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-Kv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?lp(e.source):_&&t.site?lp(t.site):null,ae=_?op(t,r,o,s,n,Ch(d).get(t.id)):ip(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:Kv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(Uv,{name:`close`})}),u.editing?(0,x.jsx)(Gv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(up[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(cp[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(Uv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(Gv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(Uv,{name:`arrowRight`})]})]})]})]})}var Xv=[`system`,`light`,`dark`],Zv={system:`Follow system`,light:`Light`,dark:`Dark`};function Qv(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function $v({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>bf(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,onOverviewKeyDown:ie,layoutPending:ae,cancelLayout:oe,updateNodeText:se,updateEdgeText:ce,readGraph:le,focusDiagram:ue,nudgeLayout:de,visibleNodes:fe,visibleEdges:pe,reset:me,exportDiagram:he,saveGraph:ge,exportStatus:_e,layoutProblem:ve,layoutWarnings:ye,focusProblem:be,boardRef:xe,fullscreenButtonRef:Se,isFullscreen:Ce,fullscreenPending:we,fullscreenSupported:Te,toggleFullscreen:Ee,toolbarOpen:De,drawerOpen:Oe,toolbarButtonRef:ke,drawerButtonRef:Ae,searchInputRef:je,inspectorRef:Me,panelRef:Ne,toggleToolbar:Pe,toggleDrawer:Fe,openDetails:Ie}=zv(e,c,d,i,t,n,f),[Le,Re]=Qv(De,v,Ne),[ze,Be]=Qv(Oe,v,Me),Ve=(0,y.useRef)(null),He=Wv(w,T,se,ce,e.meta.locale,ff(e),oe),{open:Ue,toggle:We,close:Ge}=Bv(),Ke=e.meta.notes??[],[qe,Je]=(0,y.useState)(!0),Ye=Ke.length>0&&qe&&!ze,Xe=Oe||Ye&&!Ce,Ze=(0,y.useRef)(!1),Qe=(0,y.useRef)(null);(0,y.useEffect)(()=>{Ze.current&&Qe.current?.focus({preventScroll:!0})},[qe]);let $e=Vv(ne,z,L,g,v),[et,tt]=(0,y.useState)(!1),[nt,rt]=(0,y.useState)(``),[it,at]=(0,y.useState)(0);(0,y.useEffect)(()=>{(Oe||O===0)&&at(O)},[Oe,O]);let ot=(0,y.useMemo)(()=>{let e=new Map(fe.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:Mp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=Lg(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,fe]);(0,y.useEffect)(()=>{if(!_e)return;rt(h(_e.message));let e=window.setTimeout(()=>rt(``),4500);return()=>window.clearTimeout(e)},[_e]);let st=O>0&&!Oe&&(g!==`sequence`||O!==it)&&!z.some(e=>e.dragging),ct=st?z.find(e=>e.id===E&&e.type===`diagram`):null,lt=st?pe.find(e=>e.id===D):null,ut=lt?L.edges.find(e=>e.id===lt.id):null,dt=lt?{position:lt.data.route.labelPoint,size:{width:0,height:0}}:null,ft=ut?L.nodes.find(e=>e.id===ut.source):null,pt=ut?L.nodes.find(e=>e.id===ut.target):null,mt=T?L.nodes.find(e=>e.id===T.source):null,ht=T?L.nodes.find(e=>e.id===T.target):null,gt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id),_t=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(Uv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ip(w,_,i).stroke}}),h(w.section?`Section`:up[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.overviewText?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Overview text`)}),(0,x.jsx)(`ul`,{children:w.overviewText.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(cp[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.source)})]},t))})]}),(e=>e.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Shared dependencies`)}),(0,x.jsx)(`ul`,{children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>P(e),children:[e.label??e.kind,` → `,L.nodes.find(t=>t.id===e.target)?.label]}),e.site&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.site)})]},e.id))})]}))(Cf(L).filter(e=>e.source===w.id)),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(cp[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:lp(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:pe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Yh(L).get(T.id)?.label??Mh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[mt?.label,` → `,ht?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(cp[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:lp(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(Uv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:He.editing?``:`card-actions`,children:(0,x.jsx)(Gv,{editor:He,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return Oe&&(Ve.current=_t),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||$e(E,D,!0,Xe)},"aria-controls":`graph-tools`,"aria-expanded":De,"aria-pressed":De,"aria-label":h(De?`Hide graph navigation`:`Show graph navigation`),title:h(De?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(Uv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(gf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>tt(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tt(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(Uv,{name:`search`}),(0,x.jsx)(`input`,{ref:je,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),et&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>We(`views`),"aria-haspopup":`menu`,"aria-expanded":Ue===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(Uv,{name:`views`}),(0,x.jsx)(`span`,{children:h(gf(e))}),(0,x.jsx)(Uv,{name:`chevron`})]}),Ue===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{eh(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(Uv,{name:`check`}):null}),`${h(gf(t))}${r.filter(e=>hf(e)===hf(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(Uv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>We(`more`),"aria-haspopup":`menu`,"aria-expanded":Ue===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(Uv,{name:`more`})}),Ue===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`svg`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`png`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{ge(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{me(),Ge()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{de(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Uv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":Xv.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${Xv.indexOf(l)*100}%)`}}),Xv.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(Zv[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:Ae,onClick:()=>{Fe(),Oe||$e(E,D,De,!0)},"aria-controls":`node-inspector`,"aria-expanded":Oe,"aria-pressed":Oe,title:h(Oe?`Hide details`:`Show details`),"aria-label":h(Oe?`Hide details`:`Show details`),children:(0,x.jsx)(Uv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${De?`nav-open`:``} ${Oe?`drawer-open`:``}`,children:[Le&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Ne,tabIndex:-1,className:`sidebar nav${Re}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Pe,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(Uv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(gt)})]}),(0,x.jsxs)(`figure`,{ref:xe,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:Yp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ae,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":De,"data-drawer-open":Xe,onKeyDownCapture:e=>{ie(e),e.defaultPrevented||F(e)},"aria-label":h(`Interactive {type}`,{type:h(gf(e))}),children:[(0,x.jsxs)(Sd,{nodes:fe,edges:pe,nodeTypes:Gg,edgeTypes:Kg,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),Ge()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>le(L,0)),nodesDraggable:!I&&!ae,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:ue,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(Uv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:Se,onClick:Ee,"aria-pressed":Ce,"aria-busy":we,"aria-disabled":we||!Te&&!Ce,"aria-label":h(Ce?`Exit fullscreen`:`Enter fullscreen`),title:h(!Te&&!Ce?`Fullscreen is not available in this browser or page`:Ce?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(Uv,{name:Ce?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ot,nodeStrokeColor:e=>e.type===`boundary`?`none`:ip(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:ip(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>We(`legend`),"aria-expanded":Ue===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(Uv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),Ue===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:Xg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:Yg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Ke.length>0&&!ze&&(Ye?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":h(`Key points`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[h(`Key points`),` · `,Ke.length]}),(0,x.jsx)(`button`,{className:`side-close`,ref:Qe,onClick:()=>{Ze.current=!0,Je(!1)},"aria-label":h(`Hide key points`),title:h(`Hide key points`),children:(0,x.jsx)(Uv,{name:`close`})})]}),(0,x.jsx)(`ul`,{children:Ke.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:Qe,"aria-expanded":`false`,onClick:()=>{Ze.current=!0,Je(!0),Ce||$e(E,D,De,!0)},"aria-label":h(`Show key points`),title:h(`Show key points`),children:[(0,x.jsx)(Uv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[h(`Key points`),` · `,Ke.length]})]})),ct&&(0,x.jsx)(Yv,{node:{...ct.data,position:ct.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),ut&&(0,x.jsx)(Yv,{node:dt,edge:{...ut,diagramType:g},source:ft,target:pt,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),!ve&&ye.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ye.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>be(ye.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),ve&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:ve.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>be(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:ve.message})]}),(0,x.jsx)(`div`,{className:`toast ${nt?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:nt})]})]}),ze&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:Me,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${Be}`,"aria-label":h(`Details`),children:Ve.current})]})]})}function ey(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var ty=JSON.parse(document.querySelector(`#graph-data`).textContent),ny=[...Array.isArray(ty.diagrams)?ty.diagrams:[ty]].sort(_f),ry=window.matchMedia(`(prefers-color-scheme: dark)`);function iy(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(ry.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return ry.addEventListener(`change`,e),()=>ry.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function ay(){let[e,t]=(0,y.useState)(uf(ny[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=iy(),s=ey(),c=ny.find(t=>uf(t)===e)??ny[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>mv(ty,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=$f(ny,Kf[o]);return f?e:tp(e,Kf[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(sp(Kf[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)($v,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:ny,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(ay,{})); +`),badges:structuredClone(e?.badges??[]),error:``}),save:async a=>{if(a.preventDefault(),d.pending)return;let o=d.label.trim();if(!o){m({error:bf(i,`Name is required`)});return}if(d.badges.some(e=>!e.label.trim())){m({error:bf(i,`Name is required`)});return}let s=++u.current;m({pending:!0});let c=await(t?r(t.id,o):n(e.id,o,d.subtitle.trim(),l?{overviewText:d.overviewText.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),...e.section?{}:{badges:d.badges}}:{}));if(u.current===s){if(m({pending:!1}),c){m({error:c});return}m({editing:!1,error:``})}}}}function Kv({editor:e,relation:t,locked:n,locale:r}){let i=e=>bf(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&!e.section&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),!t&&e.overview&&(0,x.jsxs)(`label`,{children:[i(`Overview text`),(0,x.jsx)(`textarea`,{disabled:e.pending,"aria-label":i(`Overview text`),value:e.overviewText,onChange:t=>e.set({overviewText:t.target.value,error:``})})]}),!t&&e.overview&&!e.section&&(0,x.jsxs)(`fieldset`,{disabled:e.pending,children:[(0,x.jsx)(`legend`,{children:i(`Badges`)}),e.badges.map((t,n)=>{let r=t=>e.set({badges:e.badges.map((e,r)=>r===n?{...e,...t}:e)});return(0,x.jsxs)(`div`,{className:`badge-editor`,children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{"aria-label":`${i(`Badges`)} ${n+1}`,value:t.label,onChange:e=>{let{source:n,...i}=t;r({...i,source:void 0,label:e.target.value,evidence:`document`})}})]}),(0,x.jsxs)(`label`,{children:[i(`Badge type`),(0,x.jsx)(`select`,{value:t.role,onChange:e=>r({role:e.target.value}),children:[`status`,`version`,`requirement`].map(e=>(0,x.jsx)(`option`,{value:e,children:i({status:`Status`,version:`Version`,requirement:`Requirement`}[e])},e))})]}),(0,x.jsxs)(`label`,{children:[i(`Evidence`),(0,x.jsx)(`select`,{value:t.evidence,onChange:e=>r({evidence:e.target.value}),children:[`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`].map(e=>(0,x.jsx)(`option`,{value:e,children:i(cp[e]??e)},e))})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:e.badges.filter((e,t)=>t!==n)}),children:i(`Remove badge`)})]},n)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:[...e.badges,{label:``,role:`status`,evidence:`document`}]}),children:i(`Add badge`)})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var qv=292,Jv=232,Yv=14;function Xv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>bf(c,e,t),_=!!t,v=_?(Yh(d).get(t.id)?.label??Mh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(Jv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??Jv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Zh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=av(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Yv,y:N.top},{side:`left`,x:N.left-Yv-qv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Yv},{side:`above`,x:N.left,y:N.top-Yv-C}],F=e=>e.x>=P.left&&e.x+qv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Zh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Yh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...dh(e)]),n=kh(d);for(let r of d.groups??[]){let i=xh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+qv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-qv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?lp(e.source):_&&t.site?lp(t.site):null,ae=_?op(t,r,o,s,n,Ch(d).get(t.id)):ip(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:qv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(Wv,{name:`close`})}),u.editing?(0,x.jsx)(Kv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(up[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(cp[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(Wv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(Kv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(Wv,{name:`arrowRight`})]})]})]})]})}var Zv=[`system`,`light`,`dark`],Qv={system:`Follow system`,light:`Light`,dark:`Dark`};function $v(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function ey({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>bf(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,onOverviewKeyDown:ie,layoutPending:ae,cancelLayout:oe,updateNodeText:se,updateEdgeText:ce,readGraph:le,focusDiagram:ue,nudgeLayout:de,visibleNodes:fe,visibleEdges:pe,reset:me,exportDiagram:he,saveGraph:ge,exportStatus:_e,layoutProblem:ve,layoutWarnings:ye,focusProblem:be,boardRef:xe,fullscreenButtonRef:Se,isFullscreen:Ce,fullscreenPending:we,fullscreenSupported:Te,toggleFullscreen:Ee,toolbarOpen:De,drawerOpen:Oe,toolbarButtonRef:ke,drawerButtonRef:Ae,searchInputRef:je,inspectorRef:Me,panelRef:Ne,toggleToolbar:Pe,toggleDrawer:Fe,openDetails:Ie}=Bv(e,c,d,i,t,n,f),[Le,Re]=$v(De,v,Ne),[ze,Be]=$v(Oe,v,Me),Ve=(0,y.useRef)(null),He=Gv(w,T,se,ce,e.meta.locale,ff(e),oe),{open:Ue,toggle:We,close:Ge}=Vv(),Ke=e.meta.notes??[],[qe,Je]=(0,y.useState)(!0),Ye=Ke.length>0&&qe&&!ze,Xe=Oe||Ye&&!Ce,Ze=(0,y.useRef)(!1),Qe=(0,y.useRef)(null);(0,y.useEffect)(()=>{Ze.current&&Qe.current?.focus({preventScroll:!0})},[qe]);let $e=Hv(ne,z,L,g,v),[et,tt]=(0,y.useState)(!1),[nt,rt]=(0,y.useState)(``),[it,at]=(0,y.useState)(0);(0,y.useEffect)(()=>{(Oe||O===0)&&at(O)},[Oe,O]);let ot=(0,y.useMemo)(()=>{let e=new Map(fe.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:Mp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=Lg(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,fe]);(0,y.useEffect)(()=>{if(!_e)return;rt(h(_e.message));let e=window.setTimeout(()=>rt(``),4500);return()=>window.clearTimeout(e)},[_e]);let st=O>0&&!Oe&&(g!==`sequence`||O!==it)&&!z.some(e=>e.dragging),ct=st?z.find(e=>e.id===E&&e.type===`diagram`):null,lt=st?pe.find(e=>e.id===D):null,ut=lt?L.edges.find(e=>e.id===lt.id):null,dt=lt?{position:lt.data.route.labelPoint,size:{width:0,height:0}}:null,ft=ut?L.nodes.find(e=>e.id===ut.source):null,pt=ut?L.nodes.find(e=>e.id===ut.target):null,mt=T?L.nodes.find(e=>e.id===T.source):null,ht=T?L.nodes.find(e=>e.id===T.target):null,gt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id),_t=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(Wv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ip(w,_,i).stroke}}),h(w.section?`Section`:up[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.overviewText?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Overview text`)}),(0,x.jsx)(`ul`,{children:w.overviewText.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(cp[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.source)})]},t))})]}),(e=>e.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Shared dependencies`)}),(0,x.jsx)(`ul`,{children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>P(e),children:[e.label??e.kind,` → `,L.nodes.find(t=>t.id===e.target)?.label]}),e.site&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.site)})]},e.id))})]}))(Cf(L).filter(e=>e.source===w.id)),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(cp[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:lp(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:pe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Yh(L).get(T.id)?.label??Mh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[mt?.label,` → `,ht?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(cp[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:lp(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(Wv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:He.editing?``:`card-actions`,children:(0,x.jsx)(Kv,{editor:He,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return Oe&&(Ve.current=_t),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||$e(E,D,!0,Xe)},"aria-controls":`graph-tools`,"aria-expanded":De,"aria-pressed":De,"aria-label":h(De?`Hide graph navigation`:`Show graph navigation`),title:h(De?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(Wv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(gf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>tt(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tt(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(Wv,{name:`search`}),(0,x.jsx)(`input`,{ref:je,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),et&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>We(`views`),"aria-haspopup":`menu`,"aria-expanded":Ue===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(Wv,{name:`views`}),(0,x.jsx)(`span`,{children:h(gf(e))}),(0,x.jsx)(Wv,{name:`chevron`})]}),Ue===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{eh(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(Wv,{name:`check`}):null}),`${h(gf(t))}${r.filter(e=>hf(e)===hf(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(Wv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>We(`more`),"aria-haspopup":`menu`,"aria-expanded":Ue===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(Wv,{name:`more`})}),Ue===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`svg`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`png`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{ge(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{me(),Ge()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{de(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":Zv.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${Zv.indexOf(l)*100}%)`}}),Zv.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(Qv[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:Ae,onClick:()=>{Fe(),Oe||$e(E,D,De,!0)},"aria-controls":`node-inspector`,"aria-expanded":Oe,"aria-pressed":Oe,title:h(Oe?`Hide details`:`Show details`),"aria-label":h(Oe?`Hide details`:`Show details`),children:(0,x.jsx)(Wv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${De?`nav-open`:``} ${Oe?`drawer-open`:``}`,children:[Le&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Ne,tabIndex:-1,className:`sidebar nav${Re}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Pe,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(Wv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(gt)})]}),(0,x.jsxs)(`figure`,{ref:xe,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:Yp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ae,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":De,"data-drawer-open":Xe,onKeyDownCapture:e=>{ie(e),e.defaultPrevented||F(e)},"aria-label":h(`Interactive {type}`,{type:h(gf(e))}),children:[(0,x.jsxs)(Sd,{nodes:fe,edges:pe,nodeTypes:Gg,edgeTypes:Kg,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),Ge()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>le(L,0)),nodesDraggable:!I&&!ae,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:ue,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(Wv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:Se,onClick:Ee,"aria-pressed":Ce,"aria-busy":we,"aria-disabled":we||!Te&&!Ce,"aria-label":h(Ce?`Exit fullscreen`:`Enter fullscreen`),title:h(!Te&&!Ce?`Fullscreen is not available in this browser or page`:Ce?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(Wv,{name:Ce?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ot,nodeStrokeColor:e=>e.type===`boundary`?`none`:ip(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:ip(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>We(`legend`),"aria-expanded":Ue===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(Wv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),Ue===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:Xg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:Yg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Ke.length>0&&!ze&&(Ye?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":h(`Key points`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[h(`Key points`),` · `,Ke.length]}),(0,x.jsx)(`button`,{className:`side-close`,ref:Qe,onClick:()=>{Ze.current=!0,Je(!1)},"aria-label":h(`Hide key points`),title:h(`Hide key points`),children:(0,x.jsx)(Wv,{name:`close`})})]}),(0,x.jsx)(`ul`,{children:Ke.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:Qe,"aria-expanded":`false`,onClick:()=>{Ze.current=!0,Je(!0),Ce||$e(E,D,De,!0)},"aria-label":h(`Show key points`),title:h(`Show key points`),children:[(0,x.jsx)(Wv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[h(`Key points`),` · `,Ke.length]})]})),ct&&(0,x.jsx)(Xv,{node:{...ct.data,position:ct.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),ut&&(0,x.jsx)(Xv,{node:dt,edge:{...ut,diagramType:g},source:ft,target:pt,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),!ve&&ye.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ye.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>be(ye.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),ve&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:ve.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>be(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:ve.message})]}),(0,x.jsx)(`div`,{className:`toast ${nt?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:nt})]})]}),ze&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:Me,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${Be}`,"aria-label":h(`Details`),children:Ve.current})]})]})}function ty(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var ny=JSON.parse(document.querySelector(`#graph-data`).textContent),ry=[...Array.isArray(ny.diagrams)?ny.diagrams:[ny]].sort(_f),iy=window.matchMedia(`(prefers-color-scheme: dark)`);function ay(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(iy.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return iy.addEventListener(`change`,e),()=>iy.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function oy(){let[e,t]=(0,y.useState)(uf(ry[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=ay(),s=ty(),c=ry.find(t=>uf(t)===e)??ry[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>hv(ny,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=$f(ry,Kf[o]);return f?e:tp(e,Kf[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(sp(Kf[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)(ey,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:ry,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(oy,{})); diff --git a/skills/q-flow/assets/viewer/src/features/useGraphLayout.js b/skills/q-flow/assets/viewer/src/features/useGraphLayout.js index d04930c..c8c9806 100644 --- a/skills/q-flow/assets/viewer/src/features/useGraphLayout.js +++ b/skills/q-flow/assets/viewer/src/features/useGraphLayout.js @@ -11,7 +11,7 @@ import { initialNodes, initialEdges } from '../DiagramCanvas.jsx'; import { graphBounds, occupiedBox } from '../edge-routing.js'; import { qualityFailure, requireDiagramQuality } from '../layout-quality.js'; import { nudgeGraphLayout } from '../layout-nudge.js'; -import { appleEase, readingPadding, readingRect, locateViewport, readableViewport, readingStart } from '../reading-area.js'; +import { appleEase, readingPadding, readingRect, locateViewport, readableViewport, readingStart, overviewFloor } from '../reading-area.js'; import { constrainNodeChanges, currentGraphFromFlow, fitCard, placed } from '../session-graph.js'; export function useGraphLayout(graph, reduceMotion, setStatus, originalGraph = graph) { @@ -133,7 +133,7 @@ export function useGraphLayout(graph, reduceMotion, setStatus, originalGraph = g const canvas = canvasRef.current; if (!canvas) return; const bounds = graphBounds(targetGraph), navOpen = canvas.dataset.navOpen === 'true', drawerOpen = canvas.dataset.drawerOpen === 'true'; // Fit canvas (overview) always shows everything; every other re-fit opens at the readable floor when everything is too small. - const viewport = (!overview && readableViewport(bounds, readingStart(targetGraph), readingRect(canvas, navOpen, drawerOpen))) + const viewport = (!overview && readableViewport(bounds, readingStart(targetGraph), readingRect(canvas, navOpen, drawerOpen), undefined, overviewFloor(targetGraph))) || getViewportForBounds(bounds, canvas.clientWidth, canvas.clientHeight, .08, 2, readingPadding(canvas, navOpen, drawerOpen)); return setViewport(viewport, { duration, ease: appleEase }); }; diff --git a/skills/q-flow/assets/viewer/src/reading-area.js b/skills/q-flow/assets/viewer/src/reading-area.js index 8bd9270..1310a19 100644 --- a/skills/q-flow/assets/viewer/src/reading-area.js +++ b/skills/q-flow/assets/viewer/src/reading-area.js @@ -60,6 +60,9 @@ export const readingStart = graph => graph.nodes.find(node => node.id === graph. ?? (graph.meta?.diagramType === 'sequence' || !graph.nodes.every(node => node.position) ? undefined : graph.nodes.find(isCore) ?? [...graph.nodes].sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x)[0]); +// A sequence is read top to bottom, so it opens whole only when the whole view already reads at the readable floor. +export const overviewFloor = graph => graph.meta?.diagramType === 'sequence' ? READABLE_ZOOM : OVERVIEW_ZOOM; + // Opening view. Fit-all stays the default while the whole view reads at OVERVIEW_ZOOM or more; a larger view opens at the // readable floor on a window that begins at the reading start instead: clamped to the graph, centred on an axis the graph // does not fill, and below the legend button. null means fit-all. diff --git a/skills/q-flow/scripts/generate-viewer.test.mjs b/skills/q-flow/scripts/generate-viewer.test.mjs index 3e1ddea..5c4c5ae 100644 --- a/skills/q-flow/scripts/generate-viewer.test.mjs +++ b/skills/q-flow/scripts/generate-viewer.test.mjs @@ -18,7 +18,7 @@ import { saveGraphJson } from '../assets/viewer/src/features/download.js'; import { pageWithGraph } from '../assets/viewer/src/session-graph.js'; import { DIAGRAM_TYPES, validateGraph, validateGraphInput, verifySourceEvidence, layoutComposition } from './validate-graph.mjs'; import { getDiagram, edgeMarkers, isDashed } from '../assets/viewer/src/diagrams/registry.js'; -import { appleEase, readingRect, readingViewport, locateViewport, readableViewport, readingStart, LEGEND } from '../assets/viewer/src/reading-area.js'; +import { appleEase, readingRect, readingViewport, locateViewport, readableViewport, readingStart, overviewFloor, LEGEND } from '../assets/viewer/src/reading-area.js'; import { sequenceFragment, renderFragment } from '../assets/viewer/src/sequence-fragments.js'; import { compileGraphLayout } from './compile-layout.mjs'; import { requireDiagramQuality } from '../assets/viewer/src/layout-quality.js'; @@ -225,6 +225,7 @@ test('opens a graph too large to fit at the readable floor on its reading start' const area = { left: 24, top: 76, right: 1416, bottom: 764, width: 1392, height: 688 }, top = area.top + LEGEND; assert.equal(readableViewport({ x: 0, y: 0, width: 1500, height: 700 }, undefined, area), null, 'a graph that reads at the floor keeps fit-all'); assert.equal(readableViewport({ x: 0, y: 0, width: 2600, height: 1300 }, undefined, area), null, 'a whole view that still reads at the overview floor opens whole'); + assert.equal(readableViewport({ x: 0, y: 0, width: 2600, height: 1300 }, undefined, area, undefined, overviewFloor({ meta: { diagramType: 'sequence' } })).zoom, READABLE_ZOOM, 'a sequence opens whole only at the readable floor'); assert.deepEqual(readableViewport({ x: 10, y: 20, width: 6000, height: 6840 }, undefined, area), { zoom: READABLE_ZOOM, x: area.left - 10 * READABLE_ZOOM, y: top - 20 * READABLE_ZOOM }, 'without a start the top-left corner opens below the legend button'); const wide = readableViewport({ x: 0, y: 0, width: 2000, height: 1800 }, box('init', 'Start', 'initial', 1800, 0, 100, 80), area); From 4c00aad9e77a28a238e3a4cc8b46d39af4b2a6ee Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 11:24:18 +0800 Subject: [PATCH 06/16] =?UTF-8?q?feat(layout):=20preserve=20=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E5=A4=B1=E8=B4=A5=E6=97=B6=E5=B1=80=E9=83=A8=E4=BF=AE?= =?UTF-8?q?=E8=A1=A5=E6=96=B0=E8=BF=9E=E7=BA=BF=E4=B8=8E=E6=8B=A5=E6=8C=A4?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=EF=BC=8C=E6=97=B6=E5=BA=8F=E5=9B=BE=E4=BF=9D?= =?UTF-8?q?=E6=8C=81=E5=88=97=E5=8F=AA=E9=87=8D=E6=8E=92=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/q-flow/SKILL.md | 4 +- skills/q-flow/assets/viewer-dist/index.html | 2 +- skills/q-flow/scripts/compile-layout.mjs | 36 +++++++++++++++-- skills/q-flow/scripts/compile-sequence.mjs | 16 +++++--- .../scripts/composition-review.test.mjs | 40 +++++++++++++++++++ skills/q-flow/scripts/generate-viewer.mjs | 3 ++ 6 files changed, 89 insertions(+), 12 deletions(-) diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index 5d7426a..42f48df 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -48,7 +48,7 @@ node scripts/validate-graph.mjs "/graph.json" --repo- - Execute the scripts; do not read them, the bundled HTML, the Viewer source or tests. `--help` lists every option. Failures report elements, rule, measurement and remediation; `--verbose` prints the receipt. - On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and moved anchors, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. - Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: split into same-type views or fold shared dependencies; keep requested detail and topics. A failing collection names every failing view. -- If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. Generation defaults to `--layout auto`; `--layout preserve` keeps existing geometry under the same gate. +- If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. - For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local files (existence, line range, symbol) and report `sourceEvidence` with `relations` coverage. Generation records `meta.sourceFiles`: moved lines pass, changed code fails as drift. Neither proves a claim. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. - Outputs are `index.html`, `graph.json` and one SVG per view (`diagram.svg`, or `diagram--.svg` in a collection), built from the prebuilt viewer; no rebuild or install. Use `--force` only with approval to replace the named outputs. All collection views must pass before replacing output. - Reply with artifact paths, types, granularity and coverage (`meta.scope`), semantic/geometry/source-relation results, `meta.notes`, unresolved evidence boundaries, and `Browser acceptance: not performed` unless the next section ran. Never paste full HTML or graph JSON. @@ -68,7 +68,7 @@ node scripts/validate-graph.mjs "/graph.json" --input-only --fix --repo-roo node scripts/generate-viewer.mjs "/graph.json" "" --layout preserve --force --repo-root "" ``` -Between the two, work only what `--fix` left: update just the elements each `meta.sourceDrift` item names (relate uncovered new code), then delete the item; fix anchors still reported and report a symbol you cannot place. Validate the output as above. `preserve` keeps moved positions and text; if it fails the gate, report the nodes and ask before `--layout auto`. Reply with the changed elements and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. +Between the two, work only what `--fix` left: update just the elements each `meta.sourceDrift` item names (relate uncovered new code), then delete the item; fix anchors still reported and report a symbol you cannot place. Validate the output as above. `preserve` keeps node positions and reroutes new or crowded edges; if that fails, report the nodes and ask before `--layout auto`. Regenerate a sequence view that lost messages with `--layout auto --view `; columns stay. Reply with the changed elements and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. ## Viewer maintenance diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index 0d8711f..70588d2 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -277,7 +277,7 @@ ${t}.field-type{font:400 ${X.body}px ui-monospace,monospace;fill:${e.ink3}} `}function Xp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return em(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+xp.pad,v=g+xp.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*xp.chipLine;return`${Q(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>Q(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>Q(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>Q(v,b+14+t*f.lineHeight,e,`meta`)).join(``),E={x:g+xp.pad,y:_+(xp.titleLine-xp.plate)/2},D=t+e.size.width-c-xp.pad-p.width-l;return`${Zp(e,t,n,r,i,s)}${Qp(e,E.x,E.y,xp.plate,a)}${Q(D+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}var Zp=(e,t,n,r,i,a)=>Ip(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Qp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:Yf(e)?i.accent:Jf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${$p(e)}`}var $p=e=>Jf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function em(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Zp(e,t,n,r,i,s)}${Qp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,wp(e,o).text,`stereotype`)}${d}${f}`}var tm=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],nm=[[.08,0],[1,0],[.92,1],[0,1]];function rm(e,t,n){let{width:r,height:i}=e.size;if(Cg(e))return Lp(e,t,n,16);if(e.kind===`external`)return Bp(e,t,n,zp);if(e.kind===`security`)return Lp(e,t,n,22);if(e.kind===`failure`)return Bp(e,t,n,tm);if(e.kind===`config`)return Bp(e,t,n,nm);if(e.kind===`business`)return Lp(e,t,n,Math.min(28,i/2));let a=Lp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var im=(e,t,n)=>Cg(e)?Gp(e,t,n,16):e.kind===`external`?qp(e,t,n,zp):e.kind===`security`?Gp(e,t,n,22):e.kind===`failure`?qp(e,t,n,tm):e.kind===`config`?qp(e,t,n,nm):e.kind===`business`?Gp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):Wp(e,t,n),am=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,om={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Cg(e)?Mg(e,t,n,a,r,i):Xp(e,t,n,r,i,a,o,rm,am(e)),outline:rm,anchor:im,cardLayout:!0,contentInset:am},sm=.12,cm=(e,t,n)=>e.kind===`decision`?Vp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*sm},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Lp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),lm=(e,t,n)=>e.kind===`decision`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?qp(e,t,n,[[sm,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Gp(e,t,n,e.size.height/2):Wp(e,t,n),um=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*sm+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function dm(e,t,n,r,i){let{width:a,height:o}=e.size,s=um(e),c=Fp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Ip(cm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var fm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:dm,outline:cm,anchor:lm,textArea:um,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},pm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n):Lp(e,t,n,7,mm(e));function mm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function hm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=mm(e),u=Ip(pm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,up[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Np([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var gm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:hm,outline:pm,sequence:!0,selectionHeight:mm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},_m=(e,t,n)=>Lp(e,t,n,9);function vm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=dp(e),u=Pp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,Pp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,Pp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Ip(_m(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,Pp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var ym={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:vm,outline:_m,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},bm=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function xm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Bp(e,t,n,bm),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Lp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`external`?Bp(e,t,n,zp):e.kind===`service`?Lp(e,t,n,16):Lp(e,t,n,10)}var Sm=(e,t,n)=>e.kind===`device`?Wp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?qp(e,t,n,bm):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?qp(e,t,n,zp):e.kind===`service`?Gp(e,t,n,16):Wp(e,t,n),Cm=e=>({container:24,artifact:18,node:20})[e.kind]??0,wm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Tm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Xp(e,...t,xm,wm(e),Cm(e)),outline:xm,anchor:Sm,cardLayout:!0,contentInset:wm,cardCorner:Cm},Em=(e,t,n)=>Lp(e,t,n,9);function Dm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=dp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``);return`${Ip(Em(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),Pp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,Pp(e.subtitle,m),`body`):``}${h}${g}`}var Om={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:Dm,outline:Em,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=kp(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},km=e=>e.subtitle?14:e.size.width/2,Am=[`entry`,`do`,`exit`],jm={side:16,pad:8,line:20,keyWidth:64};function Mm(e){let t=e.kind===`state`?Am.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*jm.side-jm.keyWidth,X.small,jm.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*jm.line+2*jm.pad:0}}var Nm=2*jm.side+jm.keyWidth,Pm=e=>{let{height:t}=Mm(e);return t?{x:jm.side,y:e.size.height-t,width:e.size.width-2*jm.side,height:t}:null},Fm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+km(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Vp(e,t,n):Lp(e,t,n,12),Im=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=km(e)-e.size.width/2;return Kp({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Wp(e,t,n)},Lm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=Mm(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Rm(e,t,n,r,i){let{rows:a,height:o}=Mm(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+jm.pad+c++*jm.line+15;return(r?``:Q(t+jm.side,a,`${e.key} /`,`field-key`))+Q(t+jm.side+jm.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function zm(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Lm(e),o=e.kind===`final`;return`${Ip(Fm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Fp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Lm(e),l=n+(e.size.height-Mm(e).height)/2;return`${Ip(Fm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,l,e.label,c.width,c.height,e.subtitle)}${Rm(e,t,n,i,a)}`}var Bm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Vm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:zm,outline:Fm,anchor:Im,textArea:Lm,activityArea:Pm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Bm(e).map(e=>e.text).join(` `),edgeLabelParts:Bm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Am)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},Hm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Um=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Wm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n+Hm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Gm=(e,t,n)=>e.kind===`actor`?Jp(e,t,n,Hm(e)):Kp(e,t,n);function Km(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+Hm(e)+98,Pp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+Hm(e)+122,Pp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Um(e);return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var qm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Km,outline:Wm,anchor:Gm,textArea:Um,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Jm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Lp(e,t,n,e.kind===`process`?24:10),Ym=e=>({width:e.size.width-32,height:e.size.height-20});function Xm(e,t,n,r,i){let a=Ym(e);return`${Ip(Jm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Zm=[om,fm,gm,ym,Tm,Om,Vm,qm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Xm,outline:Jm,textArea:Ym,anchor:(e,t,n)=>e.kind===`process`?Gp(e,t,n,24):Wp(e,t,n)}],Qm=Zm.map(e=>e.id);Object.fromEntries(Zm.map(e=>[e.id,e.label]));var $m=new Map(Zm.map(e=>[e.id,e]));if($m.size!==Zm.length)throw Error(`Duplicate diagram type`);var eh=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>$m.get(e),th=(e,t,n,r=!1)=>t===`architecture`&&Cg(e)?Tg(e):Tp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),nh=e=>{let t=eh(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=th(n,t,e.meta?.locale).minHeight)},rh=(e,t)=>!($(t).undirected??[]).includes(e.kind),ih=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),ah=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),oh=(e,t)=>({start:null,end:rh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),sh=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ch=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),lh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var uh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,dh=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),fh=(e,t)=>e?.id??String(t);function ph(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(fh(i,t))}`);return n}function mh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===fh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>mh(e,t,n,r,a)))]}function hh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>fh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=fh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=mh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function gh(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function _h(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>gh(n,t)-gh(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var vh=e=>Z(e.label,Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function yh(e,t){let n={...e.position,...e.size},r=vh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>uh(e,t,4)))}function bh(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...dh(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>uh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:fh(null,0)}]}}function xh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;uh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=yh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=bh(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===fh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=mh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...dh(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Df.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1mh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...dh(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...dh(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${fh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Df.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>uh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=fh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${fh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function Sh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function Ch(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wh(e,t,n=Ch(e),r=ph(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Th=140,Eh=54,Dh=(e,t)=>(e.route?.messageY??Th+e.order*Eh)+(t===`receive`&&e.source===e.target?30:0);function Oh(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Dh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ph(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Dh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Dh(n.get(i.end.edgeId),i.end.at)-l}})}function Ah(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var jh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Mh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Nh(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ph(e,t=Yh(e)){e=Tf(e);let n=[...bg(e),...e.groups??[],...e.nodes,...kh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Nh(n.sourceCardinality,e.points[0],e.points[1]),Nh(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Fh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=jh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Ih(e,t,n=Ef.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Lh(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Rh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function zh(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Bh(e,t,n,r){let i={clearance:-1,length:-1,point:zh(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Vh(e,t){let n=jh(e),r=jh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Hh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?tg(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Ih(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Rh(f,e);return Rh(f,Ih(t,r,a)),f.push(t),Lh(f)}function Wh(e,t,n,r,i,a=Ef.endpoint,o=`architecture`){let s=Fh(e,n.sourceSide,r,o),c=Fh(t,n.targetSide,i,o),l=Ih(s,n.sourceSide,a),u=Ih(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Lh([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Lh([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Gh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Kh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var qh=(e,t=0,n=0)=>e.curved&&Kh(e,t,n)||Gh(e.points,t,n);function Jh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Dh(e,`send`),u=Dh(e,`receive`),d=Ah(o,t.id,e,`send`,l,s.get(e.id)),f=Ah(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||jh(t).x<=jh(n).x,m=d?d.x+(p?d.width:0):jh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):jh(n).x,g=wh(a,e,c,s),_=Math.abs(h-m),v=Dp(g,t.id===n.id?Df.labelWidth:Math.min(Df.labelWidth,Math.max(1,_-32-12))),y=t.id===n.id?null:Dp(g,Math.max(1,_-64)),b=y&&(e.route?.labelAt??{x:(m+h)/2,y:l-6-y.height/2}),x=y&&y.lines.lengthuh({x:b.x-y.width/2,y:b.y-y.height/2,width:y.width,height:y.height},e,2))?y:v,S={width:x.width,height:x.height};if(t.id===n.id){let t=48+r*Ef.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Uh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+S.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Uh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-S.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Yh(e){e=Tf(e);let t=eh(e),n=$(t).endpointStub??Ef.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Vh(t,n)}}),a=t===`sequence`?{graph:e,executions:kh(e),scopes:ph(e),pairs:Ch(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?jh(i).y:jh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*Ef.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Zh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,mm(e))}:{...e.position,...e.size}}function Qh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function $h(e,t,n,r){let i=tg(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=jh(t),o=Fh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function eg(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&eg(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=jh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Fh(n,`left`,o,r).x,c=Fh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Fh(n,`top`,o,r).y,c=Fh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function sg(e){e=Tf(e);let t=eh(e),n=[],r=Yh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...kh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightuh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!nh(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:xp.minHeight))continue;let{minHeight:r}=t===`architecture`&&Cg(n)?Tg(n):Tp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;eEf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${Ef.endpoint}px`);let f=og(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!$h(i.points[0],a,i.sourceSide,t)||!$h(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Ih(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(jh(a).x-jh(o).x),t=Math.max(160,i.labelBox.width+32);eXh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),rg(t).some(([e,t])=>eg(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Xh(i.labelBox,tg(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=rg(r);for(let i=1;ieg(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ag(a,o,e,t)>Ef.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var cg=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),lg=(e,t,n)=>Math.max(t,Math.min(n,e)),ug=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=lg(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function dg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(ug(e,n,r),ug(t,n,r),ug(n,e,t),ug(r,e,t))}function fg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function pg(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function mg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:lg(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:lg((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>ug({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>dg(e,t,r,n[(i+1)%n.length])))}var gg=new WeakMap;function _g(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=gg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Hm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,ug({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>dg(e,a,t,n)),...i.map(t=>fg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>mg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>hg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,ug({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>pg(e,t,c);else{let n=s===`rect`?c:tg(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,fg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),fg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},gg.set(e,{signature:n,probe:l}),l}function vg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return rg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function yg(e,t,n=[]){let r=new Set(n),i=eh(t),a=cg(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Zh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Yh(e),d=kf($(i)).labelGap,f=[...o.map(e=>Zh(e,i)),...l.flatMap(ig)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>eg(r,e,t))||l.some(n=>vg(r,e,n).distanceeg(r,e,t)))}))&&r.add(n.id)}return r}var bg=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},xg=e=>e&&typeof e==`object`&&!Array.isArray(e),Sg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Cg=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function wg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!zf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{xg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Sg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!xg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!xg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Sg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!xg(e.position)||!xg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Sg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!xg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Tg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Eg=e=>e.frame===`none`?0:Y.padding,Dg=(e,t)=>{let n=t-Eg(e)*2;return Eg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Og(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Eg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function kg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=bg(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Ag=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),jg=(e,t,n,r,i=``)=>`${Ag(n)}`;function Mg(e,t,n,r){let i=Hf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Tg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>jg(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>jg(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ng(e,t,n=0,r=0){let i=Hf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Eg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>jg(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>jg(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function Pg(e,t=new Map){if(!ff(e))return[];let n=[],r=bg(e);for(let t of r){let r=Dg(t,t.size.width)+Eg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Eg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Eg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Og(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Fg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=ip(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Ip(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` `);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}function zg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Bg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(zg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Vg({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` -`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t){let n=structuredClone(e),r=n.groups??[],i=new Map(n.edges.map(e=>[e.id,e])),a=new Map;for(let e of[...n.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])a.has(t)||a.set(t,a.size);let o=(n.layout?.participantOrder??[...n.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||(a.get(e.id)??1/0)-(a.get(t.id)??1/0)||(e.ide.id)).map(e=>n.nodes.find(t=>t.id===e)),s=d.nodeGap+t*8,c=12+t*4,l=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,u=(e,t)=>A(l(e,t),f.labelWidth,14,20),p=e=>A(e.body,f.labelWidth,16,24),m=32;for(let e of o)e.size=Hr(e,`sequence`,n.meta.locale),e.position={x:m,y:48},m+=e.size.width+s;Tt(n,o);for(let e of n.edges)e.route={messageY:200+e.order*100};let h=H(n),g=Ot(n),_=new Set(r.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),v=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).order),y=e=>e.edge?e.edge.order:Math.min(1/0,...v(e.group)),b=e=>e.sort((e,t)=>y(e)-y(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r)).map(e=>h.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),S=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=r.find(e=>e.id===n.parentId)){t.add(n.id);let e=x(n);if(e.length)return e}return[...h.values()].flatMap(e=>e.points)};for(let e of[...r].sort((e,t)=>vt(t,r)-vt(e,r)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=S(e),n=r.filter(t=>t.parentId===e.id),a=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[u(e,t).width,p(t).width])),s=e.operands.flatMap((t,n)=>gt(e,t,n,r)).map(e=>i.get(e).route.messageY),c=Math.min(...s),l=Math.max(...s),d=g.filter(e=>!s.length||e.y<=l&&e.y+e.height>=c).sort((e,t)=>e.x-t.x),f=t.length?Math.min(...t.map(e=>e.x)):o[0].position.x,m=Math.min(f,...d.filter(e=>e.x=f-8).map(e=>e.x))-a-40,h=Math.min(m,...n.map(e=>e.position.x-32)),_=Math.max(h+a+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of d)e.x<_+8&&e.x+e.width>_-56-16&&(_=Math.max(_,e.x+e.width+56));e.position={x:h,y:0},e.size={width:Math.ceil(_-h),height:0}}function C(e,t){let n=h.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+c}function w(e,t){for(let n of b(e))t=n.edge?C(n.edge,t):T(n.group,t);return t}function T(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+c;for(let[t,a]of e.operands.entries()){n+=u(e,a).height+16,a.body&&(n+=p(a).height+16);let o=r.filter(n=>n.parentId===e.id&&n.parentOperandId===z(a,t));n=w([...a.edgeIds.map(e=>({edge:i.get(e)})),...o.map(e=>({group:e}))],n),n+=c}return e.size.height=n-t+16,t+e.size.height+c}let ee=w([...n.edges.filter(e=>!_.has(e.id)).map(e=>({edge:e})),...r.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...o.map(Ke))+d.labelGap),E=[...n.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...o.map(e=>e.position.x)));for(let e of[...o,...r])e.position.x+=te;for(let e of n.nodes)e.size.height=ee+32-e.position.y;return n}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` +`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t,{keepColumns:n=!1}={}){let r=structuredClone(e),i=r.groups??[],a=new Map(r.edges.map(e=>[e.id,e])),o=new Map,s=r.nodes.every(e=>e.position);for(let e of[...r.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])o.has(t)||o.set(t,o.size);let c=e=>s?e.position.x:o.get(e.id)??1/0,l=(r.layout?.participantOrder??[...r.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||c(e)-c(t)||(e.ide.id)).map(e=>r.nodes.find(t=>t.id===e)),u=d.nodeGap+t*8,p=12+t*4,m=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=(e,t)=>A(m(e,t),f.labelWidth,14,20),g=e=>A(e.body,f.labelWidth,16,24),_=32;for(let e of l){let t=n&&s?e.position.x:_;e.size=Hr(e,`sequence`,r.meta.locale),e.position={x:Math.max(_,t),y:48},_=e.position.x+e.size.width+u}Tt(r,l);for(let e of r.edges)e.route={messageY:200+e.order*100};let v=H(r),y=Ot(r),b=new Set(i.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).order),S=e=>e.edge?e.edge.order:Math.min(1/0,...x(e.group)),C=e=>e.sort((e,t)=>S(e)-S(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),w=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>v.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),T=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=i.find(e=>e.id===n.parentId)){t.add(n.id);let e=w(n);if(e.length)return e}return[...v.values()].flatMap(e=>e.points)};for(let e of[...i].sort((e,t)=>vt(t,i)-vt(e,i)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=T(e),n=i.filter(t=>t.parentId===e.id),r=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[h(e,t).width,g(t).width])),o=e.operands.flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).route.messageY),s=Math.min(...o),c=Math.max(...o),u=y.filter(e=>!o.length||e.y<=c&&e.y+e.height>=s).sort((e,t)=>e.x-t.x),d=t.length?Math.min(...t.map(e=>e.x)):l[0].position.x,f=Math.min(d,...u.filter(e=>e.x=d-8).map(e=>e.x))-r-40,p=Math.min(f,...n.map(e=>e.position.x-32)),m=Math.max(p+r+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of u)e.xm-56-16&&(m=Math.max(m,e.x+e.width+56));e.position={x:p,y:0},e.size={width:Math.ceil(m-p),height:0}}function ee(e,t){let n=v.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+p}function E(e,t){for(let n of C(e))t=n.edge?ee(n.edge,t):te(n.group,t);return t}function te(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+p;for(let[t,r]of e.operands.entries()){n+=h(e,r).height+16,r.body&&(n+=g(r).height+16);let o=i.filter(n=>n.parentId===e.id&&n.parentOperandId===z(r,t));n=E([...r.edgeIds.map(e=>({edge:a.get(e)})),...o.map(e=>({group:e}))],n),n+=p}return e.size.height=n-t+16,t+e.size.height+p}let ne=E([...r.edges.filter(e=>!b.has(e.id)).map(e=>({edge:e})),...i.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...l.map(Ke))+d.labelGap),re=[...r.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...l.map(e=>e.position.x)));for(let e of[...l,...i])e.position.x+=D;for(let e of r.nodes)e.size.height=ne+32-e.position.y;return r}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` - `)?String(n).split(` - `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function x_(e,t={}){let n=m_(e,{inputOnly:!0}),r=n.length?[]:m_(e,{audit:!1}),i=n.length||r.length?null:S_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw b_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` - `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function S_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(i_(t)>=i_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)__(d,g_(e))||s(`group.member-inset`,[i.id,e.id],g_(e),d,[o,g_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&v_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,g_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=y_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[g_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(g_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function C_(e){return function(){return e}}var w_=1664525,T_=1013904223,E_=4294967296;function D_(){let e=1;return()=>(e=(w_*e+T_)%E_)/E_}var O_=10,k_=Math.PI*(3-Math.sqrt(5));function A_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=D_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function j_(e){var t=C_(.1),n,r,i;typeof e!=`function`&&(e=C_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),P_=e=>e.members.map(e=>e.kind),F_=(e,t)=>P_(e).some(e=>t.includes(e)),I_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function L_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(N_))}function R_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function z_(e,t){let n=L_(e,t.edges);return n.length===1&&e.length>5?R_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||N_(e,t)))}function B_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(N_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(N_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function V_(e,t){let n=t.layout?.primaryPath??[],r=L_(e,B_(t));return r.length===1&&e.length>5?R_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||N_(e,t)}))}function H_(e,t){let n=[...e].sort((e,n)=>I_(n,t.edges)-I_(e,t.edges)||N_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return R_(r)}function U_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(i_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>L_(e,t.edges))}function W_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=L_(r,n),o=L_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>F_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function G_(e,t){let n=e.filter(e=>F_(e,[`initial`])),r=e.filter(e=>F_(e,[`final`]));return[n,...L_(e.filter(e=>!n.includes(e)&&!r.includes(e)),B_(t)),r].filter(e=>e.length)}function K_(e,t,n=0){let r=e.filter(e=>F_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(N_),i.sort(N_)].filter(e=>e.length):n>=2?i.sort(N_).map(e=>[e]):H_(i,t)}function q_(e,t){let n=e.filter(e=>F_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=L_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(N_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:z_},flowchart:{structure:`workflow-spine`,arrange:V_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:H_},deployment:{structure:`runtime-tiers`,arrange:U_},class:{structure:`contract-hierarchy`,arrange:W_},state:{structure:`lifecycle-branches`,arrange:G_},usecase:{structure:`actor-system`,arrange:K_},dataflow:{structure:`process-store`,arrange:q_}});function J_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Y_=156,X_=160,Z_=(e,t,n)=>Math.max(t,Math.min(n,e));function Q_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function $_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function ev(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Y_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Y_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Y_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Y_))}}function tv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function nv(e,t=null){if(!t)try{return x_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=Q_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=ev(t,$_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=A_(o).velocityDecay(.42).force(`anchor-x`,j_(e=>e.anchorX).strength(.16)).force(`anchor-y`,M_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,tv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:Z_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Y_),e.position.x+Y_),y:r?e.position.y:Z_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Y_),e.position.y+Y_)};return t.bounds&&(n.x=Z_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=Z_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!J_(e,d))throw Error(`Arrange would invert template bands`);x_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var rv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function iv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;rv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function ov(e,t,n){let r=av(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function sv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function cv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var lv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]),uv=e=>e.meta?.diagramType===`sequence`?Af:jf;function dv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var fv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,pv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function mv(e,t){if(!fv.test(e))throw Error(`page has no graph-data element`);return e.replace(fv,(e,n,r,i)=>`${n}${pv(t)}${i}`)}function hv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function gv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function _v(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function vv(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function yv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return x_(vv(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function bv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(qg(e,a)),[l,u]=Dd(Jg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:iv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>gv(_,o,l),[_,o,l]),x=e=>{v(e),s(qg(e,a)),u(Jg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new $g,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:b_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(_v(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return x_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return x_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=vv(i,yv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=n_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&dv(a,lv(e),av(i,o,s),void 0,uv(e))||lo(a,i.clientWidth,i.clientHeight,.08,2,ov(i,o,s));return g(c,{duration:n,ease:iv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:iv});return}let i=p.current;if(!i)return;let o=av(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=cv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:iv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(qg(r,a)),u(Jg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=nv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function xv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function Sv(e,t){return e.map(e=>({node:e,rank:xv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Cv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?Sv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function wv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&xv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function Tv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Ev(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Dv(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Ov(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function kv(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Av={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function jv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Av.indent,X.body,Av.line)),o=r+Av.top+Av.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Av.indent,t+r*Av.line,e,`body`)).join(``);return o+=e.length*Av.line+Av.gap,r}).join(``);return{height:o-r+Av.bottom,svg:`${Q(n,r+Av.top,bf(t,`Key points`),`group`)}${s}`}}function Mv(e,t=`light`,n){x_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?jv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Ov(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>kv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Nv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:Mv(e,`light`,r)}))}function Pv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Fv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Iv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=mv(await(await s.getFile()).text(),e),l;try{l=Nv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Fv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Lv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw b_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw b_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Rv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Fv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function zv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Mv(e,t,i),s=`${Pv(e.meta.title)}.${n}`;await Lv(o,e),n===`svg`?Fv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Rv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Bv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=bv(e,s,d,i),[m,h]=o,g=m&&!s,_=Tv(d,()=>p.readGraph(p.currentGraph,0)),v=Cv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=wv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await zv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Iv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Vv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Hv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=sv(p,av(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:iv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:iv})},[e,r,n,t,i,a,o])}var Uv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Wv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Uv[e]})}function Gv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` diff --git a/skills/q-flow/scripts/compile-layout.mjs b/skills/q-flow/scripts/compile-layout.mjs index 447c2fc..ba2f2fe 100644 --- a/skills/q-flow/scripts/compile-layout.mjs +++ b/skills/q-flow/scripts/compile-layout.mjs @@ -13,7 +13,7 @@ import { ASPECT_SLACK, LAYOUT_LIMITS, LAYOUT_TARGETS, OVERVIEW_AREA, layeredDire import { auditLayoutQuality, qualityFailure, requireDiagramQuality } from '../assets/viewer/src/layout-quality.js'; import { compileSequence } from './compile-sequence.mjs'; import { layoutNodeSize, templateDraft, templateOf } from '../assets/viewer/src/layout-templates.js'; -import { hasSharedDependencies, presentationGraph, restorePresentation } from '../assets/viewer/src/presentation-graph.js'; +import { foldedEdges, hasSharedDependencies, presentationGraph, restorePresentation } from '../assets/viewer/src/presentation-graph.js'; import { LAYOUT_VERSION } from '../assets/viewer/src/layout-policy.js'; export { LAYOUT_VERSION }; @@ -407,6 +407,36 @@ function candidateScore(graph, audit, index) { } const compare = (a, b) => { for (let i = 0; i < a.score.length; i++) if (a.score[i] !== b.score[i]) return a.score[i] - b.score[i]; return 0; }; +// Preserve keeps every placed node. A refreshed graph that no longer passes (a new edge without a route, a label that grew +// into its neighbour, a sequence message without a row) is repaired locally before the quality error stands: the named +// edges are rerouted with every node fixed, then their endpoints may move a little; a sequence keeps its columns and +// recomputes its rows. A graph that passes is returned untouched. +function preserveLayout(graph) { + const sequence = getDiagram(diagramTypeOf(graph)).sequence; + const folded = new Set(foldedEdges(graph).map(edge => edge.id)); + const placed = graph.edges.every(edge => folded.has(edge.id) || (sequence ? Number.isFinite(edge.route?.messageY) : edge.route)); + let failure; + if (placed) { try { requireDiagramQuality(graph); return { graph }; } catch (error) { failure = error; } } + const check = output => { requireDiagramQuality(output); return output; }; + if (sequence) { + try { return { graph: check(compileSequence(graph, Number(/^sequence-(\d+)$/.exec(graph.layout?.strategy ?? '')?.[1] ?? 0), { keepColumns: true })), repair: { rows: true, rerouted: [], movedNodeIds: [] } }; } + catch { /* the original diagnostics below */ } + } else if (!isArchitectureOverview(graph)) { + const shown = hasSharedDependencies(graph) ? presentationGraph(graph) : graph; + const named = new Set((failure?.diagnostics ?? []).filter(item => item.severity === 'error').flatMap(item => item.elementIds)); + const edgeIds = shown.edges.filter(edge => !edge.route || named.has(edge.id)).map(edge => edge.id); + const ends = [...new Set(shown.edges.filter(edge => edgeIds.includes(edge.id)).flatMap(edge => [edge.source, edge.target]))]; + for (const options of [{ move: false, evaluations: 4, passes: 2 }, ...ends.map(focusId => ({ move: true, focusId, evaluations: 12, passes: 1 }))]) { + try { + const result = refineDiagramLayout(shown, { ...options, edgeIds }); + return { graph: check(shown === graph ? result.graph : restorePresentation(graph, result.graph)), repair: { rerouted: edgeIds, movedNodeIds: result.movedNodeIds } }; + } catch { /* next: let an endpoint move */ } + } + } + requireDiagramQuality(graph); // repair found nothing better: the original diagnostics stand + return { graph }; +} + export async function compileGraphLayout(input, { layout = 'auto', timeoutMs = LAYOUT_TIMEOUT_MS } = {}) { if (!['auto', 'preserve'].includes(layout)) throw new Error('layout must be auto or preserve'); const errors = validateGraph(input, { inputOnly: true }); @@ -424,8 +454,8 @@ export async function compileGraphLayout(input, { layout = 'auto', timeoutMs = L const ownershipErrors = validateGraph(graph, { inputOnly: true }); if (ownershipErrors.length) throw qualityFailure(graph, 'semantic', ownershipErrors.join('\n')); if (layout === 'preserve') { - requireDiagramQuality(graph); - return { graph, report: { version: LAYOUT_VERSION, mode: layout, migration, semantics: semanticReport(graph) } }; + const { graph: output, repair } = preserveLayout(graph); + return { graph: output, report: { version: LAYOUT_VERSION, mode: layout, migration, ...(repair ? { repair } : {}), semantics: semanticReport(output) } }; } if (isArchitectureOverview(graph)) { let output; diff --git a/skills/q-flow/scripts/compile-sequence.mjs b/skills/q-flow/scripts/compile-sequence.mjs index a2fa1cc..8f7252d 100644 --- a/skills/q-flow/scripts/compile-sequence.mjs +++ b/skills/q-flow/scripts/compile-sequence.mjs @@ -6,22 +6,26 @@ import { sequenceMessageLabel, sequenceExecutions, spreadParticipants } from '.. import { layoutText } from '../assets/viewer/src/text-layout.js'; import { LAYOUT_LIMITS, LAYOUT_TARGETS } from '../assets/viewer/src/layout-spacing.js'; -export function compileSequence(input, candidate) { +export function compileSequence(input, candidate, { keepColumns = false } = {}) { const graph = structuredClone(input), groups = graph.groups ?? [], edges = new Map(graph.edges.map(edge => [edge.id, edge])); - // Without declared order, participants stand in the order the messages first reach them, initiator leftmost. - const firstSeen = new Map(); + // Without declared order, participants stand in the order the messages first reach them, initiator leftmost. A laid-out + // view keeps the order its reader already knows, so removing a participant's first message never reshuffles columns. + const firstSeen = new Map(), placed = graph.nodes.every(node => node.position); for (const edge of [...graph.edges].sort((a, b) => a.order - b.order)) for (const id of [edge.source, edge.target]) if (!firstSeen.has(id)) firstSeen.set(id, firstSeen.size); - const ordered = graph.layout?.participantOrder ?? [...graph.nodes].sort((a, b) => (a.layout?.order ?? 0) - (b.layout?.order ?? 0) || (firstSeen.get(a.id) ?? Infinity) - (firstSeen.get(b.id) ?? Infinity) || (a.id < b.id ? -1 : 1)).map(node => node.id); + const rank = node => placed ? node.position.x : firstSeen.get(node.id) ?? Infinity; + const ordered = graph.layout?.participantOrder ?? [...graph.nodes].sort((a, b) => (a.layout?.order ?? 0) - (b.layout?.order ?? 0) || rank(a) - rank(b) || (a.id < b.id ? -1 : 1)).map(node => node.id); const nodes = ordered.map(id => graph.nodes.find(node => node.id === id)); // Participant spacing starts at the quality floor, so the tightest message gap is not discarded with a too-narrow row. const spacing = LAYOUT_LIMITS.nodeGap + candidate * 8, gap = 12 + candidate * 4; const guardText = (group, operand) => group.kind === 'par' ? operand.label : `${group.kind === 'loop' ? `${group.loop.min}..${group.loop.max} ` : ''}[${operand.guard}]`; const guardLayout = (group, operand) => layoutText(guardText(group, operand), LAYOUT_TARGETS.labelWidth, 14, 20); const bodyLayout = operand => layoutText(operand.body, LAYOUT_TARGETS.labelWidth, 16, 24); + // keepColumns (preserve repair): placed participants stay where they are unless a wider head needs room; rows are recomputed. let x = 32; for (const node of nodes) { - node.size = minimumNodeSize(node, 'sequence', graph.meta.locale); node.position = { x, y: 48 }; - x += node.size.width + spacing; + const kept = keepColumns && placed ? node.position.x : x; + node.size = minimumNodeSize(node, 'sequence', graph.meta.locale); node.position = { x: Math.max(x, kept), y: 48 }; + x = node.position.x + node.size.width + spacing; } spreadParticipants(graph, nodes); // Provisional order-preserving times let the shared router measure actual diff --git a/skills/q-flow/scripts/composition-review.test.mjs b/skills/q-flow/scripts/composition-review.test.mjs index 582322a..eeb93b3 100644 --- a/skills/q-flow/scripts/composition-review.test.mjs +++ b/skills/q-flow/scripts/composition-review.test.mjs @@ -240,3 +240,43 @@ test('folded shared dependencies keep every edge in the model and draw as tags o assert.match(svg, />v2 { + const { createEdgeRoutes } = await import('../assets/viewer/src/edge-routing.js'); + const state = { meta: meta('state'), nodes: [{ id: 'i', label: 'start', kind: 'initial' }, ...['a', 'b', 'c'].map(id => ({ id, label: `state ${id}`, kind: 'state', module: 'order' })), { id: 'f', label: 'done', kind: 'final' }], + edges: [['i', 'a'], ['a', 'b'], ['b', 'c'], ['c', 'f']].map(([source, target], i) => ({ id: `s${i}`, source, target, kind: 'transition', label: 'next', evidence: 'inference' })) }; + const { graph: laid } = await compileGraphLayout(state); + const same = await compileGraphLayout(laid, { layout: 'preserve' }); + assert.deepEqual(same.graph, laid); assert.equal(same.report.repair, undefined); + const grown = structuredClone(laid); + grown.edges.push({ id: 'cancel', source: 'a', target: 'c', kind: 'transition', label: 'cancel after six polls', evidence: 'inference' }); + const added = await compileGraphLayout(grown, { layout: 'preserve' }); + assert.deepEqual(added.graph.nodes.map(node => node.position), laid.nodes.map(node => node.position)); + assert.ok(added.graph.edges.find(edge => edge.id === 'cancel').route); + assert.deepEqual(added.report.repair.movedNodeIds, []); + const crowded = structuredClone(laid); + crowded.edges[2].route = { ...crowded.edges[2].route, labelAt: createEdgeRoutes(laid).get('s1').labelPoint }; + assert.throws(() => requireDiagramQuality(crowded)); + const moved = await compileGraphLayout(crowded, { layout: 'preserve' }); + assert.deepEqual(moved.graph.nodes.map(node => node.position), laid.nodes.map(node => node.position)); + assert.ok(moved.report.repair.rerouted.includes('s2')); +}); + +test('preserve gives a new sequence message its row without moving a column; auto keeps the column order a reader knows', async () => { + const { graph: laid } = await compileGraphLayout(longSequence(4, 6)); + const grown = structuredClone(laid); + for (const edge of grown.edges) if (edge.order >= 4) edge.order++; + grown.edges.push({ id: 'late', source: 'p0', target: 'p2', kind: 'async', label: 'late event', order: 4, evidence: 'source' }); + const { graph: kept, report } = await compileGraphLayout(grown, { layout: 'preserve' }); + assert.equal(report.repair.rows, true); + assert.deepEqual(kept.nodes.map(node => node.position.x), laid.nodes.map(node => node.position.x)); + const rows = [...kept.edges].sort((a, b) => a.order - b.order).map(edge => edge.route.messageY); + assert.ok(rows.every((y, i) => !i || y > rows[i - 1]), 'rows follow message order'); + const talk = { meta: meta('sequence'), nodes: ['a', 'b', 'c'].map(id => ({ id, label: `Service ${id}`, kind: 'service' })), + edges: [['a', 'c'], ['c', 'b'], ['a', 'b']].map(([source, target], i) => ({ id: `m${i}`, source, target, kind: 'async', label: `event ${i}`, order: i + 1, evidence: 'source' })) }; + const columns = graph => [...graph.nodes].sort((x, y) => x.position.x - y.position.x).map(node => node.id); + const { graph: first } = await compileGraphLayout(talk); + assert.deepEqual(columns(first), ['a', 'c', 'b']); + const { graph: again } = await compileGraphLayout({ ...first, edges: first.edges.filter(edge => edge.id !== 'm0') }); + assert.deepEqual(columns(again), ['a', 'c', 'b'], 'removing a participant\'s first message keeps its column'); +}); diff --git a/skills/q-flow/scripts/generate-viewer.mjs b/skills/q-flow/scripts/generate-viewer.mjs index dcd069d..7b6ebf4 100644 --- a/skills/q-flow/scripts/generate-viewer.mjs +++ b/skills/q-flow/scripts/generate-viewer.mjs @@ -122,6 +122,9 @@ async function main() { semantic: { status: status('semantic') }, geometry: { status: status('geometry') }, rendering: { status: status('rendering') }, ...(warnings.length + oversized.length ? { warnings: warnings.length + oversized.length } : {}) }; + // Preserve repairs are reported so the author can see which routes or rows changed without rendering the page. + const repaired = compiled.flatMap((item, i) => item.report?.repair ? [{ view: viewIdOf(views[i]) ?? i, ...(item.report.repair.rows ? { rows: true } : { rerouted: item.report.repair.rerouted, moved: item.report.repair.movedNodeIds }) }] : []); + if (repaired.length) summary.repaired = repaired; const detail = values.verbose ? { layoutComposition: graphs.map(layoutComposition), layout: compiled.map(item => item.report), quality } : {}; console.log(JSON.stringify(graphs.length === 1 && !Object.hasOwn(graph, 'diagrams') ? { generated: true, diagramType: diagramTypeOf(graphs[0]), outputDir, files, ...summary, ...detail, sourceEvidence } From e92591086e29ae2cb63c60a0da1d8b6ebe63a4b5 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 11:57:58 +0800 Subject: [PATCH 07/16] =?UTF-8?q?feat(drift):=20=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=94=B9=E5=8A=A8=E6=A0=87=E5=88=B0=E5=9B=BE=E4=B8=8A=E2=80=94?= =?UTF-8?q?=E2=80=94=E5=BE=85=E5=8A=9E=E5=B8=A6=E5=85=83=E7=B4=A0=20ID?= =?UTF-8?q?=E3=80=81=E7=94=9F=E6=88=90=E6=97=B6=E6=A0=87=E5=87=BA=E5=8F=97?= =?UTF-8?q?=E5=BD=B1=E5=93=8D=E5=85=83=E7=B4=A0=E3=80=81--changes=20?= =?UTF-8?q?=E8=BE=93=E5=87=BA=20PR=20=E8=AF=84=E8=AE=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + docs/readme/README.de.md | 2 + docs/readme/README.es.md | 2 + docs/readme/README.ja.md | 2 + docs/readme/README.pt.md | 2 + docs/readme/README.ru.md | 2 + docs/readme/README.zh-CN.md | 2 + skills/q-flow/assets/viewer-dist/index.html | 15 ++--- .../assets/viewer/src/DiagramCanvas.jsx | 12 ++-- .../q-flow/assets/viewer/src/ViewerShell.jsx | 26 ++++++--- .../assets/viewer/src/i18n-messages.json | 40 ++++++++++--- .../assets/viewer/src/source-changes.js | 4 ++ skills/q-flow/assets/viewer/src/styles.css | 7 +++ skills/q-flow/references/graph-schema.md | 2 +- skills/q-flow/scripts/generate-viewer.mjs | 5 +- skills/q-flow/scripts/source-drift.mjs | 38 +++++++------ skills/q-flow/scripts/source-drift.test.mjs | 22 +++++++- skills/q-flow/scripts/validate-graph.mjs | 56 +++++++++++++++---- 18 files changed, 184 insertions(+), 57 deletions(-) create mode 100644 skills/q-flow/assets/viewer/src/source-changes.js diff --git a/README.md b/README.md index 00923b9..3a7fe03 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +To see the impact on the pull request, add `--changes changes.md` to the validate line and post the file when it fails, for example `gh pr comment "$PR" --body-file changes.md` (needs `pull-requests: write`). It lists, per view, the elements each change touches, the file and line, and the old and new code. The page regenerated after `--fix` also marks those elements and lists the changes beside the key points. + When it fails, ask the skill to refresh that diagram: ```text diff --git a/docs/readme/README.de.md b/docs/readme/README.de.md index e506fee..8c42ff5 100644 --- a/docs/readme/README.de.md +++ b/docs/readme/README.de.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +Um die Auswirkungen im Pull Request zu sehen, ergänzen Sie die validate-Zeile um `--changes changes.md` und posten die Datei bei einem Fehler als Kommentar, etwa mit `gh pr comment "$PR" --body-file changes.md` (benötigt `pull-requests: write`). Sie listet je Ansicht die Elemente, die jede Änderung berührt, Datei und Zeile sowie alten und neuen Code. Die nach `--fix` neu erzeugte Seite markiert diese Elemente ebenfalls und listet die Änderungen neben den Kernaussagen. + Schlägt er fehl, den Skill bitten, dieses Diagramm zu aktualisieren: ```text diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index 77958e0..0b564e4 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +Para ver el impacto en la pull request, añade `--changes changes.md` a la línea de validate y, si falla, publica el archivo como comentario, por ejemplo con `gh pr comment "$PR" --body-file changes.md` (requiere `pull-requests: write`). Enumera, por vista, los elementos que toca cada cambio, el archivo y la línea, y el código anterior y el nuevo. La página regenerada después de `--fix` también marca esos elementos y enumera los cambios junto a los puntos clave. + Si falla, pedir a la habilidad que actualice ese diagrama: ```text diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index 9cfc8f2..f6f4244 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +影響箇所をプルリクエストで確認したい場合は、validate の行に `--changes changes.md` を追加し、失敗したときにそのファイルをコメントとして投稿します(例:`gh pr comment "$PR" --body-file changes.md`、`pull-requests: write` 権限が必要)。ビューごとに、各変更が触れる要素、ファイルと行、変更前後のコードが一覧になります。`--fix` の後に再生成したページでも、それらの要素に印が付き、要点の横に変更が一覧表示されます。 + 失敗したら、スキルにその図の更新を頼みます。 ```text diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md index fbb9909..58f4d48 100644 --- a/docs/readme/README.pt.md +++ b/docs/readme/README.pt.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +Para ver o impacto no pull request, adicione `--changes changes.md` à linha de validate e, quando falhar, publique o arquivo como comentário, por exemplo com `gh pr comment "$PR" --body-file changes.md` (requer `pull-requests: write`). Ele lista, por visão, os elementos que cada mudança toca, o arquivo e a linha, e o código antigo e o novo. A página regenerada após `--fix` também marca esses elementos e lista as mudanças ao lado dos pontos-chave. + Quando falhar, peça à habilidade para atualizar o diagrama: ```text diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index 16ae68f..66bbb94 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +Чтобы увидеть затронутые места прямо в pull request, добавьте `--changes changes.md` в строку validate и при ошибке опубликуйте файл комментарием, например `gh pr comment "$PR" --body-file changes.md` (нужно разрешение `pull-requests: write`). В нём по каждому представлению перечислены элементы, которых касается изменение, файл и строка, а также старый и новый код. Страница, заново созданная после `--fix`, тоже отмечает эти элементы и перечисляет изменения рядом с ключевыми выводами. + Если проверка не прошла, попросите навык обновить диаграмму: ```text diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index e9b99de..e4255d0 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -256,6 +256,8 @@ jobs: exit ${failed:-0} ``` +想在 PR 里直接看到受影响的地方,就在 validate 那一行加上 `--changes changes.md`,失败时把这个文件贴成评论,例如 `gh pr comment "$PR" --body-file changes.md`(需要 `pull-requests: write` 权限)。它按视图列出每处改动碰到的元素、文件和行号,以及改动前后的代码。执行 `--fix` 后重新生成的页面也会标出这些元素,并在要点旁列出这些改动。 + 失败后,让技能刷新这张图: ```text diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index 70588d2..2021b17 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -234,7 +234,7 @@ `,` +`).split(` `));return[t,t.reduce((e,t)=>e.concat(...t),[])]}return[[],[]]},[e]);return(0,y.useEffect)(()=>{let n=t?.target??qc,c=t?.actInsideInputWithModifier??!0;if(e!==null){let e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!c)&&So(e))return!1;let n=Xc(e.code,s);if(a.current.add(e[n]),Yc(o,a.current,!1)){let n=e.composedPath?.()?.[0]||e.target,a=n?.nodeName===`BUTTON`||n?.nodeName===`A`;t.preventDefault!==!1&&(i.current||!a)&&e.preventDefault(),r(!0)}},l=e=>{let t=Xc(e.code,s);Yc(o,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(e[t]),e.key===`Meta`&&a.current.clear(),i.current=!1},u=()=>{a.current.clear(),r(!1)};return n?.addEventListener(`keydown`,e),n?.addEventListener(`keyup`,l),window.addEventListener(`blur`,u),window.addEventListener(`contextmenu`,u),()=>{n?.removeEventListener(`keydown`,e),n?.removeEventListener(`keyup`,l),window.removeEventListener(`blur`,u),window.removeEventListener(`contextmenu`,u)}}},[e,r]),n}function Yc(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function Xc(e,t){return t.includes(e)?`code`:`key`}var Zc=()=>{let e=bc();return(0,y.useMemo)(()=>({zoomIn:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):!1},zoomOut:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):!1},zoomTo:async(t,n)=>{let{panZoom:r}=e.getState();return r?r.scaleTo(t,n):!1},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,i,a],panZoom:o}=e.getState();return o?(await o.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??a},n),!0):!1},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:i,minZoom:a,maxZoom:o,panZoom:s}=e.getState(),c=lo(t,r,i,a,o,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0):!1},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:i,snapToGrid:a,domNode:o}=e.getState();if(!o)return t;let{x:s,y:c}=o.getBoundingClientRect(),l={x:t.x-s,y:t.y-c},u=n.snapGrid??i;return io(l,r,n.snapToGrid??a,u)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:i,y:a}=r.getBoundingClientRect(),o=ao(t,n);return{x:o.x+i,y:o.y+a}}}),[])};function Qc(e,t){let n=[],r=new Map,i=[];for(let t of e)if(t.type===`add`){i.push(t);continue}else if(t.type===`remove`||t.type===`replace`)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if(t[0].type===`remove`)continue;if(t[0].type===`replace`){n.push({...t[0].item});continue}let i={...e};for(let e of t)$c(e,i);n.push(i)}return i.length&&i.forEach(e=>{e.index===void 0?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function $c(e,t){switch(e.type){case`select`:t.selected=e.selected;break;case`position`:e.position!==void 0&&(t.position=e.position),e.dragging!==void 0&&(t.dragging=e.dragging);break;case`dimensions`:e.dimensions!==void 0&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes===`width`)&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes===`height`)&&(t.height=e.dimensions.height))),typeof e.resizing==`boolean`&&(t.resizing=e.resizing)}}function el(e,t){return Qc(e,t)}function tl(e,t){return Qc(e,t)}function nl(e,t){return{id:e,type:`select`,selected:t}}function rl(e,t=new Set,n=!1){let r=[];for(let[i,a]of e){let e=t.has(i);!(a.selected===void 0&&!e)&&a.selected!==e&&(n&&(a.selected=e),r.push(nl(a.id,e)))}return r}function il({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,i]of e.entries()){let e=t.get(i.id),a=e?.internals?.userNode??e;a!==void 0&&a!==i&&n.push({id:i.id,item:i,type:`replace`}),a===void 0&&n.push({item:i,type:`add`,index:r})}for(let[e]of t)r.get(e)===void 0&&n.push({id:e,type:`remove`});return n}function al(e){return{id:e.id,type:`remove`}}var ol=no(`React Flow`,`https://reactflow.dev/`);function sl(e,t,n={}){return Fo(e,t,{...n,onError:n.onError??ol})}var cl=e=>Aa(e),ll=e=>ka(e);function ul(e){return(0,y.forwardRef)(e)}var dl=typeof window<`u`?y.useLayoutEffect:y.useEffect;function fl(e){let[t,n]=(0,y.useState)(BigInt(0)),[r]=(0,y.useState)(()=>pl(()=>n(e=>e+BigInt(1))));return dl(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}function pl(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var ml=(0,y.createContext)(null);function hl({children:e}){let t=bc(),n=fl((0,y.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:a,nodeLookup:o,fitViewQueued:s,onNodesChangeMiddlewareMap:c}=t.getState(),l=n;for(let t of e)l=typeof t==`function`?t(l):t;let u=il({items:l,lookup:o});for(let e of c.values())u=e(u);i&&r(l),u.length>0?a?.(u):s&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=fl((0,y.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:a,edgeLookup:o}=t.getState(),s=n;for(let t of e)s=typeof t==`function`?t(s):t;i?r(s):a&&a(il({items:s,lookup:o}))},[])),i=(0,y.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,x.jsx)(ml.Provider,{value:i,children:e})}function gl(){let e=(0,y.useContext)(ml);if(!e)throw Error(`useBatchContext must be used within a BatchProvider`);return e}var _l=e=>!!e.panZoom;function vl(){let e=Zc(),t=bc(),n=gl(),r=G(_l),i=(0,y.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},a=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),i=cl(e)?e:n.get(e.id),a=i.parentId?po(i.position,i.measured,i.parentId,n,r):i.position;return Ya({...i,position:a,width:i.measured?.width??i.width,height:i.measured?.height??i.height})},o=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&cl(e)?e:{...r,...e}}return r}))},s=(e,t,n={replace:!1})=>{i(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&ll(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,a,o]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:i,y:a,zoom:o}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:i,onNodesDelete:a,onEdgesDelete:o,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:l,onBeforeDelete:u}=t.getState(),{nodes:d,edges:f}=await Ba({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:u}),p=f.length>0,m=d.length>0;if(p){let e=f.map(al);o?.(f),c(e)}if(m){let e=d.map(al);a?.(d),s(e)}return(m||p)&&l?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let i=eo(e),o=i?e:a(e),s=r!==void 0;return o?(r||t.getState().nodes).filter(r=>{let a=t.getState().nodeLookup.get(r.id);if(a&&!i&&(r.id===e.id||!a.internals.positionAbsolute))return!1;let c=Ya(s?r:a),l=$a(c,o);return n&&l>0||l>=c.width*c.height||l>=o.width*o.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=eo(e)?e:a(e);if(!r)return!1;let i=$a(r,t);return n&&i>0||i>=t.width*t.height||i>=r.width*r.height},updateNode:o,updateNodeData:(e,t,n={replace:!1})=>{o(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return Na(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:``}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:``}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??ho();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,y.useMemo)(()=>({...i,...e,viewportInitialized:r}),[r])}var yl=e=>e.selected,bl=typeof window<`u`?window:void 0;function xl({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=bc(),{deleteElements:r}=vl(),i=Jc(e,{actInsideInputWithModifier:!1}),a=Jc(t,{target:bl});(0,y.useEffect)(()=>{if(i){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(yl),edges:e.filter(yl)}),n.setState({nodesSelectionActive:!1})}},[i]),(0,y.useEffect)(()=>{n.setState({multiSelectionActive:a})},[a])}function Sl(e){let t=bc();(0,y.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;let n=yo(e.current);(n.height===0||n.width===0)&&t.getState().onError?.(`004`,va.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener(`resize`,n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener(`resize`,n),t&&e.current&&t.unobserve(e.current)}}},[])}var Cl={position:`absolute`,width:`100%`,height:`100%`,top:0,left:0},wl=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function Tl({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panActivationKeyPressed:i,panOnScrollSpeed:a=.5,panOnScrollMode:o=Ca.Free,zoomOnDoubleClick:s=!0,panOnDrag:c=!0,defaultViewport:l,translateExtent:u,minZoom:d,maxZoom:f,zoomActivationKeyCode:p,preventScrolling:m=!0,children:h,noWheelClassName:g,noPanClassName:_,onViewportChange:v,isControlledViewport:b,paneClickDistance:S,selectionOnDrag:C}){let w=bc(),T=(0,y.useRef)(null),{userSelectionActive:E,lib:D,connectionInProgress:O}=G(wl,hc),k=Jc(p),A=(0,y.useRef)();Sl(T);let j=(0,y.useCallback)(e=>{v?.({x:e[0],y:e[1],zoom:e[2]}),b||w.setState({transform:e})},[v,b]);return(0,y.useEffect)(()=>{if(T.current){A.current=Ws({domNode:T.current,minZoom:d,maxZoom:f,translateExtent:u,viewport:l,onDraggingChange:e=>w.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=w.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=w.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=w.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=A.current.getViewport();return w.setState({panZoom:A.current,transform:[e,t,n],domNode:T.current.closest(`.react-flow`)}),()=>{A.current?.destroy()}}},[]),(0,y.useEffect)(()=>{A.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panActivationKeyPressed:i,panOnScrollSpeed:a,panOnScrollMode:o,zoomOnDoubleClick:s,panOnDrag:c,zoomActivationKeyPressed:k,preventScrolling:m,noPanClassName:_,userSelectionActive:E,noWheelClassName:g,lib:D,onTransformChange:j,connectionInProgress:O,selectionOnDrag:C,paneClickDistance:S})},[e,t,n,r,i,a,o,s,c,k,m,_,E,g,D,j,O,C,S]),(0,x.jsx)(`div`,{className:`react-flow__renderer`,ref:T,style:Cl,children:h})}var El=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Dl(){let{userSelectionActive:e,userSelectionRect:t}=G(El,hc);return e&&t?(0,x.jsx)(`div`,{className:`react-flow__selection react-flow__container`,style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var Ol=(e,t)=>n=>{n.target===t.current&&e?.(n)},kl=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function Al({isSelecting:e,selectionKeyPressed:t,selectionMode:n=wa.Full,panOnDrag:r,autoPanOnSelection:i,paneClickDistance:a,selectionOnDrag:o,onSelectionStart:s,onSelectionEnd:c,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:d,onPaneMouseEnter:f,onPaneMouseMove:p,onPaneMouseLeave:m,children:h}){let g=(0,y.useRef)(0),_=bc(),{userSelectionActive:v,elementsSelectable:b,dragging:C,panBy:w,autoPanSpeed:T}=G(kl,hc),E=b&&(e||v),D=(0,y.useRef)(null),O=(0,y.useRef)(),k=(0,y.useRef)(new Set),A=(0,y.useRef)(new Set),j=(0,y.useRef)(!1),M=(0,y.useRef)(!1),N=(0,y.useRef)({x:0,y:0}),P=(0,y.useRef)(!1),ee=e=>{if(M.current||j.current||_.getState().connection.inProgress){M.current=!1,j.current=!1;return}l?.(e),_.getState().resetSelectedElements(),_.setState({nodesSelectionActive:!1})},F=e=>{if(Array.isArray(r)&&r?.includes(2)){e.preventDefault();return}u?.(e)},I=d?e=>d(e):void 0,te=e=>{M.current&&=(e.stopPropagation(),!1)},ne=n=>{if(n.pointerType===`touch`&&r!==!1&&!t)return;let{domNode:i,transform:a}=_.getState();if(O.current=i?.getBoundingClientRect(),!O.current)return;let s=n.target===D.current;if(!s&&n.target.closest(`.nokey`)||!e||!(o&&s||t)||n.button!==0||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),M.current=!1;let{x:c,y:l}=wo(n.nativeEvent,O.current),u=io({x:c,y:l},a);_.setState({userSelectionRect:{width:0,height:0,startX:u.x,startY:u.y,x:c,y:l}}),s||(n.stopPropagation(),n.preventDefault())};function L(e,t){let{userSelectionRect:r}=_.getState();if(!r)return;let{transform:i,nodeLookup:a,edgeLookup:o,connectionLookup:s,triggerNodeChanges:c,triggerEdgeChanges:l,defaultEdgeOptions:u}=_.getState(),d={x:r.startX,y:r.startY},{x:f,y:p}=ao(d,i),m={startX:d.x,startY:d.y,x:ee.id)),A.current=new Set;let v=u?.selectable??!0;for(let e of k.current){let t=s.get(e);if(t)for(let{edgeId:e}of t.values()){let t=o.get(e);t&&(t.selectable??v)&&A.current.add(e)}}mo(h,k.current)||c(rl(a,k.current,!0)),mo(g,A.current)||l(rl(o,A.current)),_.setState({userSelectionRect:m,userSelectionActive:!0,nodesSelectionActive:!1})}function R(){if(!i||!O.current)return;let[e,t]=Ga(N.current,O.current,T);w({x:e,y:t}).then(e=>{if(!M.current||!e){g.current=requestAnimationFrame(R);return}let{x:t,y:n}=N.current;L(t,n),g.current=requestAnimationFrame(R)})}let z=()=>{cancelAnimationFrame(g.current),g.current=0,P.current=!1};(0,y.useEffect)(()=>()=>z(),[]);let B=e=>{let{userSelectionRect:n,transform:r,resetSelectedElements:i}=_.getState();if(!O.current||!n)return;let{x:o,y:c}=wo(e.nativeEvent,O.current);N.current={x:o,y:c};let l=ao({x:n.startX,y:n.startY},r);if(!M.current){let n=t?0:a;if(Math.hypot(o-l.x,c-l.y)<=n)return;i(),s?.(e)}M.current=!0,P.current||=(R(),!0),L(o,c)},re=e=>{if(!E){e.target===D.current&&_.getState().connection.inProgress&&(j.current=!0);return}e.button===0&&(e.target?.releasePointerCapture?.(e.pointerId),!v&&e.target===D.current&&_.getState().userSelectionRect&&ee?.(e),_.setState({userSelectionActive:!1,userSelectionRect:null}),M.current&&(c?.(e),_.setState({nodesSelectionActive:k.current.size>0})),z())},ie=e=>{e.target?.releasePointerCapture?.(e.pointerId),z()},ae=r===!0||Array.isArray(r)&&r.includes(0);return(0,x.jsxs)(`div`,{className:S([`react-flow__pane`,{draggable:ae,dragging:C,selection:e}]),onClick:E?void 0:Ol(ee,D),onContextMenu:Ol(F,D),onWheel:Ol(I,D),onPointerEnter:E?void 0:f,onPointerMove:E?B:p,onPointerUp:re,onPointerCancel:E?ie:void 0,onPointerDownCapture:E?ne:void 0,onClickCapture:E?te:void 0,onPointerLeave:m,ref:D,style:Cl,children:[h,(0,x.jsx)(Dl,{})]})}function jl({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:o,nodeLookup:s,onError:c}=t.getState(),l=s.get(e);if(!l){c?.(`012`,va.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&o)&&(a({nodes:[l],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):i([e])}function Ml({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,nodeClickDistance:o}){let s=bc(),[c,l]=(0,y.useState)(!1),u=(0,y.useRef)();return(0,y.useEffect)(()=>{if(!t)return u.current=ys({getStoreItems:()=>s.getState(),onNodeMouseDown:t=>{jl({id:t,store:s,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}}),()=>{u.current?.destroy(),u.current=void 0}},[t,s,e]),(0,y.useEffect)(()=>{t||!e.current||!u.current||u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:a,nodeId:i,nodeClickDistance:o})},[n,r,t,a,e,i,o]),c}var Nl=e=>t=>t.selected&&(t.draggable||e&&t.draggable===void 0);function Pl(){let e=bc();return(0,y.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:a,onError:o,updateNodePositions:s,nodeLookup:c,nodeOrigin:l}=e.getState(),u=new Map,d=Nl(a),f=r?i[0]:5,p=r?i[1]:5,m=t.direction.x*f*t.factor,h=t.direction.y*p*t.factor;for(let[,e]of c){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+h};r&&(t=ro(t,i));let{position:a,positionAbsolute:s}=za({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:l,onError:o});e.position=a,e.internals.positionAbsolute=s,u.set(e.id,e)}s(u)},[])}var Fl=(0,y.createContext)(null),Il=Fl.Provider;Fl.Consumer;var Ll=()=>(0,y.useContext)(Fl),Rl=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),zl=(0,y.createContext)(null);function Bl({children:e}){let t=G(Rl,hc);return(0,x.jsx)(zl.Provider,{value:t,children:e})}function K(){let e=(0,y.useContext)(zl);if(!e)throw Error(`useHandleConfig must be used within a HandleConfigProvider`);return e}var q={connectingFrom:!1,connectingTo:!1,clickConnecting:!1,isPossibleEndHandle:!0,connectionInProcess:!1,clickConnectionInProcess:!1,valid:!1},Vl=(e,t,n)=>r=>{let{connectionClickStartHandle:i,connectionMode:a,connection:o}=r,{fromHandle:s,toHandle:c,isValid:l}=o;if(!s&&!i)return q;let u=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:u,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:a===Sa.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:u&&l}};function Hl({type:e=`source`,position:t=H.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:o,onConnect:s,children:c,className:l,onMouseDown:u,onTouchStart:d,...f},p){let m=o||null,h=e===`target`,g=bc(),_=Ll(),{connectOnClick:v,noPanClassName:y,rfId:b}=K(),{connectingFrom:C,connectingTo:w,clickConnecting:T,isPossibleEndHandle:E,connectionInProcess:D,clickConnectionInProcess:O,valid:k}=G(Vl(_,m,e),hc);_||g.getState().onError?.(`010`,va.error010());let A=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=g.getState(),i={...t,...e};if(r){let{edges:e,setEdges:t,onError:n}=g.getState();t(sl(i,e,{onError:n}))}n?.(i),s?.(i)},j=e=>{if(!_)return;let t=Co(e.nativeEvent);if(i&&(t&&e.button===0||!t)){let t=g.getState();ks.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:h,handleId:m,nodeId:_,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>g.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:A,isValidConnection:n||((...e)=>g.getState().isValidConnection?.(...e)??!0),getTransform:()=>g.getState().transform,getFromHandle:()=>g.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):d?.(e)};return(0,x.jsx)(`div`,{"data-handleid":m,"data-nodeid":_,"data-handlepos":t,"data-id":`${b}-${_}-${m}-${e}`,className:S([`react-flow__handle`,`react-flow__handle-${t}`,`nodrag`,y,l,{source:!h,target:h,connectable:r,connectablestart:i,connectableend:a,clickconnecting:T,connectingfrom:C,connectingto:w,valid:k,connectionindicator:r&&(!D||E)&&(D||O?a:i)}]),onMouseDown:j,onTouchStart:j,onClick:v?t=>{let{onClickConnectStart:r,onClickConnectEnd:a,connectionClickStartHandle:o,connectionMode:s,isValidConnection:c,lib:l,rfId:u,nodeLookup:d,connection:f}=g.getState();if(!_||!o&&!i)return;if(!o){r?.(t.nativeEvent,{nodeId:_,handleId:m,handleType:e}),g.setState({connectionClickStartHandle:{nodeId:_,type:e,id:m}});return}let p=bo(t.target),h=n||c,{connection:v,isValid:y}=ks.isValid(t.nativeEvent,{handle:{nodeId:_,id:m,type:e},connectionMode:s,fromNodeId:o.nodeId,fromHandleId:o.id||null,fromType:o.type,isValidConnection:h,flowId:u,doc:p,lib:l,nodeLookup:d});y&&v&&A(v);let b=structuredClone(f);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,a?.(t,b),g.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f,children:c})}var Ul=(0,y.memo)(ul(Hl));function Wl({data:e,isConnectable:t,sourcePosition:n=H.Bottom}){return(0,x.jsxs)(x.Fragment,{children:[e?.label,(0,x.jsx)(Ul,{type:`source`,position:n,isConnectable:t})]})}function Gl({data:e,isConnectable:t,targetPosition:n=H.Top,sourcePosition:r=H.Bottom}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{type:`target`,position:n,isConnectable:t}),e?.label,(0,x.jsx)(Ul,{type:`source`,position:r,isConnectable:t})]})}function Kl(){return null}function ql({data:e,isConnectable:t,targetPosition:n=H.Top}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{type:`target`,position:n,isConnectable:t}),e?.label]})}var Jl={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Yl={input:Wl,default:Gl,output:ql,group:Kl};function Xl(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var Zl=e=>{let{width:t,height:n,x:r,y:i}=Pa(e.nodeLookup,{filter:e=>!!e.selected});return{width:to(t)?t:null,height:to(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function Ql({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=bc(),{width:i,height:a,transformString:o,userSelectionActive:s}=G(Zl,hc),c=Pl(),l=(0,y.useRef)(null);(0,y.useEffect)(()=>{n||l.current?.focus({preventScroll:!0})},[n]);let u=!s&&i!==null&&a!==null;if(Ml({nodeRef:l,disabled:!u}),!u)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,x.jsx)(`div`,{className:S([`react-flow__nodesselection`,`react-flow__container`,t]),style:{transform:o},children:(0,x.jsx)(`div`,{ref:l,className:`react-flow__nodesselection-rect`,onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(Jl,e.key)&&(e.preventDefault(),c({direction:Jl[e.key],factor:e.shiftKey?4:1}))},style:{width:i,height:a}})})}var $l=typeof window<`u`?window:void 0,eu=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function tu({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,paneClickDistance:s,deleteKeyCode:c,selectionKeyCode:l,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:g,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:b,panOnScrollSpeed:S,panOnScrollMode:C,zoomOnDoubleClick:w,panOnDrag:T,autoPanOnSelection:E,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,preventScrolling:j,onSelectionContextMenu:M,noWheelClassName:N,noPanClassName:P,disableKeyboardA11y:ee,onViewportChange:F,isControlledViewport:I}){let{nodesSelectionActive:te,userSelectionActive:ne}=G(eu,hc),L=Jc(l,{target:$l}),R=Jc(h,{target:$l}),z=R||T,B=R||b,re=u&&z!==!0,ie=L||ne||re;return xl({deleteKeyCode:c,multiSelectionKeyCode:m}),(0,x.jsx)(Tl,{onPaneContextMenu:a,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:B,panActivationKeyPressed:R,panOnScrollSpeed:S,panOnScrollMode:C,zoomOnDoubleClick:w,panOnDrag:!L&&z,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,zoomActivationKeyCode:g,preventScrolling:j,noWheelClassName:N,noPanClassName:P,onViewportChange:F,isControlledViewport:I,paneClickDistance:s,selectionOnDrag:re,children:(0,x.jsxs)(Al,{onSelectionStart:f,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,panOnDrag:z,autoPanOnSelection:E,isSelecting:!!ie,selectionMode:d,selectionKeyPressed:L,paneClickDistance:s,selectionOnDrag:re,children:[e,te&&(0,x.jsx)(Ql,{onSelectionContextMenu:M,noPanClassName:P,disableKeyboardA11y:ee})]})})}tu.displayName=`FlowRenderer`;var nu=(0,y.memo)(tu),ru=e=>t=>e?Fa(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys());function iu(e){return G((0,y.useCallback)(ru(e),[e]),hc)}var au=e=>e.updateNodeInternals;function ou(){let e=G(au),[t]=(0,y.useState)(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute(`data-id`);n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,y.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function su({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let i=bc(),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(e.sourcePosition),c=(0,y.useRef)(e.targetPosition),l=(0,y.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,y.useEffect)(()=>{a.current&&!e.hidden&&(!u||o.current!==a.current)&&(o.current&&r?.unobserve(o.current),r?.observe(a.current),o.current=a.current)},[u,e.hidden]),(0,y.useEffect)(()=>()=>{o.current&&=(r?.unobserve(o.current),null)},[]),(0,y.useEffect)(()=>{if(a.current){let n=l.current!==t,r=s.current!==e.sourcePosition,o=c.current!==e.targetPosition;(n||r||o)&&(l.current=t,s.current=e.sourcePosition,c.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:a.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),a}function cu({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:i,onContextMenu:a,onDoubleClick:o,nodesDraggable:s,elementsSelectable:c,nodesConnectable:l,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:p,disableKeyboardA11y:m,rfId:h,nodeTypes:g,nodeClickDistance:_,onError:v}){let{node:y,internals:b,isParent:C}=G(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},hc),w=y.type||`default`,T=g?.[w]||Yl[w];T===void 0&&(v?.(`003`,va.error003(w)),w=`default`,T=g?.default||Yl.default);let E=!!(y.draggable||s&&y.draggable===void 0),D=!!(y.selectable||c&&y.selectable===void 0),O=!!(y.connectable||l&&y.connectable===void 0),k=!!(y.focusable||u&&y.focusable===void 0),A=bc(),j=fo(y),M=su({node:y,nodeType:w,hasDimensions:j,resizeObserver:d}),N=Ml({nodeRef:M,disabled:y.hidden||!E,noDragClassName:f,handleSelector:y.dragHandle,nodeId:e,isSelectable:D,nodeClickDistance:_}),P=Pl();if(y.hidden)return null;let ee=uo(y),F=Xl(y),I=D||E||t||n||r||i,te=n?e=>n(e,{...b.userNode}):void 0,ne=r?e=>r(e,{...b.userNode}):void 0,L=i?e=>i(e,{...b.userNode}):void 0,R=a?e=>a(e,{...b.userNode}):void 0,z=o?e=>o(e,{...b.userNode}):void 0,B=n=>{let{selectNodesOnDrag:r,nodeDragThreshold:i}=A.getState();D&&(!r||!E||i>0)&&jl({id:e,store:A,nodeRef:M}),t&&t(n,{...b.userNode})},re=t=>{if(!(So(t.nativeEvent)||m)){if(ba.includes(t.key)&&D){let n=t.key===`Escape`;jl({id:e,store:A,unselect:n,nodeRef:M})}else if(E&&y.selected&&Object.prototype.hasOwnProperty.call(Jl,t.key)){t.preventDefault();let{ariaLabelConfig:e}=A.getState();A.setState({ariaLiveMessage:e[`node.a11yDescription.ariaLiveMessage`]({direction:t.key.replace(`Arrow`,``).toLowerCase(),x:~~b.positionAbsolute.x,y:~~b.positionAbsolute.y})}),P({direction:Jl[t.key],factor:t.shiftKey?4:1})}}},ie=()=>{if(m||!M.current?.matches(`:focus-visible`))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:i,setCenter:a}=A.getState();i&&(Fa(new Map([[e,y]]),{x:0,y:0,width:n,height:r},t,!0).length>0||a(y.position.x+ee.width/2,y.position.y+ee.height/2,{zoom:t[2]}))};return(0,x.jsx)(`div`,{className:S([`react-flow__node`,`react-flow__node-${w}`,{[p]:E},y.className,{selected:y.selected,selectable:D,parent:C,draggable:E,dragging:N}]),ref:M,style:{zIndex:b.z,transform:`translate(${b.positionAbsolute.x}px,${b.positionAbsolute.y}px)`,pointerEvents:I?`all`:`none`,visibility:j?`visible`:`hidden`,...y.style,...F},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:te,onMouseMove:ne,onMouseLeave:L,onContextMenu:R,onClick:B,onDoubleClick:z,onKeyDown:k?re:void 0,tabIndex:k?0:void 0,onFocus:k?ie:void 0,role:y.ariaRole??(k?`group`:void 0),"aria-roledescription":`node`,"aria-describedby":m?void 0:`${Cc}-${h}`,"aria-label":y.ariaLabel,...y.domAttributes,children:(0,x.jsx)(Il,{value:e,children:(0,x.jsx)(T,{id:e,data:y.data,type:w,positionAbsoluteX:b.positionAbsolute.x,positionAbsoluteY:b.positionAbsolute.y,selected:y.selected??!1,selectable:D,draggable:E,deletable:y.deletable??!0,isConnectable:O,sourcePosition:y.sourcePosition,targetPosition:y.targetPosition,dragging:N,dragHandle:y.dragHandle,zIndex:b.z,parentId:y.parentId,...ee})})})}var lu=(0,y.memo)(cu),uu=e=>({nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function du(e){let{nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,onError:i}=G(uu,hc),a=iu(e.onlyRenderVisibleElements),o=ou();return(0,x.jsx)(`div`,{className:`react-flow__nodes`,style:Cl,children:a.map(a=>(0,x.jsx)(lu,{id:a,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:o,nodesDraggable:e.nodesDraggable??!0,nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,nodeClickDistance:e.nodeClickDistance,onError:i},a))})}du.displayName=`NodeRenderer`;var fu=(0,y.memo)(du);function pu(e){return G((0,y.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&Mo({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),hc)}var mu=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e}};return(0,x.jsx)(`polyline`,{className:`arrow`,style:n,strokeLinecap:`round`,fill:`none`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4`})},hu=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e,fill:e}};return(0,x.jsx)(`polyline`,{className:`arrowclosed`,style:n,strokeLinecap:`round`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4 -5,-4`})},gu={[Da.Arrow]:mu,[Da.ArrowClosed]:hu};function _u(e){let t=bc();return(0,y.useMemo)(()=>Object.prototype.hasOwnProperty.call(gu,e)?gu[e]:(t.getState().onError?.(`009`,va.error009(e)),null),[e])}var vu=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a=`strokeWidth`,strokeWidth:o,orient:s=`auto-start-reverse`})=>{let c=_u(t);return c?(0,x.jsx)(`marker`,{className:`react-flow__arrowhead`,id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:`-10 -10 20 20`,markerUnits:a,orient:s,refX:`0`,refY:`0`,children:(0,x.jsx)(c,{color:n,strokeWidth:o})}):null},yu=({defaultColor:e,rfId:t})=>{let n=G(e=>e.edges),r=G(e=>e.defaultEdgeOptions),i=(0,y.useMemo)(()=>Yo(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return i.length?(0,x.jsx)(`svg`,{className:`react-flow__marker`,"aria-hidden":`true`,children:(0,x.jsx)(`defs`,{children:i.map(e=>(0,x.jsx)(vu,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};yu.displayName=`MarkerDefinitions`;var bu=(0,y.memo)(yu);function xu({x:e,y:t,label:n,labelStyle:r,labelShowBg:i=!0,labelBgStyle:a,labelBgPadding:o=[2,4],labelBgBorderRadius:s=2,children:c,className:l,...u}){let[d,f]=(0,y.useState)({x:1,y:0,width:0,height:0}),p=S([`react-flow__edge-textwrapper`,l]),m=(0,y.useRef)(null);return(0,y.useEffect)(()=>{if(m.current){let e=m.current.getBBox();f({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,x.jsxs)(`g`,{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?`visible`:`hidden`,...u,children:[i&&(0,x.jsx)(`rect`,{width:d.width+2*o[0],x:-o[0],y:-o[1],height:d.height+2*o[1],className:`react-flow__edge-textbg`,style:a,rx:s,ry:s}),(0,x.jsx)(`text`,{className:`react-flow__edge-text`,y:d.height/2,dy:`0.3em`,ref:m,style:r,children:n}),c]}):null}xu.displayName=`EdgeText`;var Su=(0,y.memo)(xu);function Cu({path:e,labelX:t,labelY:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c,interactionWidth:l=20,...u}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{...u,d:e,fill:`none`,className:S([`react-flow__edge-path`,u.className])}),l?(0,x.jsx)(`path`,{d:e,fill:`none`,strokeOpacity:0,strokeWidth:l,className:`react-flow__edge-interaction`}):null,r&&to(t)&&to(n)?(0,x.jsx)(Su,{x:t,y:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c}):null]})}function wu({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===H.Left||e===H.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function Tu({sourceX:e,sourceY:t,sourcePosition:n=H.Bottom,targetX:r,targetY:i,targetPosition:a=H.Top}){let[o,s]=wu({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,l]=wu({pos:a,x1:r,y1:i,x2:e,y2:t}),[u,d,f,p]=Eo({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:s,targetControlX:c,targetControlY:l});return[`M${e},${t} C${o},${s} ${c},${l} ${r},${i}`,u,d,f,p]}function Eu(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o,targetPosition:s,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})=>{let[v,y,b]=Tu({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s}),S=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:S,path:v,labelX:y,labelY:b,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})})}var Du=Eu({isInternal:!1}),Ou=Eu({isInternal:!0});Du.displayName=`SimpleBezierEdge`,Ou.displayName=`SimpleBezierEdgeInternal`;function ku(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:p=H.Bottom,targetPosition:m=H.Top,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,S]=Ho({sourceX:n,sourceY:r,sourcePosition:p,targetX:i,targetY:a,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition}),C=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:C,path:y,labelX:b,labelY:S,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:g,interactionWidth:v})})}var Au=ku({isInternal:!1}),ju=ku({isInternal:!0});Au.displayName=`SmoothStepEdge`,ju.displayName=`SmoothStepEdgeInternal`;function Mu(e){return(0,y.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,x.jsx)(Au,{...n,id:r,pathOptions:(0,y.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var Nu=Mu({isInternal:!1}),Pu=Mu({isInternal:!0});Nu.displayName=`StepEdge`,Pu.displayName=`StepEdgeInternal`;function Fu(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})=>{let[g,_,v]=Io({sourceX:n,sourceY:r,targetX:i,targetY:a}),y=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:y,path:g,labelX:_,labelY:v,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})})}var Iu=Fu({isInternal:!1}),Lu=Fu({isInternal:!0});Iu.displayName=`StraightEdge`,Lu.displayName=`StraightEdgeInternal`;function Ru(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o=H.Bottom,targetPosition:s=H.Top,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,S]=ko({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s,curvature:_?.curvature}),C=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:C,path:y,labelX:b,labelY:S,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:v})})}var zu=Ru({isInternal:!1}),Bu=Ru({isInternal:!0});zu.displayName=`BezierEdge`,Bu.displayName=`BezierEdgeInternal`;var Vu={default:Bu,straight:Lu,step:Pu,smoothstep:ju,simplebezier:Ou},Hu={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null,zIndex:void 0},Uu=(e,t,n)=>n===H.Left?e-t:n===H.Right?e+t:e,Wu=(e,t,n)=>n===H.Top?e-t:n===H.Bottom?e+t:e,Gu=`react-flow__edgeupdater`;function Ku({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:o,type:s}){return(0,x.jsx)(`circle`,{onMouseDown:i,onMouseEnter:a,onMouseOut:o,className:S([Gu,`${Gu}-${s}`]),cx:Uu(t,r,e),cy:Wu(n,r,e),r,stroke:`transparent`,fill:`transparent`})}function qu({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:i,targetX:a,targetY:o,sourcePosition:s,targetPosition:c,onReconnect:l,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:p}){let m=bc(),h=(e,t)=>{if(e.button!==0)return;let{autoPanOnConnect:r,domNode:i,connectionMode:a,connectionRadius:o,lib:s,onConnectStart:c,cancelConnection:p,nodeLookup:h,rfId:g,panBy:_,updateConnection:v}=m.getState(),y=t.type===`target`;ks.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:o,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:y,edgeUpdaterType:t.type,lib:s,flowId:g,cancelConnection:p,panBy:_,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>l?.(n,e),onConnectStart:(r,i)=>{f(!0),u?.(e,n,t.type),c?.(r,i)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=e=>h(e,{nodeId:n.target,id:n.targetHandle??null,type:`target`}),_=e=>h(e,{nodeId:n.source,id:n.sourceHandle??null,type:`source`}),v=()=>p(!0),y=()=>p(!1);return(0,x.jsxs)(x.Fragment,{children:[(e===!0||e===`source`)&&(0,x.jsx)(Ku,{position:s,centerX:r,centerY:i,radius:t,onMouseDown:g,onMouseEnter:v,onMouseOut:y,type:`source`}),(e===!0||e===`target`)&&(0,x.jsx)(Ku,{position:c,centerX:a,centerY:o,radius:t,onMouseDown:_,onMouseEnter:v,onMouseOut:y,type:`target`})]})}function Ju({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:i,onDoubleClick:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,rfId:m,edgeTypes:h,noPanClassName:g,onError:_,disableKeyboardA11y:v}){let b=G(t=>t.edgeLookup.get(e)),C=G(e=>e.defaultEdgeOptions);b=C?{...C,...b}:b;let w=b.type||`default`,T=h?.[w]||Vu[w];T===void 0&&(_?.(`011`,va.error011(w)),w=`default`,T=h?.default||Vu.default);let E=!!(b.focusable||t&&b.focusable===void 0),D=d!==void 0&&(b.reconnectable||n&&b.reconnectable===void 0),O=!!(b.selectable||r&&b.selectable===void 0),k=(0,y.useRef)(null),[A,j]=(0,y.useState)(!1),[M,N]=(0,y.useState)(!1),P=bc(),{zIndex:ee=b.zIndex,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R}=G((0,y.useCallback)(t=>{let n=t.nodeLookup.get(b.source),r=t.nodeLookup.get(b.target);if(!n||!r)return Hu;let i=Wo({id:e,sourceNode:n,targetNode:r,sourceHandle:b.sourceHandle||null,targetHandle:b.targetHandle||null,connectionMode:t.connectionMode,onError:_}),a=jo({selected:b.selected,zIndex:b.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode});return{...i||Hu,zIndex:a}},[b.source,b.target,b.sourceHandle,b.targetHandle,b.selected,b.zIndex,_]),hc),z=(0,y.useMemo)(()=>b.markerStart?`url('#${Jo(b.markerStart,m)}')`:void 0,[b.markerStart,m]),B=(0,y.useMemo)(()=>b.markerEnd?`url('#${Jo(b.markerEnd,m)}')`:void 0,[b.markerEnd,m]);if(b.hidden||F===null||I===null||te===null||ne===null)return null;let re=t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:a}=P.getState();O&&(P.setState({nodesSelectionActive:!1}),b.selected&&a?(r({nodes:[],edges:[b]}),k.current?.blur()):n([e])),i&&i(t,b)},ie=a?e=>{a(e,{...b})}:void 0,ae=o?e=>{o(e,{...b})}:void 0,oe=s?e=>{s(e,{...b})}:void 0,se=c?e=>{c(e,{...b})}:void 0,ce=l?e=>{l(e,{...b})}:void 0;return(0,x.jsx)(`svg`,{style:{zIndex:ee},children:(0,x.jsxs)(`g`,{className:S([`react-flow__edge`,`react-flow__edge-${w}`,b.className,g,{selected:b.selected,animated:b.animated,inactive:!O&&!i,updating:A,selectable:O}]),onClick:re,onDoubleClick:ie,onContextMenu:ae,onMouseEnter:oe,onMouseMove:se,onMouseLeave:ce,onKeyDown:E?t=>{if(!v&&ba.includes(t.key)&&O){let{unselectNodesAndEdges:n,addSelectedEdges:r}=P.getState();t.key===`Escape`?(k.current?.blur(),n({edges:[b]})):r([e])}}:void 0,tabIndex:E?0:void 0,role:b.ariaRole??(E?`group`:`img`),"aria-roledescription":`edge`,"data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":b.ariaLabel===null?void 0:b.ariaLabel||`Edge from ${b.source} to ${b.target}`,"aria-describedby":E?`${wc}-${m}`:void 0,ref:k,...b.domAttributes,children:[!M&&(0,x.jsx)(T,{id:e,source:b.source,target:b.target,type:b.type,selected:b.selected,animated:b.animated,selectable:O,deletable:b.deletable??!0,label:b.label,labelStyle:b.labelStyle,labelShowBg:b.labelShowBg,labelBgStyle:b.labelBgStyle,labelBgPadding:b.labelBgPadding,labelBgBorderRadius:b.labelBgBorderRadius,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R,data:b.data,style:b.style,sourceHandleId:b.sourceHandle,targetHandleId:b.targetHandle,markerStart:z,markerEnd:B,pathOptions:`pathOptions`in b?b.pathOptions:void 0,interactionWidth:b.interactionWidth}),D&&(0,x.jsx)(qu,{edge:b,isReconnectable:D,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R,setUpdateHover:j,setReconnecting:N})]})})}var Yu=(0,y.memo)(Ju),Xu=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Zu({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:i,onReconnect:a,onEdgeContextMenu:o,onEdgeMouseEnter:s,onEdgeMouseMove:c,onEdgeMouseLeave:l,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:h}){let{edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,onError:y}=G(Xu,hc),b=pu(t);return(0,x.jsxs)(`div`,{className:`react-flow__edges`,children:[(0,x.jsx)(bu,{defaultColor:e,rfId:n}),b.map(e=>(0,x.jsx)(Yu,{id:e,edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,noPanClassName:i,onReconnect:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,rfId:n,onError:y,edgeTypes:r,disableKeyboardA11y:h},e))]})}Zu.displayName=`EdgeRenderer`;var Qu=(0,y.memo)(Zu),$u=e=>`translate(${e[0]}px,${e[1]}px) scale(${e[2]})`;function ed({children:e}){let t=bc(),n=(0,y.useRef)(null),[r]=(0,y.useState)(()=>t.getState().transform);return dl(()=>{let e=null,r=()=>{let r=t.getState().transform;e&&r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2]||(e=r,n.current&&(n.current.style.transform=$u(r)))};return r(),t.subscribe(r)},[t]),(0,x.jsx)(`div`,{ref:n,className:`react-flow__viewport xyflow__viewport react-flow__container`,style:{transform:$u(r)},children:e})}function td(e){let t=vl(),n=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var nd=e=>e.panZoom?.syncViewport;function rd(e){let t=G(nd),n=bc();return(0,y.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function id(e){return e.connection.inProgress?{...e.connection,to:io(e.connection.to,e.transform)}:{...e.connection}}function ad(e){return e?t=>e(id(t)):id}function od(e){return G(ad(e),hc)}var sd=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function cd({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:i,width:a,height:o,isValid:s,inProgress:c}=G(sd,hc);return a&&i&&c?(0,x.jsx)(`svg`,{style:e,width:a,height:o,className:`react-flow__connectionline react-flow__container`,children:(0,x.jsx)(`g`,{className:S([`react-flow__connection`,_o(s)]),children:(0,x.jsx)(ld,{style:t,type:n,CustomComponent:r,isValid:s})})}):null}var ld=({style:e,type:t=Ea.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:i,from:a,fromNode:o,fromHandle:s,fromPosition:c,to:l,toNode:u,toHandle:d,toPosition:f,pointer:p}=od();if(!i)return;if(n)return(0,x.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:o,fromHandle:s,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:c,toPosition:f,connectionStatus:_o(r),toNode:u,toHandle:d,pointer:p});let m=``,h={sourceX:a.x,sourceY:a.y,sourcePosition:c,targetX:l.x,targetY:l.y,targetPosition:f};switch(t){case Ea.Bezier:[m]=ko(h);break;case Ea.SimpleBezier:[m]=Tu(h);break;case Ea.Step:[m]=Ho({...h,borderRadius:0});break;case Ea.SmoothStep:[m]=Ho(h);break;default:[m]=Io(h)}return(0,x.jsx)(`path`,{d:m,fill:`none`,className:`react-flow__connection-path`,style:e})};ld.displayName=`ConnectionLine`;var ud={};function dd(e=ud){(0,y.useRef)(e),bc(),(0,y.useEffect)(()=>{},[e])}function fd(){bc(),(0,y.useRef)(!1),(0,y.useEffect)(()=>{},[])}function pd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:i,onNodeDoubleClick:a,onEdgeDoubleClick:o,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:h,connectionLineComponent:g,connectionLineContainerStyle:_,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,multiSelectionKeyCode:S,panActivationKeyCode:C,zoomActivationKeyCode:w,deleteKeyCode:T,onlyRenderVisibleElements:E,elementsSelectable:D,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,preventScrolling:M,defaultMarkerColor:N,zoomOnScroll:P,zoomOnPinch:ee,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,zoomOnDoubleClick:ne,panOnDrag:L,autoPanOnSelection:R,onPaneClick:z,onPaneMouseEnter:B,onPaneMouseMove:re,onPaneMouseLeave:ie,onPaneScroll:ae,onPaneContextMenu:oe,paneClickDistance:se,nodeClickDistance:ce,onEdgeContextMenu:le,onEdgeMouseEnter:ue,onEdgeMouseMove:de,onEdgeMouseLeave:fe,reconnectRadius:pe,onReconnect:me,onReconnectStart:he,onReconnectEnd:ge,noDragClassName:_e,noWheelClassName:ve,noPanClassName:ye,disableKeyboardA11y:be,nodeExtent:xe,rfId:Se,viewport:Ce,onViewportChange:we,nodesDraggable:Te}){return dd(e),dd(t),fd(),td(n),rd(Ce),(0,x.jsx)(nu,{onPaneClick:z,onPaneMouseEnter:B,onPaneMouseMove:re,onPaneMouseLeave:ie,onPaneContextMenu:oe,onPaneScroll:ae,paneClickDistance:se,deleteKeyCode:T,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:S,panActivationKeyCode:C,zoomActivationKeyCode:w,elementsSelectable:D,zoomOnScroll:P,zoomOnPinch:ee,zoomOnDoubleClick:ne,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,panOnDrag:L,autoPanOnSelection:R,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,onSelectionContextMenu:d,preventScrolling:M,noDragClassName:_e,noWheelClassName:ve,noPanClassName:ye,disableKeyboardA11y:be,onViewportChange:we,isControlledViewport:!!Ce,children:(0,x.jsxs)(ed,{children:[(0,x.jsx)(Qu,{edgeTypes:t,onEdgeClick:i,onEdgeDoubleClick:o,onReconnect:me,onReconnectStart:he,onReconnectEnd:ge,onlyRenderVisibleElements:E,onEdgeContextMenu:le,onEdgeMouseEnter:ue,onEdgeMouseMove:de,onEdgeMouseLeave:fe,reconnectRadius:pe,defaultMarkerColor:N,noPanClassName:ye,disableKeyboardA11y:be,rfId:Se}),(0,x.jsx)(cd,{style:h,type:m,component:g,containerStyle:_}),(0,x.jsx)(`div`,{className:`react-flow__edgelabel-renderer`}),(0,x.jsx)(fu,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:a,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,nodeClickDistance:ce,onlyRenderVisibleElements:E,noPanClassName:ye,noDragClassName:_e,disableKeyboardA11y:be,nodeExtent:xe,rfId:Se,nodesDraggable:Te}),(0,x.jsx)(`div`,{className:`react-flow__viewport-portal`})]})})}pd.displayName=`GraphView`;var md=(0,y.memo)(pd),hd=no(`React Flow`,`https://reactflow.dev/`),gd=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c=.5,maxZoom:l=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f=`basic`}={})=>{let p=new Map,m=new Map,h=new Map,g=new Map,_=r??t??[],v=n??e??[],y=u??[0,0],b=d??ya;ps(h,g,_);let{nodesInitialized:x}=is(v,p,m,{nodeOrigin:y,nodeExtent:b,zIndexMode:f}),S=[0,0,1];if(o&&i&&a){let{x:e,y:t,zoom:n}=lo(Pa(p,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),i,a,c,l,s?.padding??.1);S=[e,t,n]}return{rfId:`1`,width:i??0,height:a??0,transform:S,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:m,edges:_,edgeLookup:g,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:l,translateExtent:ya,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Sa.Strict,domNode:null,paneDragging:!1,noPanClassName:`nopan`,nodeOrigin:y,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:o??!1,fitViewOptions:s,fitViewResolver:null,connection:{...Ta},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:``,autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:hd,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:`react`,debug:!1,ariaLabelConfig:xa,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},_d=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>mc((p,m)=>{async function h(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:a,minZoom:o,maxZoom:s}=m();t&&(await Ra({nodes:e,width:i,height:a,panZoom:t,minZoom:o,maxZoom:s},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...gd({nodes:e,edges:t,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,fitViewQueued:o,zIndexMode:s,nodesSelectionActive:c}=m(),{nodesInitialized:l,hasSelectedNodes:u}=is(e,t,n,{nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,checkEquality:!0,zIndexMode:s}),d=c&&u;o&&l?(h(),p({nodes:e,nodesInitialized:l,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:d})):p({nodes:e,nodesInitialized:l,nodesSelectionActive:d})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=m();ps(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:a,nodeExtent:o,debug:s,fitViewQueued:c,zIndexMode:l}=m(),{changes:u,updatedInternals:d}=us(e,n,r,i,a,o,l);d&&(ts(n,r,{nodeOrigin:a,nodeExtent:o,zIndexMode:l}),c?(h(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),u?.length>0&&(s&&console.log(`React Flow: trigger node changes`,u),t?.(u)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:i,triggerNodeChanges:a,connection:o,updateConnection:s,onNodesChangeMiddlewareMap:c}=m();for(let[a,c]of e){let e=i.get(a),l=!!(e?.expandParent&&e?.parentId&&c?.position),u={id:a,type:`position`,position:l?{x:Math.max(0,c.position.x),y:Math.max(0,c.position.y)}:c.position,dragging:t};if(e&&o.inProgress&&o.fromNode.id===e.id){let t=Ko(e,o.fromHandle,H.Left,!0);s({...o,from:t})}l&&e.parentId&&n.push({id:a,parentId:e.parentId,rect:{...c.internals.positionAbsolute,width:c.measured.width??0,height:c.measured.height??0}}),r.push(u)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=m(),a=ls(n,i,e,t);r.push(...a)}for(let e of c.values())r=e(r);a(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:a}=m();e?.length&&(i&&n(el(e,r)),a&&console.log(`React Flow: trigger node changes`,e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:a}=m();e?.length&&(i&&n(tl(e,r)),a&&console.log(`React Flow: trigger edge changes`,e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){i(e.map(e=>nl(e,!0)));return}i(rl(r,new Set([...e]),!0)),a(rl(n))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){a(e.map(e=>nl(e,!0)));return}a(rl(n,new Set([...e]))),i(rl(r,new Set,!0))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:a,triggerEdgeChanges:o}=m(),s=e||r,c=t||n,l=[];for(let e of s){if(!e.selected)continue;let t=i.get(e.id);t&&(t.selected=!1),l.push(nl(e.id,!1))}let u=[];for(let e of c)e.selected&&u.push(nl(e.id,!1));a(l),o(u)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=m();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=m();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:i}=m();if(!i)return;let a=t.reduce((e,t)=>t.selected?[...e,nl(t.id,!1)]:e,[]),o=e.reduce((e,t)=>t.selected?[...e,nl(t.id,!1)]:e,[]);n(a),r(o)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:a,nodeExtent:o,zIndexMode:s}=m();(e[0][0]!==o[0][0]||e[0][1]!==o[0][1]||e[1][0]!==o[1][0]||e[1][1]!==o[1][1])&&(is(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:a,checkEquality:!1,zIndexMode:s}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:i,translateExtent:a}=m();return ds({delta:e,panZoom:i,transform:t,translateExtent:a,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:i,maxZoom:a,panZoom:o}=m();if(!o)return!1;let s=n?.zoom===void 0?a:n.zoom;return await o.setViewport({x:r/2-e*s,y:i/2-t*s,zoom:s},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0},cancelConnection:()=>{p({connection:{...Ta}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...gd()})}},Object.is);function vd({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:i,initialHeight:a,initialMinZoom:o,initialMaxZoom:s,initialFitViewOptions:c,fitView:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:p}){let[m]=(0,y.useState)(()=>_d({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:l,minZoom:o,maxZoom:s,fitViewOptions:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,x.jsx)(vc,{value:m,children:(0,x.jsx)(hl,{children:(0,x.jsx)(Bl,{children:p})})})}function yd({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:i,width:a,height:o,fitView:s,fitViewOptions:c,minZoom:l,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p}){return(0,y.useContext)(_c)?(0,x.jsx)(x.Fragment,{children:e}):(0,x.jsx)(vd,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:i,initialWidth:a,initialHeight:o,fitView:s,initialFitViewOptions:c,initialMinZoom:l,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p,children:e})}var bd={width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`,zIndex:0};function xd({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a,edgeTypes:o,onNodeClick:s,onEdgeClick:c,onInit:l,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,onNodeMouseEnter:v,onNodeMouseMove:b,onNodeMouseLeave:C,onNodeContextMenu:w,onNodeDoubleClick:T,onNodeDragStart:E,onNodeDrag:D,onNodeDragStop:O,onNodesDelete:k,onEdgesDelete:A,onDelete:j,onSelectionChange:M,onSelectionDragStart:N,onSelectionDrag:P,onSelectionDragStop:ee,onSelectionContextMenu:F,onSelectionStart:I,onSelectionEnd:te,onBeforeDelete:ne,connectionMode:L,connectionLineType:R=Ea.Bezier,connectionLineStyle:z,connectionLineComponent:B,connectionLineContainerStyle:re,deleteKeyCode:ie=`Backspace`,selectionKeyCode:ae=`Shift`,selectionOnDrag:oe=!1,selectionMode:se=wa.Full,panActivationKeyCode:ce=`Space`,multiSelectionKeyCode:le=U()?`Meta`:`Control`,zoomActivationKeyCode:ue=U()?`Meta`:`Control`,snapToGrid:de,snapGrid:fe,onlyRenderVisibleElements:pe=!1,selectNodesOnDrag:me,nodesDraggable:he,autoPanOnNodeFocus:ge,nodesConnectable:_e,nodesFocusable:ve,nodeOrigin:ye=zc,edgesFocusable:be,edgesReconnectable:xe,elementsSelectable:Se=!0,defaultViewport:Ce=Bc,minZoom:we=.5,maxZoom:Te=2,translateExtent:Ee=ya,preventScrolling:De=!0,nodeExtent:Oe,defaultMarkerColor:ke=`#b1b1b7`,zoomOnScroll:Ae=!0,zoomOnPinch:je=!0,panOnScroll:Me=!1,panOnScrollSpeed:Ne=.5,panOnScrollMode:Pe=Ca.Free,zoomOnDoubleClick:Fe=!0,panOnDrag:Ie=!0,onPaneClick:Le,onPaneMouseEnter:Re,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:Ve,onPaneContextMenu:He,paneClickDistance:Ue=1,nodeClickDistance:We=0,children:Ge,onReconnect:Ke,onReconnectStart:qe,onReconnectEnd:Je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Xe,onEdgeMouseEnter:Ze,onEdgeMouseMove:Qe,onEdgeMouseLeave:$e,reconnectRadius:et=10,onNodesChange:tt,onEdgesChange:nt,noDragClassName:rt=`nodrag`,noWheelClassName:it=`nowheel`,noPanClassName:at=`nopan`,fitView:ot,fitViewOptions:st,connectOnClick:ct,attributionPosition:lt,proOptions:ut,defaultEdgeOptions:dt,elevateNodesOnSelect:ft=!0,elevateEdgesOnSelect:pt=!1,disableKeyboardA11y:mt=!1,autoPanOnConnect:ht,autoPanOnNodeDrag:gt,autoPanOnSelection:_t=!0,autoPanSpeed:vt,connectionRadius:yt,isValidConnection:bt,onError:xt,style:St,id:Ct,nodeDragThreshold:wt,connectionDragThreshold:Tt,viewport:Et,onViewportChange:Dt,width:Ot,height:kt,colorMode:At=`light`,debug:jt,onScroll:Mt,ariaLabelConfig:Nt,zIndexMode:Pt=`basic`,...Ft},It){let Lt=Ct||`1`,Rt=Kc(At),zt=(0,y.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:`instant`}),Mt?.(e)},[Mt]);return(0,x.jsx)(`div`,{"data-testid":`rf__wrapper`,...Ft,onScroll:zt,style:{...St,...bd},ref:It,className:S([`react-flow`,i,Rt]),id:Ct,role:`application`,children:(0,x.jsxs)(yd,{nodes:e,edges:t,width:Ot,height:kt,fitView:ot,fitViewOptions:st,minZoom:we,maxZoom:Te,nodeOrigin:ye,nodeExtent:Oe,zIndexMode:Pt,children:[(0,x.jsx)(Wc,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,nodesDraggable:he,autoPanOnNodeFocus:ge,nodesConnectable:_e,nodesFocusable:ve,edgesFocusable:be,edgesReconnectable:xe,elementsSelectable:Se,elevateNodesOnSelect:ft,elevateEdgesOnSelect:pt,minZoom:we,maxZoom:Te,nodeExtent:Oe,onNodesChange:tt,onEdgesChange:nt,snapToGrid:de,snapGrid:fe,connectionMode:L,translateExtent:Ee,connectOnClick:ct,defaultEdgeOptions:dt,fitView:ot,fitViewOptions:st,onNodesDelete:k,onEdgesDelete:A,onDelete:j,onNodeDragStart:E,onNodeDrag:D,onNodeDragStop:O,onSelectionDrag:P,onSelectionDragStart:N,onSelectionDragStop:ee,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:at,nodeOrigin:ye,rfId:Lt,autoPanOnConnect:ht,autoPanOnNodeDrag:gt,autoPanSpeed:vt,onError:xt,connectionRadius:yt,isValidConnection:bt,selectNodesOnDrag:me,nodeDragThreshold:wt,connectionDragThreshold:Tt,onBeforeDelete:ne,debug:jt,ariaLabelConfig:Nt,zIndexMode:Pt}),(0,x.jsx)(md,{onInit:l,onNodeClick:s,onEdgeClick:c,onNodeMouseEnter:v,onNodeMouseMove:b,onNodeMouseLeave:C,onNodeContextMenu:w,onNodeDoubleClick:T,nodeTypes:a,edgeTypes:o,connectionLineType:R,connectionLineStyle:z,connectionLineComponent:B,connectionLineContainerStyle:re,selectionKeyCode:ae,selectionOnDrag:oe,selectionMode:se,deleteKeyCode:ie,multiSelectionKeyCode:le,panActivationKeyCode:ce,zoomActivationKeyCode:ue,onlyRenderVisibleElements:pe,defaultViewport:Ce,translateExtent:Ee,minZoom:we,maxZoom:Te,preventScrolling:De,zoomOnScroll:Ae,zoomOnPinch:je,zoomOnDoubleClick:Fe,panOnScroll:Me,panOnScrollSpeed:Ne,panOnScrollMode:Pe,panOnDrag:Ie,autoPanOnSelection:_t,onPaneClick:Le,onPaneMouseEnter:Re,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:Ve,onPaneContextMenu:He,paneClickDistance:Ue,nodeClickDistance:We,onSelectionContextMenu:F,onSelectionStart:I,onSelectionEnd:te,onReconnect:Ke,onReconnectStart:qe,onReconnectEnd:Je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Xe,onEdgeMouseEnter:Ze,onEdgeMouseMove:Qe,onEdgeMouseLeave:$e,reconnectRadius:et,defaultMarkerColor:ke,noDragClassName:rt,noWheelClassName:it,noPanClassName:at,rfId:Lt,disableKeyboardA11y:mt,nodeExtent:Oe,viewport:Et,onViewportChange:Dt,nodesDraggable:he}),(0,x.jsx)(Rc,{onSelectionChange:M}),Ge,(0,x.jsx)(Mc,{proOptions:ut,position:lt}),(0,x.jsx)(kc,{rfId:Lt,disableKeyboardA11y:mt})]})})}var Sd=ul(xd),Cd=e=>e.domNode?.querySelector(`.react-flow__edgelabel-renderer`);function J({children:e}){let t=G(Cd);return t?(0,gc.createPortal)(e,t):null}var wd=e=>({x:e.transform[0],y:e.transform[1],zoom:e.transform[2]});function Td(){return G(wd,hc)}function Ed(e){let[t,n]=(0,y.useState)(e);return[t,n,(0,y.useCallback)(e=>n(t=>el(e,t)),[])]}function Dd(e){let[t,n]=(0,y.useState)(e);return[t,n,(0,y.useCallback)(e=>n(t=>tl(e,t)),[])]}va.error014();function Od({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,x.jsx)(`path`,{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:S([`react-flow__background-pattern`,n,r])})}function kd({radius:e,className:t}){return(0,x.jsx)(`circle`,{cx:e,cy:e,r:e,className:S([`react-flow__background-pattern`,`dots`,t])})}var Ad;(function(e){e.Lines=`lines`,e.Dots=`dots`,e.Cross=`cross`})(Ad||={});var jd={[Ad.Dots]:1,[Ad.Lines]:1,[Ad.Cross]:6},Md=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Nd({id:e,variant:t=Ad.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=0,color:o,bgColor:s,style:c,className:l,patternClassName:u}){let d=(0,y.useRef)(null),{transform:f,patternId:p}=G(Md,hc),m=r||jd[t],h=t===Ad.Dots,g=t===Ad.Cross,_=Array.isArray(n)?n:[n,n],v=[_[0]*f[2]||1,_[1]*f[2]||1],b=m*f[2],C=Array.isArray(a)?a:[a,a],w=g?[b,b]:v,T=[C[0]*f[2]+w[0]/2,C[1]*f[2]+w[1]/2],E=`${p}${e||``}`;return(0,x.jsxs)(`svg`,{className:S([`react-flow__background`,l]),style:{...c,...Cl,"--xy-background-color-props":s,"--xy-background-pattern-color-props":o},ref:d,"data-testid":`rf__background`,children:[(0,x.jsx)(`pattern`,{id:E,x:f[0]%v[0],y:f[1]%v[1],width:v[0],height:v[1],patternUnits:`userSpaceOnUse`,patternTransform:`translate(-${T[0]},-${T[1]})`,children:h?(0,x.jsx)(kd,{radius:b/2,className:u}):(0,x.jsx)(Od,{dimensions:w,lineWidth:i,variant:t,className:u})}),(0,x.jsx)(`rect`,{x:`0`,y:`0`,width:`100%`,height:`100%`,fill:`url(#${E})`})]})}Nd.displayName=`Background`,(0,y.memo)(Nd);function Pd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,children:(0,x.jsx)(`path`,{d:`M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z`})})}function Fd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 5`,children:(0,x.jsx)(`path`,{d:`M0 0h32v4.2H0z`})})}function Id(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 30`,children:(0,x.jsx)(`path`,{d:`M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z`})})}function Ld(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,x.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z`})})}function Rd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,x.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z`})})}function zd({children:e,className:t,...n}){return(0,x.jsx)(`button`,{type:`button`,className:S([`react-flow__controls-button`,t]),...n,children:e})}var Bd=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Vd({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:o,onFitView:s,onInteractiveChange:c,className:l,children:u,position:d=`bottom-left`,orientation:f=`vertical`,"aria-label":p}){let m=bc(),{isInteractive:h,minZoomReached:g,maxZoomReached:_,ariaLabelConfig:v}=G(Bd,hc),{zoomIn:y,zoomOut:b,fitView:C}=vl();return(0,x.jsxs)(Ac,{className:S([`react-flow__controls`,f===`horizontal`?`horizontal`:`vertical`,l]),position:d,style:e,"data-testid":`rf__controls`,"aria-label":p??v[`controls.ariaLabel`],children:[t&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zd,{onClick:()=>{y(),a?.()},className:`react-flow__controls-zoomin`,title:v[`controls.zoomIn.ariaLabel`],"aria-label":v[`controls.zoomIn.ariaLabel`],disabled:_,children:(0,x.jsx)(Pd,{})}),(0,x.jsx)(zd,{onClick:()=>{b(),o?.()},className:`react-flow__controls-zoomout`,title:v[`controls.zoomOut.ariaLabel`],"aria-label":v[`controls.zoomOut.ariaLabel`],disabled:g,children:(0,x.jsx)(Fd,{})})]}),n&&(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:()=>{C(i),s?.()},title:v[`controls.fitView.ariaLabel`],"aria-label":v[`controls.fitView.ariaLabel`],children:(0,x.jsx)(Id,{})}),r&&(0,x.jsx)(zd,{className:`react-flow__controls-interactive`,onClick:()=>{m.setState({nodesDraggable:!h,nodesConnectable:!h,elementsSelectable:!h}),c?.(!h)},title:v[`controls.interactive.ariaLabel`],"aria-label":v[`controls.interactive.ariaLabel`],children:h?(0,x.jsx)(Rd,{}):(0,x.jsx)(Ld,{})}),u]})}Vd.displayName=`Controls`;var Hd=(0,y.memo)(Vd);function Ud({id:e,x:t,y:n,width:r,height:i,style:a,color:o,strokeColor:s,strokeWidth:c,className:l,borderRadius:u,shapeRendering:d,selected:f,onClick:p}){let{background:m,backgroundColor:h}=a||{},g=o||m||h;return(0,x.jsx)(`rect`,{className:S([`react-flow__minimap-node`,{selected:f},l]),x:t,y:n,rx:u,ry:u,width:r,height:i,style:{fill:g,stroke:s,strokeWidth:c},shapeRendering:d,onClick:p?t=>p(t,e):void 0})}var Wd=(0,y.memo)(Ud),Gd=e=>e.nodes.map(e=>e.id),Kd=e=>e instanceof Function?e:()=>e;function qd({nodeStrokeColor:e,nodeColor:t,nodeClassName:n=``,nodeBorderRadius:r=5,nodeStrokeWidth:i,nodeComponent:a=Wd,onClick:o}){let s=G(Gd,hc),c=Kd(t),l=Kd(e),u=Kd(n),d=typeof window>`u`||window.chrome?`crispEdges`:`geometricPrecision`;return(0,x.jsx)(x.Fragment,{children:s.map(e=>(0,x.jsx)(Yd,{id:e,nodeColorFunc:c,nodeStrokeColorFunc:l,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:i,NodeComponent:a,onClick:o,shapeRendering:d},e))})}function Jd({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:i,nodeStrokeWidth:a,shapeRendering:o,NodeComponent:s,onClick:c}){let{node:l,x:u,y:d,width:f,height:p}=G(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:i,y:a}=n.internals.positionAbsolute,{width:o,height:s}=uo(r);return{node:r,x:i,y:a,width:o,height:s}},hc);return!l||l.hidden||!fo(l)?null:(0,x.jsx)(s,{x:u,y:d,width:f,height:p,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:i,strokeColor:n(l),strokeWidth:a,shapeRendering:o,onClick:c,id:l.id})}var Yd=(0,y.memo)(Jd),Xd=(0,y.memo)(qd),Zd=200,Qd=150,$d=e=>!e.hidden,ef=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]},n=!1;for(let t of e.nodeLookup.values())if(!t.hidden){n=!0;break}return{viewBB:t,boundingRect:n?Za(Pa(e.nodeLookup,{filter:$d}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},tf=(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,nf=(e,t)=>tf(e.viewBB,t.viewBB)&&tf(e.boundingRect,t.boundingRect)&&e.rfId===t.rfId&&e.panZoom===t.panZoom&&e.translateExtent===t.translateExtent&&e.flowWidth===t.flowWidth&&e.flowHeight===t.flowHeight&&e.ariaLabelConfig===t.ariaLabelConfig,rf=`react-flow__minimap-desc`;function af({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:i=``,nodeBorderRadius:a=5,nodeStrokeWidth:o,nodeComponent:s,bgColor:c,maskColor:l,maskStrokeColor:u,maskStrokeWidth:d,position:f=`bottom-right`,onClick:p,onNodeClick:m,pannable:h=!1,zoomable:g=!1,ariaLabel:_,inversePan:v,zoomStep:b=1,offsetScale:C=5}){let w=bc(),T=(0,y.useRef)(null),{boundingRect:E,panZoom:D,viewBB:O,rfId:k,translateExtent:A,flowWidth:j,flowHeight:M,ariaLabelConfig:N}=G(ef,nf),P=e?.width??Zd,ee=e?.height??Qd,F=E.width/P,I=E.height/ee,te=Math.max(F,I),ne=te*P,L=te*ee,R=C*te,z=E.x-(ne-E.width)/2-R,B=E.y-(L-E.height)/2-R,re=ne+R*2,ie=L+R*2,ae=`${rf}-${k}`,oe=(0,y.useRef)(0),se=(0,y.useRef)();oe.current=te,(0,y.useEffect)(()=>{let e=w.getState().panZoom;if(T.current&&e)return se.current=As({domNode:T.current,panZoom:e,getTransform:()=>w.getState().transform,getViewScale:()=>oe.current}),()=>{se.current?.destroy()}},[D]),(0,y.useEffect)(()=>{se.current?.update({translateExtent:A,width:j,height:M,inversePan:v,pannable:h,zoomStep:b,zoomable:g})},[h,g,v,b,A,j,M]);let ce=p?e=>{let[t,n]=se.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,le=(0,y.useCallback)((e,t)=>{let n=w.getState().nodeLookup.get(t).internals.userNode;m?.(e,n)},[m]),ue=m?le:void 0,de=_??N[`minimap.ariaLabel`];return(0,x.jsx)(Ac,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c==`string`?c:void 0,"--xy-minimap-mask-background-color-props":typeof l==`string`?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof u==`string`?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d==`number`?d*te:void 0,"--xy-minimap-node-background-color-props":typeof r==`string`?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n==`string`?n:void 0,"--xy-minimap-node-stroke-width-props":typeof o==`number`?o:void 0},className:S([`react-flow__minimap`,t]),"data-testid":`rf__minimap`,children:(0,x.jsxs)(`svg`,{width:P,height:ee,viewBox:`${z} ${B} ${re} ${ie}`,className:`react-flow__minimap-svg`,role:`img`,"aria-labelledby":ae,ref:T,onClick:ce,children:[de&&(0,x.jsx)(`title`,{id:ae,children:de}),(0,x.jsx)(Xd,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:o,nodeComponent:s}),(0,x.jsx)(`path`,{className:`react-flow__minimap-mask`,d:`M${z-R},${B-R}h${re+R*2}v${ie+R*2}h${-re-R*2}z - M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}af.displayName=`MiniMap`;var of=(0,y.memo)(af),sf=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,cf={[Gs.Line]:`right`,[Gs.Handle]:`bottom-right`};function lf({nodeId:e,position:t,variant:n=Gs.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let v=Ll(),b=typeof e==`string`?e:v,C=bc(),w=(0,y.useRef)(null),T=n===Gs.Handle,E=G((0,y.useCallback)(sf(T&&p),[T,p]),hc),D=(0,y.useRef)(null),O=t??cf[n];(0,y.useEffect)(()=>{if(!(!w.current||!b))return D.current||=nc({domNode:w.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=C.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=C.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=ls([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...po({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};C.getState().triggerNodeChanges([n])}}),D.current.update({controlPosition:O,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{D.current?.destroy()}},[O,s,c,l,u,d,h,g,_,m]);let k=O.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__resize-control`,`nodrag`,...k,n,r]),ref:w,style:{...i,scale:E,...o&&{[T?`backgroundColor`:`borderColor`]:o}},children:a})}(0,y.memo)(lf);var uf=e=>e?.meta?.viewId??e?.meta?.diagramType??`architecture`,df=e=>e?.meta?.architectureView??`relations`,ff=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&df(e)!==`relations`,pf={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`},mf=Object.freeze([{id:`capabilities`,type:`architecture`,label:pf.capabilities},{id:`engineering`,type:`architecture`,label:pf.engineering},{id:`relations`,type:`architecture`,label:pf.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]),hf=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?df(e):e.meta.diagramType,gf=e=>mf.find(t=>t.id===hf(e))?.label??e?.meta?.diagramType??pf.relations,_f=(e,t)=>{let n=e=>{let t=mf.findIndex(t=>t.id===hf(e));return t<0?mf.length:t};return n(e)-n(t)},vf={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}},yf=[`en`,...Object.keys(vf)];function bf(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(vf,r)?vf[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function xf(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}var Sf=e=>!ff(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null;function Cf(e){let t=Sf(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function wf(e){let t=Sf(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!ff(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=xf(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function Tf(e){if(!Sf(e))return{...e,edges:wf(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of Cf(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:wf(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}var Ef=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),Df=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),Of=Object.freeze({...Ef,nodeGap:32,groupInset:24,groupGap:32});Object.freeze({...Df,nodeGap:40,layerGap:48});var kf=e=>e?.cardLayout?Of:Ef,Af=.75,jf=.45;Object.freeze({width:1392,height:688});var Mf=[`er`,`deployment`,`dataflow`,`usecase`],Nf=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[Mf.includes(e)?`right`:`down`],Pf=(e,t)=>(t?.direction??Nf(e)[0])===`down`,Ff={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},If=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],Lf={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},Rf=`MIT License + M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}af.displayName=`MiniMap`;var of=(0,y.memo)(af),sf=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,cf={[Gs.Line]:`right`,[Gs.Handle]:`bottom-right`};function lf({nodeId:e,position:t,variant:n=Gs.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let v=Ll(),b=typeof e==`string`?e:v,C=bc(),w=(0,y.useRef)(null),T=n===Gs.Handle,E=G((0,y.useCallback)(sf(T&&p),[T,p]),hc),D=(0,y.useRef)(null),O=t??cf[n];(0,y.useEffect)(()=>{if(!(!w.current||!b))return D.current||=nc({domNode:w.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=C.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=C.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=ls([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...po({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};C.getState().triggerNodeChanges([n])}}),D.current.update({controlPosition:O,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{D.current?.destroy()}},[O,s,c,l,u,d,h,g,_,m]);let k=O.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__resize-control`,`nodrag`,...k,n,r]),ref:w,style:{...i,scale:E,...o&&{[T?`backgroundColor`:`borderColor`]:o}},children:a})}(0,y.memo)(lf);var uf=e=>e?.meta?.viewId??e?.meta?.diagramType??`architecture`,df=e=>e?.meta?.architectureView??`relations`,ff=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&df(e)!==`relations`,pf={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`},mf=Object.freeze([{id:`capabilities`,type:`architecture`,label:pf.capabilities},{id:`engineering`,type:`architecture`,label:pf.engineering},{id:`relations`,type:`architecture`,label:pf.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]),hf=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?df(e):e.meta.diagramType,gf=e=>mf.find(t=>t.id===hf(e))?.label??e?.meta?.diagramType??pf.relations,_f=(e,t)=>{let n=e=>{let t=mf.findIndex(t=>t.id===hf(e));return t<0?mf.length:t};return n(e)-n(t)},vf={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`,"Source changes":`源码变化`,"Show source changes":`显示源码变化`,"Hide source changes":`隐藏源码变化`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`,"Source changes":`ソースの変更`,"Show source changes":`ソースの変更を表示`,"Hide source changes":`ソースの変更を隠す`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`,"Source changes":`소스 변경`,"Show source changes":`소스 변경 표시`,"Hide source changes":`소스 변경 숨기기`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`,"Source changes":`Quellcode-Änderungen`,"Show source changes":`Quellcode-Änderungen anzeigen`,"Hide source changes":`Quellcode-Änderungen ausblenden`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`,"Source changes":`Modifications du code`,"Show source changes":`Afficher les modifications du code`,"Hide source changes":`Masquer les modifications du code`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`,"Source changes":`Cambios en el código`,"Show source changes":`Mostrar cambios en el código`,"Hide source changes":`Ocultar cambios en el código`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости","Source changes":"Изменения в коде","Show source changes":"Показать изменения в коде","Hide source changes":"Скрыть изменения в коде"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`,"Source changes":`Alterações no código`,"Show source changes":`Mostrar alterações no código`,"Hide source changes":`Ocultar alterações no código`}},yf=[`en`,...Object.keys(vf)];function bf(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(vf,r)?vf[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function xf(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}var Sf=e=>!ff(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null;function Cf(e){let t=Sf(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function wf(e){let t=Sf(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!ff(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=xf(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function Tf(e){if(!Sf(e))return{...e,edges:wf(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of Cf(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:wf(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}var Ef=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),Df=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),Of=Object.freeze({...Ef,nodeGap:32,groupInset:24,groupGap:32});Object.freeze({...Df,nodeGap:40,layerGap:48});var kf=e=>e?.cardLayout?Of:Ef,Af=.75,jf=.45;Object.freeze({width:1392,height:688});var Mf=[`er`,`deployment`,`dataflow`,`usecase`],Nf=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[Mf.includes(e)?`right`:`down`],Pf=(e,t)=>(t?.direction??Nf(e)[0])===`down`,Ff={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},If=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],Lf={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},Rf=`MIT License Copyright (c) 2021-2022 Modulz Copyright (c) 2022-Present WorkOS @@ -276,14 +276,15 @@ ${t}.member{font:500 ${X.body}px ui-monospace,monospace;fill:${e.ink2}} ${t}.field-type{font:400 ${X.body}px ui-monospace,monospace;fill:${e.ink3}} `}function Xp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return em(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+xp.pad,v=g+xp.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*xp.chipLine;return`${Q(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>Q(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>Q(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>Q(v,b+14+t*f.lineHeight,e,`meta`)).join(``),E={x:g+xp.pad,y:_+(xp.titleLine-xp.plate)/2},D=t+e.size.width-c-xp.pad-p.width-l;return`${Zp(e,t,n,r,i,s)}${Qp(e,E.x,E.y,xp.plate,a)}${Q(D+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}var Zp=(e,t,n,r,i,a)=>Ip(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Qp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:Yf(e)?i.accent:Jf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${$p(e)}`}var $p=e=>Jf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function em(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Zp(e,t,n,r,i,s)}${Qp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,wp(e,o).text,`stereotype`)}${d}${f}`}var tm=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],nm=[[.08,0],[1,0],[.92,1],[0,1]];function rm(e,t,n){let{width:r,height:i}=e.size;if(Cg(e))return Lp(e,t,n,16);if(e.kind===`external`)return Bp(e,t,n,zp);if(e.kind===`security`)return Lp(e,t,n,22);if(e.kind===`failure`)return Bp(e,t,n,tm);if(e.kind===`config`)return Bp(e,t,n,nm);if(e.kind===`business`)return Lp(e,t,n,Math.min(28,i/2));let a=Lp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var im=(e,t,n)=>Cg(e)?Gp(e,t,n,16):e.kind===`external`?qp(e,t,n,zp):e.kind===`security`?Gp(e,t,n,22):e.kind===`failure`?qp(e,t,n,tm):e.kind===`config`?qp(e,t,n,nm):e.kind===`business`?Gp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):Wp(e,t,n),am=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,om={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Cg(e)?Mg(e,t,n,a,r,i):Xp(e,t,n,r,i,a,o,rm,am(e)),outline:rm,anchor:im,cardLayout:!0,contentInset:am},sm=.12,cm=(e,t,n)=>e.kind===`decision`?Vp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*sm},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Lp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),lm=(e,t,n)=>e.kind===`decision`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?qp(e,t,n,[[sm,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Gp(e,t,n,e.size.height/2):Wp(e,t,n),um=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*sm+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function dm(e,t,n,r,i){let{width:a,height:o}=e.size,s=um(e),c=Fp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Ip(cm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var fm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:dm,outline:cm,anchor:lm,textArea:um,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},pm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n):Lp(e,t,n,7,mm(e));function mm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function hm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=mm(e),u=Ip(pm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,up[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Np([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var gm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:hm,outline:pm,sequence:!0,selectionHeight:mm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},_m=(e,t,n)=>Lp(e,t,n,9);function vm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=dp(e),u=Pp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,Pp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,Pp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Ip(_m(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,Pp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var ym={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:vm,outline:_m,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},bm=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function xm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Bp(e,t,n,bm),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Lp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`external`?Bp(e,t,n,zp):e.kind===`service`?Lp(e,t,n,16):Lp(e,t,n,10)}var Sm=(e,t,n)=>e.kind===`device`?Wp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?qp(e,t,n,bm):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?qp(e,t,n,zp):e.kind===`service`?Gp(e,t,n,16):Wp(e,t,n),Cm=e=>({container:24,artifact:18,node:20})[e.kind]??0,wm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Tm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Xp(e,...t,xm,wm(e),Cm(e)),outline:xm,anchor:Sm,cardLayout:!0,contentInset:wm,cardCorner:Cm},Em=(e,t,n)=>Lp(e,t,n,9);function Dm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=dp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``);return`${Ip(Em(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),Pp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,Pp(e.subtitle,m),`body`):``}${h}${g}`}var Om={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:Dm,outline:Em,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=kp(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},km=e=>e.subtitle?14:e.size.width/2,Am=[`entry`,`do`,`exit`],jm={side:16,pad:8,line:20,keyWidth:64};function Mm(e){let t=e.kind===`state`?Am.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*jm.side-jm.keyWidth,X.small,jm.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*jm.line+2*jm.pad:0}}var Nm=2*jm.side+jm.keyWidth,Pm=e=>{let{height:t}=Mm(e);return t?{x:jm.side,y:e.size.height-t,width:e.size.width-2*jm.side,height:t}:null},Fm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+km(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Vp(e,t,n):Lp(e,t,n,12),Im=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=km(e)-e.size.width/2;return Kp({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Wp(e,t,n)},Lm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=Mm(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Rm(e,t,n,r,i){let{rows:a,height:o}=Mm(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+jm.pad+c++*jm.line+15;return(r?``:Q(t+jm.side,a,`${e.key} /`,`field-key`))+Q(t+jm.side+jm.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function zm(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Lm(e),o=e.kind===`final`;return`${Ip(Fm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Fp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Lm(e),l=n+(e.size.height-Mm(e).height)/2;return`${Ip(Fm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,l,e.label,c.width,c.height,e.subtitle)}${Rm(e,t,n,i,a)}`}var Bm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Vm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:zm,outline:Fm,anchor:Im,textArea:Lm,activityArea:Pm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Bm(e).map(e=>e.text).join(` `),edgeLabelParts:Bm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Am)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},Hm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Um=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Wm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n+Hm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Gm=(e,t,n)=>e.kind===`actor`?Jp(e,t,n,Hm(e)):Kp(e,t,n);function Km(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+Hm(e)+98,Pp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+Hm(e)+122,Pp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Um(e);return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var qm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Km,outline:Wm,anchor:Gm,textArea:Um,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Jm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Lp(e,t,n,e.kind===`process`?24:10),Ym=e=>({width:e.size.width-32,height:e.size.height-20});function Xm(e,t,n,r,i){let a=Ym(e);return`${Ip(Jm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Zm=[om,fm,gm,ym,Tm,Om,Vm,qm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Xm,outline:Jm,textArea:Ym,anchor:(e,t,n)=>e.kind===`process`?Gp(e,t,n,24):Wp(e,t,n)}],Qm=Zm.map(e=>e.id);Object.fromEntries(Zm.map(e=>[e.id,e.label]));var $m=new Map(Zm.map(e=>[e.id,e]));if($m.size!==Zm.length)throw Error(`Duplicate diagram type`);var eh=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>$m.get(e),th=(e,t,n,r=!1)=>t===`architecture`&&Cg(e)?Tg(e):Tp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),nh=e=>{let t=eh(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=th(n,t,e.meta?.locale).minHeight)},rh=(e,t)=>!($(t).undirected??[]).includes(e.kind),ih=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),ah=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),oh=(e,t)=>({start:null,end:rh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),sh=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ch=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),lh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var uh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,dh=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),fh=(e,t)=>e?.id??String(t);function ph(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(fh(i,t))}`);return n}function mh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===fh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>mh(e,t,n,r,a)))]}function hh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>fh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=fh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=mh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function gh(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function _h(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>gh(n,t)-gh(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var vh=e=>Z(e.label,Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function yh(e,t){let n={...e.position,...e.size},r=vh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>uh(e,t,4)))}function bh(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...dh(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>uh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:fh(null,0)}]}}function xh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;uh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=yh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=bh(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===fh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=mh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...dh(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Df.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1mh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...dh(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...dh(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${fh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Df.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>uh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=fh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${fh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function Sh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function Ch(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wh(e,t,n=Ch(e),r=ph(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Th=140,Eh=54,Dh=(e,t)=>(e.route?.messageY??Th+e.order*Eh)+(t===`receive`&&e.source===e.target?30:0);function Oh(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Dh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ph(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Dh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Dh(n.get(i.end.edgeId),i.end.at)-l}})}function Ah(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var jh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Mh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Nh(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ph(e,t=Yh(e)){e=Tf(e);let n=[...bg(e),...e.groups??[],...e.nodes,...kh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Nh(n.sourceCardinality,e.points[0],e.points[1]),Nh(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Fh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=jh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Ih(e,t,n=Ef.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Lh(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Rh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function zh(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Bh(e,t,n,r){let i={clearance:-1,length:-1,point:zh(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Vh(e,t){let n=jh(e),r=jh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Hh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?tg(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Ih(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Rh(f,e);return Rh(f,Ih(t,r,a)),f.push(t),Lh(f)}function Wh(e,t,n,r,i,a=Ef.endpoint,o=`architecture`){let s=Fh(e,n.sourceSide,r,o),c=Fh(t,n.targetSide,i,o),l=Ih(s,n.sourceSide,a),u=Ih(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Lh([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Lh([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Gh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Kh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var qh=(e,t=0,n=0)=>e.curved&&Kh(e,t,n)||Gh(e.points,t,n);function Jh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Dh(e,`send`),u=Dh(e,`receive`),d=Ah(o,t.id,e,`send`,l,s.get(e.id)),f=Ah(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||jh(t).x<=jh(n).x,m=d?d.x+(p?d.width:0):jh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):jh(n).x,g=wh(a,e,c,s),_=Math.abs(h-m),v=Dp(g,t.id===n.id?Df.labelWidth:Math.min(Df.labelWidth,Math.max(1,_-32-12))),y=t.id===n.id?null:Dp(g,Math.max(1,_-64)),b=y&&(e.route?.labelAt??{x:(m+h)/2,y:l-6-y.height/2}),x=y&&y.lines.lengthuh({x:b.x-y.width/2,y:b.y-y.height/2,width:y.width,height:y.height},e,2))?y:v,S={width:x.width,height:x.height};if(t.id===n.id){let t=48+r*Ef.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Uh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+S.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Uh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-S.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Yh(e){e=Tf(e);let t=eh(e),n=$(t).endpointStub??Ef.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Vh(t,n)}}),a=t===`sequence`?{graph:e,executions:kh(e),scopes:ph(e),pairs:Ch(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?jh(i).y:jh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*Ef.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Zh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,mm(e))}:{...e.position,...e.size}}function Qh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function $h(e,t,n,r){let i=tg(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=jh(t),o=Fh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function eg(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&eg(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=jh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Fh(n,`left`,o,r).x,c=Fh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Fh(n,`top`,o,r).y,c=Fh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function sg(e){e=Tf(e);let t=eh(e),n=[],r=Yh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...kh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightuh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!nh(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:xp.minHeight))continue;let{minHeight:r}=t===`architecture`&&Cg(n)?Tg(n):Tp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;eEf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${Ef.endpoint}px`);let f=og(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!$h(i.points[0],a,i.sourceSide,t)||!$h(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Ih(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(jh(a).x-jh(o).x),t=Math.max(160,i.labelBox.width+32);eXh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),rg(t).some(([e,t])=>eg(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Xh(i.labelBox,tg(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=rg(r);for(let i=1;ieg(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ag(a,o,e,t)>Ef.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var cg=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),lg=(e,t,n)=>Math.max(t,Math.min(n,e)),ug=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=lg(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function dg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(ug(e,n,r),ug(t,n,r),ug(n,e,t),ug(r,e,t))}function fg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function pg(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function mg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:lg(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:lg((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>ug({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>dg(e,t,r,n[(i+1)%n.length])))}var gg=new WeakMap;function _g(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=gg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Hm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,ug({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>dg(e,a,t,n)),...i.map(t=>fg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>mg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>hg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,ug({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>pg(e,t,c);else{let n=s===`rect`?c:tg(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,fg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),fg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},gg.set(e,{signature:n,probe:l}),l}function vg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return rg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function yg(e,t,n=[]){let r=new Set(n),i=eh(t),a=cg(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Zh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Yh(e),d=kf($(i)).labelGap,f=[...o.map(e=>Zh(e,i)),...l.flatMap(ig)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>eg(r,e,t))||l.some(n=>vg(r,e,n).distanceeg(r,e,t)))}))&&r.add(n.id)}return r}var bg=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},xg=e=>e&&typeof e==`object`&&!Array.isArray(e),Sg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Cg=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function wg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!zf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{xg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Sg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!xg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!xg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Sg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!xg(e.position)||!xg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Sg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!xg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Tg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Eg=e=>e.frame===`none`?0:Y.padding,Dg=(e,t)=>{let n=t-Eg(e)*2;return Eg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Og(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Eg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function kg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=bg(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Ag=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),jg=(e,t,n,r,i=``)=>`${Ag(n)}`;function Mg(e,t,n,r){let i=Hf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Tg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>jg(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>jg(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ng(e,t,n=0,r=0){let i=Hf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Eg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>jg(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>jg(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function Pg(e,t=new Map){if(!ff(e))return[];let n=[],r=bg(e);for(let t of r){let r=Dg(t,t.size.width)+Eg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Eg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Eg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Og(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Fg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=ip(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Ip(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` -`);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}function zg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Bg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(zg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Vg({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` -`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Hg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Ug({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Hg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Hg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Wg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Gg={diagram:Bg,boundary:Vg,overview:Wg},Kg={routed:Ug};function qg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e]));return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Jg(e,t){return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t}}))}var Yg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Xg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var Zg='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t,{keepColumns:n=!1}={}){let r=structuredClone(e),i=r.groups??[],a=new Map(r.edges.map(e=>[e.id,e])),o=new Map,s=r.nodes.every(e=>e.position);for(let e of[...r.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])o.has(t)||o.set(t,o.size);let c=e=>s?e.position.x:o.get(e.id)??1/0,l=(r.layout?.participantOrder??[...r.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||c(e)-c(t)||(e.ide.id)).map(e=>r.nodes.find(t=>t.id===e)),u=d.nodeGap+t*8,p=12+t*4,m=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=(e,t)=>A(m(e,t),f.labelWidth,14,20),g=e=>A(e.body,f.labelWidth,16,24),_=32;for(let e of l){let t=n&&s?e.position.x:_;e.size=Hr(e,`sequence`,r.meta.locale),e.position={x:Math.max(_,t),y:48},_=e.position.x+e.size.width+u}Tt(r,l);for(let e of r.edges)e.route={messageY:200+e.order*100};let v=H(r),y=Ot(r),b=new Set(i.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).order),S=e=>e.edge?e.edge.order:Math.min(1/0,...x(e.group)),C=e=>e.sort((e,t)=>S(e)-S(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),w=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>v.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),T=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=i.find(e=>e.id===n.parentId)){t.add(n.id);let e=w(n);if(e.length)return e}return[...v.values()].flatMap(e=>e.points)};for(let e of[...i].sort((e,t)=>vt(t,i)-vt(e,i)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=T(e),n=i.filter(t=>t.parentId===e.id),r=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[h(e,t).width,g(t).width])),o=e.operands.flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).route.messageY),s=Math.min(...o),c=Math.max(...o),u=y.filter(e=>!o.length||e.y<=c&&e.y+e.height>=s).sort((e,t)=>e.x-t.x),d=t.length?Math.min(...t.map(e=>e.x)):l[0].position.x,f=Math.min(d,...u.filter(e=>e.x=d-8).map(e=>e.x))-r-40,p=Math.min(f,...n.map(e=>e.position.x-32)),m=Math.max(p+r+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of u)e.xm-56-16&&(m=Math.max(m,e.x+e.width+56));e.position={x:p,y:0},e.size={width:Math.ceil(m-p),height:0}}function ee(e,t){let n=v.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+p}function E(e,t){for(let n of C(e))t=n.edge?ee(n.edge,t):te(n.group,t);return t}function te(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+p;for(let[t,r]of e.operands.entries()){n+=h(e,r).height+16,r.body&&(n+=g(r).height+16);let o=i.filter(n=>n.parentId===e.id&&n.parentOperandId===z(r,t));n=E([...r.edgeIds.map(e=>({edge:a.get(e)})),...o.map(e=>({group:e}))],n),n+=p}return e.size.height=n-t+16,t+e.size.height+p}let ne=E([...r.edges.filter(e=>!b.has(e.id)).map(e=>({edge:e})),...i.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...l.map(Ke))+d.labelGap),re=[...r.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...l.map(e=>e.position.x)));for(let e of[...l,...i])e.position.x+=D;for(let e of r.nodes)e.size.height=ne+32-e.position.y;return r}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',Qg=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,Zg],{type:`text/javascript;charset=utf-8`});function $g(e){let t;try{if(t=Qg&&(self.URL||self.webkitURL).createObjectURL(Qg),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zg),{name:e?.name})}}var e_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),t_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function n_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=e_(e.label,X.title),a=e_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return t_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>e_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return t_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=e_(e.name,X.body),n=e_(e.type,X.body);return Math.max(t+n+74,n/.55)});return t_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return t_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>e_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,e_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,t_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return t_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var r_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function i_(e){return e.layout?.tier?r_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var a_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),o_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function c_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function l_(e,t,n){s_(e.file,`${t}.file`,n),c_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function p_(e,t){f_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function m_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!o_(e))return[`graph must be an object`];o_(e.meta)||r.push(`meta must be an object`),s_(e.meta?.title,`meta.title`,r),s_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&s_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])c_(e.meta?.[t],`meta.${t}`,r);p_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!o_(c)){r.push(`${e} must be an object`);continue}s_(c?.id,`${e}.id`,r),s_(c?.label,`${e}.label`,r),c_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&s_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!o_(c.source)?r.push(`${e}.source must be an object`):c.source&&(l_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!a_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])f_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!o_(n)){r.push(`${i} must be an object`);continue}s_(n.name,`${i}.name`,r),s_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:s_,validateStringArray:f_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!o_(s)){r.push(`${e} must be an object`);continue}s_(s?.id,`${e}.id`,r),s_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),u_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!o_(o)){r.push(`${e} must be an object`);continue}s_(o?.id,`${e}.id`,r),c_(o.label,`${e}.label`,r),o.module!==void 0&&s_(o.module,`${e}.module`,r),s_(o?.source,`${e}.source`,r),s_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),a_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!o_(o.site)?r.push(`${e}.site must be an object`):o.site&&l_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>d_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&d_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:s_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:l_,evidenceKinds:a_})),r.length===0&&r.push(...h_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function h_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(o_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!r_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${r_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),o_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!o_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(o_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var g_=e=>({...e.position,...e.size}),__=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,v_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function b_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` +`);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}var zg=e=>Array.isArray(e.meta?.sourceDrift)?e.meta.sourceDrift:[],Bg=e=>new Set(zg(e).flatMap(e=>Array.isArray(e?.elements)?e.elements:[]));function Vg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Hg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${e.drifted?`is-drifted`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(Vg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Ug({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` +`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Wg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Gg({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Wg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Wg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan${r.drifted?` is-drifted`:``}`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Kg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var qg={diagram:Hg,boundary:Ug,overview:Kg},Jg={routed:Gg};function Yg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e])),a=Bg(e);return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r,drifted:a.has(n.id)},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Xg(e,t){let n=Bg(e);return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t,drifted:n.has(e.id)}}))}var Zg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Qg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var $g='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`,"Source changes":`源码变化`,"Show source changes":`显示源码变化`,"Hide source changes":`隐藏源码变化`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`,"Source changes":`ソースの変更`,"Show source changes":`ソースの変更を表示`,"Hide source changes":`ソースの変更を隠す`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`,"Source changes":`소스 변경`,"Show source changes":`소스 변경 표시`,"Hide source changes":`소스 변경 숨기기`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`,"Source changes":`Quellcode-Änderungen`,"Show source changes":`Quellcode-Änderungen anzeigen`,"Hide source changes":`Quellcode-Änderungen ausblenden`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`,"Source changes":`Modifications du code`,"Show source changes":`Afficher les modifications du code`,"Hide source changes":`Masquer les modifications du code`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`,"Source changes":`Cambios en el código`,"Show source changes":`Mostrar cambios en el código`,"Hide source changes":`Ocultar cambios en el código`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости","Source changes":"Изменения в коде","Show source changes":"Показать изменения в коде","Hide source changes":"Скрыть изменения в коде"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`,"Source changes":`Alterações no código`,"Show source changes":`Mostrar alterações no código`,"Hide source changes":`Ocultar alterações no código`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t,{keepColumns:n=!1}={}){let r=structuredClone(e),i=r.groups??[],a=new Map(r.edges.map(e=>[e.id,e])),o=new Map,s=r.nodes.every(e=>e.position);for(let e of[...r.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])o.has(t)||o.set(t,o.size);let c=e=>s?e.position.x:o.get(e.id)??1/0,l=(r.layout?.participantOrder??[...r.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||c(e)-c(t)||(e.ide.id)).map(e=>r.nodes.find(t=>t.id===e)),u=d.nodeGap+t*8,p=12+t*4,m=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=(e,t)=>A(m(e,t),f.labelWidth,14,20),g=e=>A(e.body,f.labelWidth,16,24),_=32;for(let e of l){let t=n&&s?e.position.x:_;e.size=Hr(e,`sequence`,r.meta.locale),e.position={x:Math.max(_,t),y:48},_=e.position.x+e.size.width+u}Tt(r,l);for(let e of r.edges)e.route={messageY:200+e.order*100};let v=H(r),y=Ot(r),b=new Set(i.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).order),S=e=>e.edge?e.edge.order:Math.min(1/0,...x(e.group)),C=e=>e.sort((e,t)=>S(e)-S(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),w=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>v.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),T=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=i.find(e=>e.id===n.parentId)){t.add(n.id);let e=w(n);if(e.length)return e}return[...v.values()].flatMap(e=>e.points)};for(let e of[...i].sort((e,t)=>vt(t,i)-vt(e,i)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=T(e),n=i.filter(t=>t.parentId===e.id),r=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[h(e,t).width,g(t).width])),o=e.operands.flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).route.messageY),s=Math.min(...o),c=Math.max(...o),u=y.filter(e=>!o.length||e.y<=c&&e.y+e.height>=s).sort((e,t)=>e.x-t.x),d=t.length?Math.min(...t.map(e=>e.x)):l[0].position.x,f=Math.min(d,...u.filter(e=>e.x=d-8).map(e=>e.x))-r-40,p=Math.min(f,...n.map(e=>e.position.x-32)),m=Math.max(p+r+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of u)e.xm-56-16&&(m=Math.max(m,e.x+e.width+56));e.position={x:p,y:0},e.size={width:Math.ceil(m-p),height:0}}function ee(e,t){let n=v.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+p}function E(e,t){for(let n of C(e))t=n.edge?ee(n.edge,t):te(n.group,t);return t}function te(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+p;for(let[t,r]of e.operands.entries()){n+=h(e,r).height+16,r.body&&(n+=g(r).height+16);let o=i.filter(n=>n.parentId===e.id&&n.parentOperandId===z(r,t));n=E([...r.edgeIds.map(e=>({edge:a.get(e)})),...o.map(e=>({group:e}))],n),n+=p}return e.size.height=n-t+16,t+e.size.height+p}let ne=E([...r.edges.filter(e=>!b.has(e.id)).map(e=>({edge:e})),...i.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...l.map(Ke))+d.labelGap),re=[...r.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...l.map(e=>e.position.x)));for(let e of[...l,...i])e.position.x+=D;for(let e of r.nodes)e.size.height=ne+32-e.position.y;return r}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',e_=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,$g],{type:`text/javascript;charset=utf-8`});function t_(e){let t;try{if(t=e_&&(self.URL||self.webkitURL).createObjectURL(e_),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent($g),{name:e?.name})}}var n_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),r_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function i_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=n_(e.label,X.title),a=n_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return r_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>n_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return r_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=n_(e.name,X.body),n=n_(e.type,X.body);return Math.max(t+n+74,n/.55)});return r_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return r_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>n_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,n_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,r_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return r_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var a_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o_(e){return e.layout?.tier?a_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var s_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),c_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function l_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function u_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function d_(e,t,n){l_(e.file,`${t}.file`,n),u_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function h_(e,t){m_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function g_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!c_(e))return[`graph must be an object`];c_(e.meta)||r.push(`meta must be an object`),l_(e.meta?.title,`meta.title`,r),l_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&l_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])u_(e.meta?.[t],`meta.${t}`,r);h_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!c_(c)){r.push(`${e} must be an object`);continue}l_(c?.id,`${e}.id`,r),l_(c?.label,`${e}.label`,r),u_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&l_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),f_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!c_(c.source)?r.push(`${e}.source must be an object`):c.source&&(d_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!s_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])m_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!c_(n)){r.push(`${i} must be an object`);continue}l_(n.name,`${i}.name`,r),l_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:l_,validateStringArray:m_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!c_(s)){r.push(`${e} must be an object`);continue}l_(s?.id,`${e}.id`,r),l_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),f_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!c_(o)){r.push(`${e} must be an object`);continue}l_(o?.id,`${e}.id`,r),u_(o.label,`${e}.label`,r),o.module!==void 0&&l_(o.module,`${e}.module`,r),l_(o?.source,`${e}.source`,r),l_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),s_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!c_(o.site)?r.push(`${e}.site must be an object`):o.site&&d_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>p_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&p_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:l_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:d_,evidenceKinds:s_})),r.length===0&&r.push(...__(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function __(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(c_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),c_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!c_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(c_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var v_=e=>({...e.position,...e.size}),y_=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,b_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function S_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` - `)?String(n).split(` -- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function x_(e,t={}){let n=m_(e,{inputOnly:!0}),r=n.length?[]:m_(e,{audit:!1}),i=n.length||r.length?null:S_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw b_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` -- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function S_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(i_(t)>=i_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)__(d,g_(e))||s(`group.member-inset`,[i.id,e.id],g_(e),d,[o,g_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&v_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,g_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=y_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[g_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(g_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function C_(e){return function(){return e}}var w_=1664525,T_=1013904223,E_=4294967296;function D_(){let e=1;return()=>(e=(w_*e+T_)%E_)/E_}var O_=10,k_=Math.PI*(3-Math.sqrt(5));function A_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=D_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function j_(e){var t=C_(.1),n,r,i;typeof e!=`function`&&(e=C_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),P_=e=>e.members.map(e=>e.kind),F_=(e,t)=>P_(e).some(e=>t.includes(e)),I_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function L_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(N_))}function R_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function z_(e,t){let n=L_(e,t.edges);return n.length===1&&e.length>5?R_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||N_(e,t)))}function B_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(N_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(N_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function V_(e,t){let n=t.layout?.primaryPath??[],r=L_(e,B_(t));return r.length===1&&e.length>5?R_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||N_(e,t)}))}function H_(e,t){let n=[...e].sort((e,n)=>I_(n,t.edges)-I_(e,t.edges)||N_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return R_(r)}function U_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(i_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>L_(e,t.edges))}function W_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=L_(r,n),o=L_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>F_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function G_(e,t){let n=e.filter(e=>F_(e,[`initial`])),r=e.filter(e=>F_(e,[`final`]));return[n,...L_(e.filter(e=>!n.includes(e)&&!r.includes(e)),B_(t)),r].filter(e=>e.length)}function K_(e,t,n=0){let r=e.filter(e=>F_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(N_),i.sort(N_)].filter(e=>e.length):n>=2?i.sort(N_).map(e=>[e]):H_(i,t)}function q_(e,t){let n=e.filter(e=>F_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=L_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(N_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:z_},flowchart:{structure:`workflow-spine`,arrange:V_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:H_},deployment:{structure:`runtime-tiers`,arrange:U_},class:{structure:`contract-hierarchy`,arrange:W_},state:{structure:`lifecycle-branches`,arrange:G_},usecase:{structure:`actor-system`,arrange:K_},dataflow:{structure:`process-store`,arrange:q_}});function J_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Y_=156,X_=160,Z_=(e,t,n)=>Math.max(t,Math.min(n,e));function Q_(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function $_(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function ev(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Y_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Y_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Y_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Y_))}}function tv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function nv(e,t=null){if(!t)try{return x_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=Q_(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=ev(t,$_(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=A_(o).velocityDecay(.42).force(`anchor-x`,j_(e=>e.anchorX).strength(.16)).force(`anchor-y`,M_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,tv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:Z_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Y_),e.position.x+Y_),y:r?e.position.y:Z_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Y_),e.position.y+Y_)};return t.bounds&&(n.x=Z_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=Z_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!J_(e,d))throw Error(`Arrange would invert template bands`);x_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var rv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function iv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;rv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function ov(e,t,n){let r=av(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function sv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function cv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var lv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]),uv=e=>e.meta?.diagramType===`sequence`?Af:jf;function dv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var fv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,pv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function mv(e,t){if(!fv.test(e))throw Error(`page has no graph-data element`);return e.replace(fv,(e,n,r,i)=>`${n}${pv(t)}${i}`)}function hv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function gv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function _v(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function vv(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function yv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return x_(vv(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function bv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(qg(e,a)),[l,u]=Dd(Jg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:iv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>gv(_,o,l),[_,o,l]),x=e=>{v(e),s(qg(e,a)),u(Jg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new $g,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:b_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(_v(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return x_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return x_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=vv(i,yv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=n_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&dv(a,lv(e),av(i,o,s),void 0,uv(e))||lo(a,i.clientWidth,i.clientHeight,.08,2,ov(i,o,s));return g(c,{duration:n,ease:iv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:iv});return}let i=p.current;if(!i)return;let o=av(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=cv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:iv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(qg(r,a)),u(Jg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=nv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function xv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function Sv(e,t){return e.map(e=>({node:e,rank:xv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Cv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?Sv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function wv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&xv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function Tv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Ev(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Dv(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Ov(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function kv(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Av={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function jv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Av.indent,X.body,Av.line)),o=r+Av.top+Av.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Av.indent,t+r*Av.line,e,`body`)).join(``);return o+=e.length*Av.line+Av.gap,r}).join(``);return{height:o-r+Av.bottom,svg:`${Q(n,r+Av.top,bf(t,`Key points`),`group`)}${s}`}}function Mv(e,t=`light`,n){x_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?jv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Ov(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>kv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Nv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:Mv(e,`light`,r)}))}function Pv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Fv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Iv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=mv(await(await s.getFile()).text(),e),l;try{l=Nv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Fv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Lv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw b_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw b_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Rv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Fv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function zv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Mv(e,t,i),s=`${Pv(e.meta.title)}.${n}`;await Lv(o,e),n===`svg`?Fv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Rv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Bv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=bv(e,s,d,i),[m,h]=o,g=m&&!s,_=Tv(d,()=>p.readGraph(p.currentGraph,0)),v=Cv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=wv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await zv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Iv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Vv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Hv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=sv(p,av(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:iv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:iv})},[e,r,n,t,i,a,o])}var Uv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Wv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Uv[e]})}function Gv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` +- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function C_(e,t={}){let n=g_(e,{inputOnly:!0}),r=n.length?[]:g_(e,{audit:!1}),i=n.length||r.length?null:w_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw S_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` +- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function w_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o_(t)>=o_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)y_(d,v_(e))||s(`group.member-inset`,[i.id,e.id],v_(e),d,[o,v_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&b_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,v_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=x_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[v_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(v_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function T_(e){return function(){return e}}var E_=1664525,D_=1013904223,O_=4294967296;function k_(){let e=1;return()=>(e=(E_*e+D_)%O_)/O_}var A_=10,j_=Math.PI*(3-Math.sqrt(5));function M_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=k_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function N_(e){var t=T_(.1),n,r,i;typeof e!=`function`&&(e=T_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),I_=e=>e.members.map(e=>e.kind),L_=(e,t)=>I_(e).some(e=>t.includes(e)),R_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function z_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(F_))}function B_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function V_(e,t){let n=z_(e,t.edges);return n.length===1&&e.length>5?B_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||F_(e,t)))}function H_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(F_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(F_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function U_(e,t){let n=t.layout?.primaryPath??[],r=z_(e,H_(t));return r.length===1&&e.length>5?B_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||F_(e,t)}))}function W_(e,t){let n=[...e].sort((e,n)=>R_(n,t.edges)-R_(e,t.edges)||F_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return B_(r)}function G_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>z_(e,t.edges))}function K_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=z_(r,n),o=z_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>L_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function q_(e,t){let n=e.filter(e=>L_(e,[`initial`])),r=e.filter(e=>L_(e,[`final`]));return[n,...z_(e.filter(e=>!n.includes(e)&&!r.includes(e)),H_(t)),r].filter(e=>e.length)}function J_(e,t,n=0){let r=e.filter(e=>L_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(F_),i.sort(F_)].filter(e=>e.length):n>=2?i.sort(F_).map(e=>[e]):W_(i,t)}function Y_(e,t){let n=e.filter(e=>L_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=z_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(F_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:V_},flowchart:{structure:`workflow-spine`,arrange:U_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:W_},deployment:{structure:`runtime-tiers`,arrange:G_},class:{structure:`contract-hierarchy`,arrange:K_},state:{structure:`lifecycle-branches`,arrange:q_},usecase:{structure:`actor-system`,arrange:J_},dataflow:{structure:`process-store`,arrange:Y_}});function X_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Z_=156,Q_=160,$_=(e,t,n)=>Math.max(t,Math.min(n,e));function ev(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function tv(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function nv(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Z_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Z_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Z_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Z_))}}function rv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function iv(e,t=null){if(!t)try{return C_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=ev(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=nv(t,tv(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=M_(o).velocityDecay(.42).force(`anchor-x`,N_(e=>e.anchorX).strength(.16)).force(`anchor-y`,P_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,rv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:$_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Z_),e.position.x+Z_),y:r?e.position.y:$_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Z_),e.position.y+Z_)};return t.bounds&&(n.x=$_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=$_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!X_(e,d))throw Error(`Arrange would invert template bands`);C_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var av=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function ov(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;av(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function cv(e,t,n){let r=sv(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function lv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function uv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var dv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]),fv=e=>e.meta?.diagramType===`sequence`?Af:jf;function pv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var mv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,hv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function gv(e,t){if(!mv.test(e))throw Error(`page has no graph-data element`);return e.replace(mv,(e,n,r,i)=>`${n}${hv(t)}${i}`)}function _v(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function vv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function yv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function bv(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function xv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return C_(bv(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function Sv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(Yg(e,a)),[l,u]=Dd(Xg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:ov},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>vv(_,o,l),[_,o,l]),x=e=>{v(e),s(Yg(e,a)),u(Xg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new t_,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:S_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(yv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return C_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return C_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=bv(i,xv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=i_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&pv(a,dv(e),sv(i,o,s),void 0,fv(e))||lo(a,i.clientWidth,i.clientHeight,.08,2,cv(i,o,s));return g(c,{duration:n,ease:ov})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:ov});return}let i=p.current;if(!i)return;let o=sv(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=uv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:ov})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(Yg(r,a)),u(Xg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=iv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function Cv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function wv(e,t){return e.map(e=>({node:e,rank:Cv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Tv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?wv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function Ev(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&Cv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function Dv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Ov(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function kv(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Av(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function jv(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Mv={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function Nv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Mv.indent,X.body,Mv.line)),o=r+Mv.top+Mv.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Mv.indent,t+r*Mv.line,e,`body`)).join(``);return o+=e.length*Mv.line+Mv.gap,r}).join(``);return{height:o-r+Mv.bottom,svg:`${Q(n,r+Mv.top,bf(t,`Key points`),`group`)}${s}`}}function Pv(e,t=`light`,n){C_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?Nv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Av(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>jv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Fv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:Pv(e,`light`,r)}))}function Iv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Lv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Rv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=gv(await(await s.getFile()).text(),e),l;try{l=Fv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Lv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function zv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw S_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw S_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Bv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Lv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function Vv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Pv(e,t,i),s=`${Iv(e.meta.title)}.${n}`;await zv(o,e),n===`svg`?Lv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Bv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Hv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=Sv(e,s,d,i),[m,h]=o,g=m&&!s,_=Dv(d,()=>p.readGraph(p.currentGraph,0)),v=Tv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=Ev(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await Vv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Rv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Uv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Wv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=lv(p,sv(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:ov});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:ov})},[e,r,n,t,i,a,o])}var Gv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Kv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Gv[e]})}function qv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` `),badges:structuredClone(e?.badges??[]),error:``,returnFocus:t});(0,y.useEffect)(()=>{u.current++,o(),p()},[c]);let m=e=>f(t=>({...t,...e}));return{...d,section:!!e?.section,overview:l,set:m,cancel:()=>{u.current++,o(),p(!0)},begin:()=>m({editing:!0,returnFocus:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` -`),badges:structuredClone(e?.badges??[]),error:``}),save:async a=>{if(a.preventDefault(),d.pending)return;let o=d.label.trim();if(!o){m({error:bf(i,`Name is required`)});return}if(d.badges.some(e=>!e.label.trim())){m({error:bf(i,`Name is required`)});return}let s=++u.current;m({pending:!0});let c=await(t?r(t.id,o):n(e.id,o,d.subtitle.trim(),l?{overviewText:d.overviewText.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),...e.section?{}:{badges:d.badges}}:{}));if(u.current===s){if(m({pending:!1}),c){m({error:c});return}m({editing:!1,error:``})}}}}function Kv({editor:e,relation:t,locked:n,locale:r}){let i=e=>bf(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&!e.section&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),!t&&e.overview&&(0,x.jsxs)(`label`,{children:[i(`Overview text`),(0,x.jsx)(`textarea`,{disabled:e.pending,"aria-label":i(`Overview text`),value:e.overviewText,onChange:t=>e.set({overviewText:t.target.value,error:``})})]}),!t&&e.overview&&!e.section&&(0,x.jsxs)(`fieldset`,{disabled:e.pending,children:[(0,x.jsx)(`legend`,{children:i(`Badges`)}),e.badges.map((t,n)=>{let r=t=>e.set({badges:e.badges.map((e,r)=>r===n?{...e,...t}:e)});return(0,x.jsxs)(`div`,{className:`badge-editor`,children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{"aria-label":`${i(`Badges`)} ${n+1}`,value:t.label,onChange:e=>{let{source:n,...i}=t;r({...i,source:void 0,label:e.target.value,evidence:`document`})}})]}),(0,x.jsxs)(`label`,{children:[i(`Badge type`),(0,x.jsx)(`select`,{value:t.role,onChange:e=>r({role:e.target.value}),children:[`status`,`version`,`requirement`].map(e=>(0,x.jsx)(`option`,{value:e,children:i({status:`Status`,version:`Version`,requirement:`Requirement`}[e])},e))})]}),(0,x.jsxs)(`label`,{children:[i(`Evidence`),(0,x.jsx)(`select`,{value:t.evidence,onChange:e=>r({evidence:e.target.value}),children:[`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`].map(e=>(0,x.jsx)(`option`,{value:e,children:i(cp[e]??e)},e))})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:e.badges.filter((e,t)=>t!==n)}),children:i(`Remove badge`)})]},n)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:[...e.badges,{label:``,role:`status`,evidence:`document`}]}),children:i(`Add badge`)})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var qv=292,Jv=232,Yv=14;function Xv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>bf(c,e,t),_=!!t,v=_?(Yh(d).get(t.id)?.label??Mh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(Jv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??Jv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Zh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=av(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Yv,y:N.top},{side:`left`,x:N.left-Yv-qv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Yv},{side:`above`,x:N.left,y:N.top-Yv-C}],F=e=>e.x>=P.left&&e.x+qv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Zh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Yh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...dh(e)]),n=kh(d);for(let r of d.groups??[]){let i=xh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+qv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-qv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?lp(e.source):_&&t.site?lp(t.site):null,ae=_?op(t,r,o,s,n,Ch(d).get(t.id)):ip(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:qv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(Wv,{name:`close`})}),u.editing?(0,x.jsx)(Kv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(up[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(cp[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(Wv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(Kv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(Wv,{name:`arrowRight`})]})]})]})]})}var Zv=[`system`,`light`,`dark`],Qv={system:`Follow system`,light:`Light`,dark:`Dark`};function $v(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function ey({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>bf(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,onOverviewKeyDown:ie,layoutPending:ae,cancelLayout:oe,updateNodeText:se,updateEdgeText:ce,readGraph:le,focusDiagram:ue,nudgeLayout:de,visibleNodes:fe,visibleEdges:pe,reset:me,exportDiagram:he,saveGraph:ge,exportStatus:_e,layoutProblem:ve,layoutWarnings:ye,focusProblem:be,boardRef:xe,fullscreenButtonRef:Se,isFullscreen:Ce,fullscreenPending:we,fullscreenSupported:Te,toggleFullscreen:Ee,toolbarOpen:De,drawerOpen:Oe,toolbarButtonRef:ke,drawerButtonRef:Ae,searchInputRef:je,inspectorRef:Me,panelRef:Ne,toggleToolbar:Pe,toggleDrawer:Fe,openDetails:Ie}=Bv(e,c,d,i,t,n,f),[Le,Re]=$v(De,v,Ne),[ze,Be]=$v(Oe,v,Me),Ve=(0,y.useRef)(null),He=Gv(w,T,se,ce,e.meta.locale,ff(e),oe),{open:Ue,toggle:We,close:Ge}=Vv(),Ke=e.meta.notes??[],[qe,Je]=(0,y.useState)(!0),Ye=Ke.length>0&&qe&&!ze,Xe=Oe||Ye&&!Ce,Ze=(0,y.useRef)(!1),Qe=(0,y.useRef)(null);(0,y.useEffect)(()=>{Ze.current&&Qe.current?.focus({preventScroll:!0})},[qe]);let $e=Hv(ne,z,L,g,v),[et,tt]=(0,y.useState)(!1),[nt,rt]=(0,y.useState)(``),[it,at]=(0,y.useState)(0);(0,y.useEffect)(()=>{(Oe||O===0)&&at(O)},[Oe,O]);let ot=(0,y.useMemo)(()=>{let e=new Map(fe.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:Mp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=Lg(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,fe]);(0,y.useEffect)(()=>{if(!_e)return;rt(h(_e.message));let e=window.setTimeout(()=>rt(``),4500);return()=>window.clearTimeout(e)},[_e]);let st=O>0&&!Oe&&(g!==`sequence`||O!==it)&&!z.some(e=>e.dragging),ct=st?z.find(e=>e.id===E&&e.type===`diagram`):null,lt=st?pe.find(e=>e.id===D):null,ut=lt?L.edges.find(e=>e.id===lt.id):null,dt=lt?{position:lt.data.route.labelPoint,size:{width:0,height:0}}:null,ft=ut?L.nodes.find(e=>e.id===ut.source):null,pt=ut?L.nodes.find(e=>e.id===ut.target):null,mt=T?L.nodes.find(e=>e.id===T.source):null,ht=T?L.nodes.find(e=>e.id===T.target):null,gt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id),_t=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(Wv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ip(w,_,i).stroke}}),h(w.section?`Section`:up[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.overviewText?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Overview text`)}),(0,x.jsx)(`ul`,{children:w.overviewText.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(cp[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.source)})]},t))})]}),(e=>e.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Shared dependencies`)}),(0,x.jsx)(`ul`,{children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>P(e),children:[e.label??e.kind,` → `,L.nodes.find(t=>t.id===e.target)?.label]}),e.site&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.site)})]},e.id))})]}))(Cf(L).filter(e=>e.source===w.id)),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(cp[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:lp(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:pe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Yh(L).get(T.id)?.label??Mh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[mt?.label,` → `,ht?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(cp[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:lp(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(Wv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:He.editing?``:`card-actions`,children:(0,x.jsx)(Kv,{editor:He,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return Oe&&(Ve.current=_t),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||$e(E,D,!0,Xe)},"aria-controls":`graph-tools`,"aria-expanded":De,"aria-pressed":De,"aria-label":h(De?`Hide graph navigation`:`Show graph navigation`),title:h(De?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(Wv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(gf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>tt(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tt(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(Wv,{name:`search`}),(0,x.jsx)(`input`,{ref:je,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),et&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>We(`views`),"aria-haspopup":`menu`,"aria-expanded":Ue===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(Wv,{name:`views`}),(0,x.jsx)(`span`,{children:h(gf(e))}),(0,x.jsx)(Wv,{name:`chevron`})]}),Ue===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{eh(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(Wv,{name:`check`}):null}),`${h(gf(t))}${r.filter(e=>hf(e)===hf(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(Wv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>We(`more`),"aria-haspopup":`menu`,"aria-expanded":Ue===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(Wv,{name:`more`})}),Ue===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`svg`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`png`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{ge(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{me(),Ge()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{de(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Wv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":Zv.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${Zv.indexOf(l)*100}%)`}}),Zv.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(Qv[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:Ae,onClick:()=>{Fe(),Oe||$e(E,D,De,!0)},"aria-controls":`node-inspector`,"aria-expanded":Oe,"aria-pressed":Oe,title:h(Oe?`Hide details`:`Show details`),"aria-label":h(Oe?`Hide details`:`Show details`),children:(0,x.jsx)(Wv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${De?`nav-open`:``} ${Oe?`drawer-open`:``}`,children:[Le&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Ne,tabIndex:-1,className:`sidebar nav${Re}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Pe,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(Wv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(gt)})]}),(0,x.jsxs)(`figure`,{ref:xe,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:Yp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ae,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":De,"data-drawer-open":Xe,onKeyDownCapture:e=>{ie(e),e.defaultPrevented||F(e)},"aria-label":h(`Interactive {type}`,{type:h(gf(e))}),children:[(0,x.jsxs)(Sd,{nodes:fe,edges:pe,nodeTypes:Gg,edgeTypes:Kg,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),Ge()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>le(L,0)),nodesDraggable:!I&&!ae,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:ue,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(Wv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:Se,onClick:Ee,"aria-pressed":Ce,"aria-busy":we,"aria-disabled":we||!Te&&!Ce,"aria-label":h(Ce?`Exit fullscreen`:`Enter fullscreen`),title:h(!Te&&!Ce?`Fullscreen is not available in this browser or page`:Ce?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(Wv,{name:Ce?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ot,nodeStrokeColor:e=>e.type===`boundary`?`none`:ip(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:ip(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>We(`legend`),"aria-expanded":Ue===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(Wv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),Ue===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:Xg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:Yg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Ke.length>0&&!ze&&(Ye?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":h(`Key points`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[h(`Key points`),` · `,Ke.length]}),(0,x.jsx)(`button`,{className:`side-close`,ref:Qe,onClick:()=>{Ze.current=!0,Je(!1)},"aria-label":h(`Hide key points`),title:h(`Hide key points`),children:(0,x.jsx)(Wv,{name:`close`})})]}),(0,x.jsx)(`ul`,{children:Ke.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:Qe,"aria-expanded":`false`,onClick:()=>{Ze.current=!0,Je(!0),Ce||$e(E,D,De,!0)},"aria-label":h(`Show key points`),title:h(`Show key points`),children:[(0,x.jsx)(Wv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[h(`Key points`),` · `,Ke.length]})]})),ct&&(0,x.jsx)(Xv,{node:{...ct.data,position:ct.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),ut&&(0,x.jsx)(Xv,{node:dt,edge:{...ut,diagramType:g},source:ft,target:pt,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),$e(E,D,De,!0))},onClose:()=>ee()}),!ve&&ye.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ye.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>be(ye.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),ve&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:ve.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>be(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:ve.message})]}),(0,x.jsx)(`div`,{className:`toast ${nt?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:nt})]})]}),ze&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:Me,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${Be}`,"aria-label":h(`Details`),children:Ve.current})]})]})}function ty(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var ny=JSON.parse(document.querySelector(`#graph-data`).textContent),ry=[...Array.isArray(ny.diagrams)?ny.diagrams:[ny]].sort(_f),iy=window.matchMedia(`(prefers-color-scheme: dark)`);function ay(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(iy.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return iy.addEventListener(`change`,e),()=>iy.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function oy(){let[e,t]=(0,y.useState)(uf(ry[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=ay(),s=ty(),c=ry.find(t=>uf(t)===e)??ry[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>hv(ny,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=$f(ry,Kf[o]);return f?e:tp(e,Kf[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(sp(Kf[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)(ey,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:ry,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(oy,{})); - diff --git a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx index c831dc9..a58f944 100644 --- a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx +++ b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx @@ -9,6 +9,7 @@ import { cardinalityMarks } from './edge-routing.js'; import { renderFragment, fragmentDepth } from './sequence-fragments.js'; import { isCore, TYPOGRAPHY } from './visual-style.js'; import { groupHeadingSvg, groupFrameSvg } from './diagrams/drawing.js'; +import { driftedElements } from './source-changes.js'; function NodeHandles({ sequence = false }) { if (sequence) return <> @@ -30,7 +31,7 @@ function NodeHandles({ sequence = false }) { function DiagramNode({ data, selected }) { const moduleColor = data.moduleColors?.get(data.module); const markup = renderNode({ ...data, position: { x: 0, y: 0 } }, data.diagramType, 0, 0, data.palette, data.locale, data.moduleColors); - return
+ return
{selected && } @@ -79,7 +80,7 @@ function RoutedEdge({ id, markerEnd, style, data }) { {label.label} )} - {route.label && } + {route.label && } ; } @@ -101,19 +102,20 @@ export function initialNodes(graph, diagramType) { connectable: false, zIndex: -(graph.groups?.length ?? 0) + fragmentDepth(group, graph.groups ?? []) })); - const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])); + const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])), drifted = driftedElements(graph); return [...overviewSections(graph).map((section, index) => ({ id: section.id, type: 'overview', position: section.position, data: { ...section }, style: { width: section.size.width, height: section.size.height, pointerEvents: 'none' }, draggable: false, selectable: false, zIndex: -100 + index })), ...boundaries, ...graph.nodes.map(node => ({ id: node.id, type: 'diagram', className: diagramType === 'sequence' ? 'sequence-column' : undefined, position: node.position, - data: { ...drawn.get(node.id), diagramType, locale: graph.meta.locale, classicCard }, + data: { ...drawn.get(node.id), diagramType, locale: graph.meta.locale, classicCard, drifted: drifted.has(node.id) }, style: { width: node.size.width, height: node.size.height, ...(diagramType === 'sequence' ? { pointerEvents: 'none' } : {}) }, zIndex: 2 }))]; } export function initialEdges(graph, diagramType) { + const drifted = driftedElements(graph); return visibleEdges(graph).map(edge => ({ id: edge.id, source: edge.source, @@ -121,6 +123,6 @@ export function initialEdges(graph, diagramType) { type: 'routed', zIndex: diagramType === 'sequence' ? 3 : 0, markerEnd: hasArrow(edge, diagramType) ? { type: MarkerType.ArrowClosed } : undefined, - data: { ...edge, diagramType } + data: { ...edge, diagramType, drifted: drifted.has(edge.id) } })); } diff --git a/skills/q-flow/assets/viewer/src/ViewerShell.jsx b/skills/q-flow/assets/viewer/src/ViewerShell.jsx index 8302850..8a6976d 100644 --- a/skills/q-flow/assets/viewer/src/ViewerShell.jsx +++ b/skills/q-flow/assets/viewer/src/ViewerShell.jsx @@ -9,6 +9,7 @@ import { visibleEdgeLabel, createEdgeRoutes } from './edge-routing.js'; import { svgStyles, groupFrameSvg } from './diagrams/drawing.js'; import { anchorText, evidenceLabels, kindLabels, nodeAppearance } from './visual-style.js'; import { foldedEdges } from './presentation-graph.js'; +import { sourceChanges } from './source-changes.js'; import { graphLegend, rampGradient } from './legend.js'; import { useViewerController } from './features/useViewerController.js'; import { usePopover } from './features/usePopover.js'; @@ -58,9 +59,12 @@ export default function ViewerShell({ graph, originalGraph, graphForSave, allDia // everything but name: while it shows, the reading area gives up the right edge exactly as it does for the details drawer, // and it waits for that drawer (even while it slides out) to be gone before it appears. Fullscreen has no panels, so // there it simply floats over the canvas until it is hidden. - const notes = graph.meta.notes ?? []; + // Unresolved source changes (meta.sourceDrift) share the card: they follow the key points, or stand alone. + const notes = graph.meta.notes ?? [], changes = sourceChanges(graph); + const side = notes.length ? { title: t('Key points'), count: notes.length, hide: t('Hide key points'), show: t('Show key points') } + : { title: t('Source changes'), count: changes.length, hide: t('Hide source changes'), show: t('Show source changes') }; const [notesOpen, setNotesOpen] = useState(true); - const notesShown = notes.length > 0 && notesOpen && !drawerShown; + const notesShown = side.count > 0 && notesOpen && !drawerShown; const rightReserved = drawerOpen || (notesShown && !isFullscreen); // The hide and show buttons replace each other, so a reader's toggle hands focus to whichever one appears. const notesToggled = useRef(false), notesFocusRef = useRef(null); @@ -236,12 +240,20 @@ export default function ViewerShell({ graph, originalGraph, graphForSave, allDia } - {notes.length > 0 && !drawerShown && (notesShown - ?
-

{t('Key points')} · {notes.length}

-
    {notes.map((note, index) =>
  • {note}
  • )}
+ {side.count > 0 && !drawerShown && (notesShown + ?
+

{side.title} · {side.count}

+ {notes.length > 0 &&
    {notes.map((note, index) =>
  • {note}
  • )}
} + {changes.length > 0 && <>{notes.length > 0 &&

{t('Source changes')} · {changes.length}

}
    {changes.map((item, index) =>
  • + {String(item?.file ?? '').split('/').pop()}:{item?.line} {item?.change} + {(item?.elements ?? []).map(id => { + const node = currentGraph.nodes.find(entry => entry.id === id), edge = node ? null : currentGraph.edges.find(entry => entry.id === id); + return node || edge ? : null; + })} + {(item?.removed?.length > 0 || item?.added?.length > 0) &&
    {[...(item.removed ?? []).slice(0, 3).map(line => `- ${line}`), ...(item.added ?? []).slice(0, 3).map(line => `+ ${line}`)].join('\n')}
    } +
  • )}
}
- : )} + : )} {cardNode && { if (isFullscreen && !await toggleFullscreen()) return; diff --git a/skills/q-flow/assets/viewer/src/i18n-messages.json b/skills/q-flow/assets/viewer/src/i18n-messages.json index bb02dc1..8562fc5 100644 --- a/skills/q-flow/assets/viewer/src/i18n-messages.json +++ b/skills/q-flow/assets/viewer/src/i18n-messages.json @@ -184,7 +184,10 @@ "Component relationship architecture": "组件关系架构图", "Platform capability architecture": "平台能力架构图", "Engineering layer architecture": "工程分层架构图", - "Shared dependencies": "公共依赖" + "Shared dependencies": "公共依赖", + "Source changes": "源码变化", + "Show source changes": "显示源码变化", + "Hide source changes": "隐藏源码变化" }, "ja": { "Architecture": "アーキテクチャ", @@ -371,7 +374,10 @@ "Engineering layer architecture": "プロジェクト階層アーキテクチャ図", "Layout suggestions": "レイアウトの提案", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。", - "Shared dependencies": "共通の依存先" + "Shared dependencies": "共通の依存先", + "Source changes": "ソースの変更", + "Show source changes": "ソースの変更を表示", + "Hide source changes": "ソースの変更を隠す" }, "ko": { "Architecture": "아키텍처", @@ -558,7 +564,10 @@ "Engineering layer architecture": "엔지니어링 계층 아키텍처", "Layout suggestions": "레이아웃 제안", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.", - "Shared dependencies": "공통 의존성" + "Shared dependencies": "공통 의존성", + "Source changes": "소스 변경", + "Show source changes": "소스 변경 표시", + "Hide source changes": "소스 변경 숨기기" }, "de": { "Architecture": "Architektur", @@ -745,7 +754,10 @@ "Engineering layer architecture": "Schichtenarchitektur", "Layout suggestions": "Layoutvorschläge", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.", - "Shared dependencies": "Gemeinsame Abhängigkeiten" + "Shared dependencies": "Gemeinsame Abhängigkeiten", + "Source changes": "Quellcode-Änderungen", + "Show source changes": "Quellcode-Änderungen anzeigen", + "Hide source changes": "Quellcode-Änderungen ausblenden" }, "fr": { "Architecture": "Architecture", @@ -932,7 +944,10 @@ "Engineering layer architecture": "Architecture en couches", "Layout suggestions": "Suggestions de disposition", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.", - "Shared dependencies": "Dépendances partagées" + "Shared dependencies": "Dépendances partagées", + "Source changes": "Modifications du code", + "Show source changes": "Afficher les modifications du code", + "Hide source changes": "Masquer les modifications du code" }, "es": { "Architecture": "Arquitectura", @@ -1119,7 +1134,10 @@ "Engineering layer architecture": "Arquitectura por capas", "Layout suggestions": "Sugerencias de diseño", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.", - "Shared dependencies": "Dependencias compartidas" + "Shared dependencies": "Dependencias compartidas", + "Source changes": "Cambios en el código", + "Show source changes": "Mostrar cambios en el código", + "Hide source changes": "Ocultar cambios en el código" }, "ru": { "Architecture": "Архитектура", @@ -1306,7 +1324,10 @@ "Engineering layer architecture": "Слоистая архитектура", "Layout suggestions": "Рекомендации по размещению", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.", - "Shared dependencies": "Общие зависимости" + "Shared dependencies": "Общие зависимости", + "Source changes": "Изменения в коде", + "Show source changes": "Показать изменения в коде", + "Hide source changes": "Скрыть изменения в коде" }, "pt": { "Architecture": "Arquitetura", @@ -1493,6 +1514,9 @@ "Engineering layer architecture": "Arquitetura em camadas", "Layout suggestions": "Sugestões de disposição", "Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.": "Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.", - "Shared dependencies": "Dependências compartilhadas" + "Shared dependencies": "Dependências compartilhadas", + "Source changes": "Alterações no código", + "Show source changes": "Mostrar alterações no código", + "Hide source changes": "Ocultar alterações no código" } } diff --git a/skills/q-flow/assets/viewer/src/source-changes.js b/skills/q-flow/assets/viewer/src/source-changes.js new file mode 100644 index 0000000..7d5c443 --- /dev/null +++ b/skills/q-flow/assets/viewer/src/source-changes.js @@ -0,0 +1,4 @@ +// meta.sourceDrift: source changes validate --fix listed and the author has not resolved yet. Until each item is deleted +// the Viewer marks the elements it names and lists it beside the key points; validation keeps failing meanwhile. +export const sourceChanges = graph => Array.isArray(graph.meta?.sourceDrift) ? graph.meta.sourceDrift : []; +export const driftedElements = graph => new Set(sourceChanges(graph).flatMap(item => Array.isArray(item?.elements) ? item.elements : [])); diff --git a/skills/q-flow/assets/viewer/src/styles.css b/skills/q-flow/assets/viewer/src/styles.css index 691c6b0..d420c63 100644 --- a/skills/q-flow/assets/viewer/src/styles.css +++ b/skills/q-flow/assets/viewer/src/styles.css @@ -187,6 +187,13 @@ button:disabled { cursor: not-allowed; } .notes-card ul { margin: 0; padding-left: 16px; color: var(--label-2); font-size: 13px; line-height: 1.6; } .notes-card li + li { margin-top: 5px; } .notes-card li::marker { color: var(--accent); } +.notes-card .source-changes-title { margin: 12px 0 6px; } +.notes-card .source-changes li::marker { color: var(--warm); } +.source-changes code { font-size: 12px; color: var(--label); } +.source-changes .folded-edge { display: block; margin-top: 2px; color: var(--warm); } +.source-changes pre { margin: 4px 0 0; padding: 4px 6px; border-radius: var(--r-control); background: var(--fill); color: var(--label-2); font-size: 11px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; } +.diagram-node.is-drifted { outline: 2px dashed var(--warm); outline-offset: 3px; } +.edge-label.is-drifted { box-shadow: 0 0 0 1.5px var(--warm); } .workspace.nav-open .legend-anchor { left: calc(var(--side-w) + 2 * var(--gutter)); } .float-btn { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 9px; border: 0; border-radius: var(--r-field); color: var(--label); background: var(--material-thin); -webkit-backdrop-filter: var(--blur-thin); backdrop-filter: var(--blur-thin); box-shadow: 0 0 0 .5px var(--sep), var(--shadow-1); cursor: pointer; font-size: 12px; transition: background var(--fast) var(--ease), transform 100ms ease-out; } .float-btn .ic { width: 14px; height: 14px; color: var(--label-2); } diff --git a/skills/q-flow/references/graph-schema.md b/skills/q-flow/references/graph-schema.md index 07ad367..d7f166d 100644 --- a/skills/q-flow/references/graph-schema.md +++ b/skills/q-flow/references/graph-schema.md @@ -98,7 +98,7 @@ The abbreviated graphs above show only the wrapper; every graph still follows th - Optional node `source.kind` uses the same evidence values. `source.file` and `source.lineStart` identify the exact anchor. - Optional edge `site` (`file`, `lineStart`, optional `lineEnd` and `symbol`) records the line that makes the relationship hold: the call, write, foreign key, `extends` clause or state assignment. It has the same shape and checks as a node `source` but no `kind`: the edge's own `evidence` names the kind. An edge needs one when its `evidence` is `source`, `code`, `config`, `schema` or `test` and it is not a sequence `return` (`needsSite()`); the field is optional everywhere, so graphs written without it stay valid. - With `--repo-root `, validation and generation read every node's `source.file` and every edge's `site.file` as repository-relative UTF-8 text and check the inclusive line range. Absolute paths, parent traversal, directories, binary files and symlinks escaping the root are rejected. Repeated references share one file read. When `source.symbol` is present, its last segment (split on every character other than a letter, digit, `_` or `$`) must occur as a whole word within the range; write the name as it appears at the definition, not a description. A failure names the lines where the word does occur in the file, and the receipt counts symbol checks in `sourceEvidence.symbols` and relationship coverage in `sourceEvidence.relations` (`sited` of `eligible`, computed with or without the root). A site failure is named `diagrams[i].edges[j].site`. `--fix --repo-root` moves a node `source` or edge `site` `lineStart` to the only such line in the file and shifts `lineEnd` with it, clamped to the last line; anchors with several or no matches stay for the author (`edge .site` in the messages). Without the root, receipts explicitly mark existing source anchors `skipped`; without anchors they report `not-applicable`. These checks cover the local working tree, not `sourceRef` revision identity, definition parsing or claim correctness: a mention of the name left inside the range still passes. -- Source drift. With `--repo-root` inside a git work tree, generation and `validate --fix` record `meta.sourceFiles` on every view: each anchored file mapped to the git blob hash of the content its anchors point at (computed with `git hash-object`, nothing written to the repository). Later validation diffs each file against that blob: an anchor on a line that only moved follows it (in memory; `--fix` and generation write the new numbers) and passes, while changed code fails as source drift, grouped per changed hunk with the old and new lines, the anchored elements and the text that names what changed. Drift is reported when (1) an anchored line was rewritten, with any text still stating a number the rewrite changed; (2) a removed call leaves a method with no caller in the repository, naming the anchors inside it and the text that names what only it used; (3) added code that mentions an anchored symbol or calls a receiver named like an anchored file sits on no anchor; (4) an identifier gone from the anchored files is still written in the graph. `validate --fix --repo-root` realigns every anchor, renews `meta.sourceFiles` and appends one `meta.sourceDrift` item per change to each view it touches (`file`, `line`, `change`, `removed`, `added`, `anchors`, `mentions`); validation and generation fail while any item remains, so the author updates the named elements and deletes each item. A baseline blob missing from the repository (a shallow CI clone: use `fetch-depth: 0`) is reported and that file falls back to the working-tree check above; graphs without `meta.sourceFiles` keep that check unchanged. The rules are C-family text heuristics, not a parser: a call split across lines or an overloaded name can be missed. +- Source drift. With `--repo-root` inside a git work tree, generation and `validate --fix` record `meta.sourceFiles` on every view: each anchored file mapped to the git blob hash of the content its anchors point at (computed with `git hash-object`, nothing written to the repository). Later validation diffs each file against that blob: an anchor on a line that only moved follows it (in memory; `--fix` and generation write the new numbers) and passes, while changed code fails as source drift, grouped per changed hunk with the old and new lines, the anchored elements and the text that names what changed. Drift is reported when (1) an anchored line was rewritten, with any text still stating a number the rewrite changed; (2) a removed call leaves a method with no caller in the repository, naming the anchors inside it and the text that names what only it used; (3) added code that mentions an anchored symbol or calls a receiver named like an anchored file sits on no anchor; (4) an identifier gone from the anchored files is still written in the graph. `validate --fix --repo-root` realigns every anchor, renews `meta.sourceFiles` and appends one `meta.sourceDrift` item per change to each view it touches (`file`, `line`, `change`, `elements` — the ids in that view the change touches —, `removed`, `added`, `anchors`, `mentions`); validation fails while any item remains, so the author updates the named elements and deletes each item. Generation does not fail on listed items: it exempts their elements from the line check and the Viewer marks them (a dashed outline on nodes, an outlined edge label) and lists the items beside the key points; drift not yet listed still fails generation. `validate --changes --repo-root` writes the listed and newly detected changes as Markdown for a pull request comment: per view, the readable names of the touched elements, `file:line`, the change and the old and new code; the exit code is unchanged. A baseline blob missing from the repository (a shallow CI clone: use `fetch-depth: 0`) is reported and that file falls back to the working-tree check above; graphs without `meta.sourceFiles` keep that check unchanged. The rules are C-family text heuristics, not a parser: a call split across lines or an overloaded name can be missed. - To emphasize the business center, use the existing `business` kind where supported, or include `core` or `business` in `tags` (matched case-insensitively). Keep the diagram's legal node kind; `core` is not a new kind or schema field. In a state diagram the `core` state is the goal and a `failure` tag marks a failed state; both only feed the Viewer's derived state colors. - Composition review (`reviewComposition()` in `graph-validation.js`, printed in full by `validate-graph.mjs --input-only` as `Composition warning () : …`, counted as `warnings: n` in every receipt) is advisory: warnings never fail validation or generation, and a collection with no `module` anywhere gets none. Rules: `module.missing` (an ordinary node without `module` once the collection uses modules; `initial` / `final` and the outsider kinds `external`, `actor`, `device` are exempt), `module.inconsistent` (the same node label carries a module in one view and none or another in a second view), `module.single-tone` (a flowchart or data flow of ≥ 6 washed nodes all in one module — a prompt to check, legitimate when the flow lives in one subsystem), `flowchart.process-branch` (a non-decision with more than one outgoing edge), `edge.site-missing` (an edge that needs a `site` while at least one other edge of the same graph records one; a graph with no site anywhere stays quiet). One rule needs the laid-out graph: `view.oversized` (`overviewWarnings()`, printed by `generate-viewer.mjs` once and only counted by output validation) fires when a view's bounds need more than `MAX_SCREENS` (4) reading rectangles of `OVERVIEW_AREA` (1392×688, a 1440×900 window with both panels closed) at `READABLE_ZOOM` (.75); a graph without positions reports nothing. The receipt carries `warnings: ` only when there are any. - The cool-neutral visual system is a Viewer presentation rule. Color, typography, and core styling require no new graph fields. The order-fulfillment preview model is example content, not a default dataset or evidence source. diff --git a/skills/q-flow/scripts/generate-viewer.mjs b/skills/q-flow/scripts/generate-viewer.mjs index 7b6ebf4..749b7f2 100644 --- a/skills/q-flow/scripts/generate-viewer.mjs +++ b/skills/q-flow/scripts/generate-viewer.mjs @@ -86,7 +86,9 @@ async function main() { if (selected.size && values.layout !== 'auto') throw new Error('--view requires --layout auto'); const unknown = [...selected].filter(id => !views.some(graph => viewIdOf(graph) === id)); if (unknown.length) throw new Error(`Unknown view: ${unknown.join(', ')}; available views: ${views.map(viewIdOf).join(', ')}`); - const sourceEvidence = verifySourceEvidence(input, values['repo-root']); + const sourceEvidence = verifySourceEvidence(input, values['repo-root'], { pendingDrift: 'show' }); + const pendingDrift = views.reduce((sum, graph) => sum + (Array.isArray(graph.meta?.sourceDrift) ? graph.meta.sourceDrift.length : 0), 0); + if (pendingDrift) console.warn(`${pendingDrift} source change${pendingDrift === 1 ? '' : 's'} listed in meta.sourceDrift: the Viewer marks the named elements; validation fails until each item is resolved and deleted.`); const warnings = printCompositionReview(input, { print: false }); // already printed by the input validation step if (!fs.existsSync(shellPath)) throw new Error(`Viewer shell missing: ${shellPath}`); @@ -125,6 +127,7 @@ async function main() { // Preserve repairs are reported so the author can see which routes or rows changed without rendering the page. const repaired = compiled.flatMap((item, i) => item.report?.repair ? [{ view: viewIdOf(views[i]) ?? i, ...(item.report.repair.rows ? { rows: true } : { rerouted: item.report.repair.rerouted, moved: item.report.repair.movedNodeIds }) }] : []); if (repaired.length) summary.repaired = repaired; + if (pendingDrift) summary.sourceDrift = pendingDrift; const detail = values.verbose ? { layoutComposition: graphs.map(layoutComposition), layout: compiled.map(item => item.report), quality } : {}; console.log(JSON.stringify(graphs.length === 1 && !Object.hasOwn(graph, 'diagrams') ? { generated: true, diagramType: diagramTypeOf(graphs[0]), outputDir, files, ...summary, ...detail, sourceEvidence } diff --git a/skills/q-flow/scripts/source-drift.mjs b/skills/q-flow/scripts/source-drift.mjs index 5b77067..4d73c78 100644 --- a/skills/q-flow/scripts/source-drift.mjs +++ b/skills/q-flow/scripts/source-drift.mjs @@ -65,18 +65,19 @@ function fileDiff(repoRoot, blob, file) { } finally { fs.rmSync(dir, { recursive: true, force: true }); } } -// Every human-readable string of a view with the element that carries it; anchors and geometry are skipped. -function textsOf(graph, view) { +// Every human-readable string of a view with the element that carries it (id null for view-level text); anchors and +// geometry are skipped. +function textsOf(graph, view, graphIndex) { const texts = []; - const walk = (value, element, key) => { - if (Array.isArray(value)) return value.forEach(item => walk(item, element, key)); + const walk = (value, element, id, key) => { + if (Array.isArray(value)) return value.forEach(item => walk(item, element, id, key)); if (value && typeof value === 'object') { if (isAnchor(value)) return; - const here = typeof value.id === 'string' ? `${view} ${value.id}` : element; - for (const [name, item] of Object.entries(value)) if (!SKIP.has(name)) walk(item, here, name); - } else if (typeof value === 'string' && /\p{L}/u.test(value)) texts.push({ element, key, text: value }); + const own = typeof value.id === 'string' ? value.id : id; + for (const [name, item] of Object.entries(value)) if (!SKIP.has(name)) walk(item, own === id ? element : `${view} ${own}`, own, name); + } else if (typeof value === 'string' && /\p{L}/u.test(value)) texts.push({ element, key, text: value, graphIndex, id }); }; - walk(graph, `${view} meta`, ''); + walk(graph, `${view} meta`, null, ''); return texts; } @@ -112,7 +113,7 @@ export function detectDrift(graphs, { repoRoot, anchors, read, term }) { return diffs.get(key); }; const views = graphs.map((graph, i) => graph?.meta?.viewId ?? graph?.meta?.diagramType ?? `view ${i + 1}`); - const texts = graphs.flatMap((graph, i) => textsOf(graph, views[i])); + const texts = graphs.flatMap((graph, i) => textsOf(graph, views[i], i)); const scope = [...new Set(anchors.map(({ source }) => source.file))]; const scopeText = new Map(), scopeOf = file => { if (!scopeText.has(file)) { try { scopeText.set(file, read(file).join('\n')); } catch { scopeText.set(file, ''); } } return scopeText.get(file); }; const terms = new Set(anchors.map(({ source }) => term(source.symbol ?? '')).filter(name => name && (name.length >= 6 || /[A-Z_]/.test(name.slice(1))))); @@ -120,10 +121,10 @@ export function detectDrift(graphs, { repoRoot, anchors, read, term }) { const alarms = new Map(), moves = new Map(), held = new Map(), reported = new Set(); const alarm = (file, hunk, kind) => { const key = `${file}#${hunk.oldStart}`; - if (!alarms.has(key)) alarms.set(key, { file, oldLine: hunk.oldStart, newLine: hunk.newStart, kinds: new Set(), removed: hunk.removed.filter(isCode).map(line => line.trim()), added: hunk.added.filter(isCode).map(line => line.trim()), anchors: new Set(), mentions: new Set() }); + if (!alarms.has(key)) alarms.set(key, { file, oldLine: hunk.oldStart, newLine: hunk.newStart, kinds: new Set(), removed: hunk.removed.filter(isCode).map(line => line.trim()), added: hunk.added.filter(isCode).map(line => line.trim()), anchors: new Set(), mentions: new Set(), refs: new Set() }); const item = alarms.get(key); item.kinds.add(kind); return item; }; - const mention = (item, test) => { for (const t of texts) if (test(t.text) && !reported.has(t)) { reported.add(t); item.mentions.add(`${t.element}${t.key ? ` ${t.key}` : ''}: "${[...t.text].slice(0, 80).join('')}"`); } }; + const mention = (item, test) => { for (const t of texts) if (test(t.text) && !reported.has(t)) { reported.add(t); if (t.id !== null) item.refs.add(`${t.graphIndex}:${t.id}`); item.mentions.add(`${t.element}${t.key ? ` ${t.key}` : ''}: "${[...t.text].slice(0, 80).join('')}"`); } }; let realigned = 0; // Rules 1-2: carry every anchor to its new lines; an anchor whose own line was rewritten is a change to report. @@ -135,7 +136,7 @@ export function detectDrift(graphs, { repoRoot, anchors, read, term }) { const rewritten = !container && Array.from({ length: end - source.lineStart + 1 }, (_, i) => mapLine(diff.hunks, source.lineStart + i)).find(result => result.hunk); if (rewritten) { const { hunk } = rewritten, item = alarm(source.file, hunk, 'anchored line rewritten'); - item.anchors.add(`${anchor.element}${source.symbol ? ` (${source.symbol})` : ''}`); + item.anchors.add(`${anchor.element}${source.symbol ? ` (${source.symbol})` : ''}`); item.refs.add(`${anchor.graphIndex}:${anchor.id}`); const added = hunk.added.join('\n'); for (const value of new Set(hunk.removed.join('\n').match(/(? numberIn(value).test(text)); const lineStart = Math.max(1, hunk.newStart + Math.min(source.lineStart - hunk.oldStart, Math.max(0, hunk.newCount - 1))); @@ -167,7 +168,7 @@ export function detectDrift(graphs, { repoRoot, anchors, read, term }) { const item = alarm(file, hunk, `call removed: ${name}() has no remaining caller`); for (const other of based) if (other.source.file === file && (other.source.lineEnd ?? other.source.lineStart) - other.source.lineStart <= 3) { const line = moves.get(other.source)?.lineStart; - if (line >= span[0] && line <= span[1]) item.anchors.add(`${other.element}${other.source.symbol ? ` (${other.source.symbol})` : ''}`); + if (line >= span[0] && line <= span[1]) { item.anchors.add(`${other.element}${other.source.symbol ? ` (${other.source.symbol})` : ''}`); item.refs.add(`${other.graphIndex}:${other.id}`); } } // Names only this method uses (outside it and the imports they never appear) describe what it did. const body = lines.slice(span[0] - 1, span[1]).join('\n'); @@ -194,7 +195,7 @@ export function detectDrift(graphs, { repoRoot, anchors, read, term }) { } } const list = [...alarms.values()].filter(item => item.anchors.size || item.mentions.size || [...item.kinds].some(kind => kind.startsWith('new code') || kind.startsWith('call removed'))) - .map(item => ({ ...item, kinds: [...item.kinds], anchors: [...item.anchors], mentions: [...item.mentions] })); + .map(item => ({ ...item, kinds: [...item.kinds], anchors: [...item.anchors], mentions: [...item.mentions], refs: [...item.refs] })); return { files: new Set(based.map(({ source }) => source.file)).size, realigned, alarms: list, moves, unchecked: [...unchecked] }; } @@ -206,9 +207,14 @@ export function formatDrift(alarms) { ].join('\n')).join('\n'); } -// The compact form kept in meta.sourceDrift until the author has updated the listed elements. -export const driftItems = alarms => alarms.map(item => ({ +// Alarms touching view graphIndex: they name one of its elements or change a file it anchors. +export const viewAlarms = (alarms, graphIndex, files) => alarms.filter(item => item.refs.some(ref => ref.startsWith(`${graphIndex}:`)) || files.has(item.file)); + +// The compact form kept in meta.sourceDrift until the author has updated the listed elements; `elements` holds the ids +// in view graphIndex that the change touches (anchored there or whose text names what changed). +export const driftItems = (alarms, graphIndex) => alarms.map(item => ({ file: item.file, line: item.newLine, change: item.kinds.join('; '), + elements: [...new Set(item.refs.filter(ref => ref.startsWith(`${graphIndex}:`)).map(ref => ref.slice(ref.indexOf(':') + 1)))], ...(item.removed.length ? { removed: item.removed.slice(0, 6) } : {}), ...(item.added.length ? { added: item.added.slice(0, 6) } : {}), ...(item.anchors.length ? { anchors: item.anchors } : {}), ...(item.mentions.length ? { mentions: item.mentions } : {}) })); diff --git a/skills/q-flow/scripts/source-drift.test.mjs b/skills/q-flow/scripts/source-drift.test.mjs index c1aa645..2e9997a 100644 --- a/skills/q-flow/scripts/source-drift.test.mjs +++ b/skills/q-flow/scripts/source-drift.test.mjs @@ -6,7 +6,8 @@ import path from 'node:path'; import test from 'node:test'; import { collection, repoRoot, source } from '../../../tests/jeepay.mjs'; import { mapLine, parseHunks } from './source-drift.mjs'; -import { fixGraphFile, stampSourceFiles, verifySourceEvidence } from './validate-graph.mjs'; +import { changesReport, fixGraphFile, stampSourceFiles, verifySourceEvidence } from './validate-graph.mjs'; +import { driftedElements } from '../assets/viewer/src/source-changes.js'; const git = (dir, ...args) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8' }); @@ -94,10 +95,17 @@ test('--fix realigns, renews the baseline and keeps the change as a worklist unt const fixed = JSON.parse(fs.readFileSync(file, 'utf8')), sequence = view(fixed, 'sequence'); assert.equal(sequence.edges.find(edge => edge.id === 'm3').site.lineStart, anchor.lineStart + 1); assert.equal(sequence.meta.sourceDrift[0].file, anchor.file); + assert.ok(sequence.meta.sourceDrift[0].elements.includes('m3'), 'the worklist names the element ids it touches'); + assert.ok(driftedElements(sequence).has('m3'), 'the Viewer marks the named elements'); assert.equal(sequence.meta.sourceFiles[anchor.file], git(dir, 'hash-object', anchor.file).trim()); assert.throws(() => verifySourceEvidence(fixed, dir), /Unresolved source drift/); + assert.equal(verifySourceEvidence(structuredClone(fixed), dir, { pendingDrift: 'show' }).status, 'passed', 'generation shows listed items instead of failing'); + const pending = structuredClone(fixed); for (const item of fixed.diagrams) delete item.meta.sourceDrift; assert.equal(verifySourceEvidence(fixed, dir).status, 'passed'); + const other = site(pending, 'sequence', 'm1'); + editLine(dir, other.file, other.lineStart, line => `${line} // changed`); + assert.throws(() => verifySourceEvidence(pending, dir, { pendingDrift: 'show' }), /Source drift: 1 change/, 'an unlisted change still fails generation'); }); test('graphs without a baseline keep the working-tree check unchanged', t => { @@ -114,3 +122,15 @@ test('a baseline missing from the repository falls back to the working-tree chec assert.equal(verifySourceEvidence(graph, dir).status, 'passed'); assert.ok(warn.mock.calls.some(call => /fetch-depth: 0/.test(call.arguments[0]))); }); + +test('--changes reports each change with the readable elements it touches, or that nothing changed', t => { + const { dir, graph } = baseline(t), anchor = site(graph, 'sequence', 'm3'), sequence = view(graph, 'sequence'); + assert.match(changesReport(graph, dir), /^No source changes affect /); + editLine(dir, anchor.file, anchor.lineStart, line => line.replace('payOrderService.save(', 'payOrderService.saveOrder(')); + const edge = sequence.edges.find(item => item.id === 'm3'), label = id => sequence.nodes.find(node => node.id === id).label; + const report = changesReport(graph, dir); + assert.match(report, /^## Source changes affecting /); + assert.ok(report.includes(`\`${anchor.file}:${anchor.lineStart}\``), report); + assert.ok(report.includes(`${label(edge.source)} → ${label(edge.target)}`), report); + assert.ok(report.includes('+ payOrderService.saveOrder(payOrder);'), report); +}); diff --git a/skills/q-flow/scripts/validate-graph.mjs b/skills/q-flow/scripts/validate-graph.mjs index 506626a..3099806 100644 --- a/skills/q-flow/scripts/validate-graph.mjs +++ b/skills/q-flow/scripts/validate-graph.mjs @@ -12,7 +12,7 @@ import { graphsOf, needsSite, overviewWarnings, reviewComposition, validateGraph import { requireDiagramQuality, qualityFailure } from '../assets/viewer/src/layout-quality.js'; import { operandScopes } from '../assets/viewer/src/sequence-fragments.js'; import { callsMissingExecutions } from '../assets/viewer/src/sequence-executions.js'; -import { detectDrift, driftItems, fingerprintFiles, formatDrift } from './source-drift.mjs'; +import { detectDrift, driftItems, fingerprintFiles, formatDrift, viewAlarms } from './source-drift.mjs'; export { DIAGRAM_TYPES, diagramTypeOf } from '../assets/viewer/src/diagrams/registry.js'; export { graphsOf, reviewComposition, validateGraph, validateGraphInput } from '../assets/viewer/src/graph-validation.js'; @@ -24,6 +24,9 @@ const USAGE = `Usage: node validate-graph.mjs [options] unambiguous replyTo, the callee activation bar of each answered sync call; with --repo-root, anchors follow moved lines, source drift is listed in meta.sourceDrift and meta.sourceFiles is renewed); prints each change; writes back only when the graph then passes + --changes with --repo-root, write the source changes that touch the diagram as Markdown for a pull request + comment (per view: the elements, file:line, the change, the old and new code); the exit code is + unchanged, so validation still fails while they remain --verbose print the full receipt (layout composition, diagnostics) instead of one summary line -h, --help this text Success prints one JSON line; failure prints the failing elements with rule, measurement and remediation. @@ -168,10 +171,10 @@ export function sourceAnchors(input) { return graphsOf(input).flatMap((graph, graphIndex) => { const view = graph?.meta?.viewId ?? graph?.meta?.diagramType ?? `view ${graphIndex + 1}`; return [ - ...overviewSections(graph).flatMap(section => section.source ? [{ source: section.source, label: `diagrams[${graphIndex}].sections.${section.id}.source`, graphIndex, element: `${view} ${section.id}` }] : []), - ...graph.nodes.flatMap((node, nodeIndex) => (node.badges ?? []).flatMap((badge, i) => badge.source ? [{ source: badge.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].badges[${i}].source`, graphIndex, element: `${view} ${node.id} badge` }] : [])), - ...graph.nodes.flatMap((node, nodeIndex) => node.source ? [{ source: node.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].source`, graphIndex, element: `${view} ${node.id}` }] : []), - ...(graph.edges ?? []).flatMap((edge, edgeIndex) => edge.site ? [{ source: edge.site, label: `diagrams[${graphIndex}].edges[${edgeIndex}].site`, graphIndex, element: `${view} ${edge.id}` }] : [])]; + ...overviewSections(graph).flatMap(section => section.source ? [{ source: section.source, label: `diagrams[${graphIndex}].sections.${section.id}.source`, graphIndex, id: section.id, element: `${view} ${section.id}` }] : []), + ...graph.nodes.flatMap((node, nodeIndex) => (node.badges ?? []).flatMap((badge, i) => badge.source ? [{ source: badge.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].badges[${i}].source`, graphIndex, id: node.id, element: `${view} ${node.id} badge` }] : [])), + ...graph.nodes.flatMap((node, nodeIndex) => node.source ? [{ source: node.source, label: `diagrams[${graphIndex}].nodes[${nodeIndex}].source`, graphIndex, id: node.id, element: `${view} ${node.id}` }] : []), + ...(graph.edges ?? []).flatMap((edge, edgeIndex) => edge.site ? [{ source: edge.site, label: `diagrams[${graphIndex}].edges[${edgeIndex}].site`, graphIndex, id: edge.id, element: `${view} ${edge.id}` }] : [])]; }); } @@ -210,11 +213,9 @@ export function applyAnchorFixes(input, repoRoot) { for (const item of drift.alarms) for (const anchor of all) if (item.anchors.some(text => text === anchor.element || text.startsWith(`${anchor.element} (`))) exempt.add(anchor.label); if (drift.alarms.length) { // Each view keeps the items that name one of its elements, or that touch a file it anchors. - const items = driftItems(drift.alarms); graphs.forEach((graph, graphIndex) => { - const view = graph.meta.viewId ?? graph.meta.diagramType ?? `view ${graphIndex + 1}`; const files = new Set(all.filter(anchor => anchor.graphIndex === graphIndex).map(({ source }) => source.file)); - const own = items.filter(item => [...(item.anchors ?? []), ...(item.mentions ?? [])].some(text => text.startsWith(`${view} `)) || files.has(item.file)); + const own = driftItems(viewAlarms(drift.alarms, graphIndex, files), graphIndex); if (!own.length) return; graph.meta.sourceDrift = [...(graph.meta.sourceDrift ?? []), ...own]; changes.push(`${Object.hasOwn(input, 'diagrams') ? `diagrams[${graphIndex}].` : ''}meta.sourceDrift + ${own.length} item${own.length === 1 ? '' : 's'}`); @@ -241,6 +242,31 @@ export function applyAnchorFixes(input, repoRoot) { return { changes, blocked, drift: drift?.alarms ?? [], exempt }; } +// Markdown for a pull request comment: per view, every listed (meta.sourceDrift) or newly detected source change with +// the readable names of the elements it touches, file:line, the change and the old and new code. +export function changesReport(input, repoRoot) { + const graphs = graphsOf(input), anchors = sourceAnchors(input), { read } = sourceReader(repoRoot); + const live = detectDrift(graphs, { repoRoot, anchors, read, term: symbolTerm })?.alarms ?? []; + const title = input.meta?.title ?? graphs[0]?.meta?.title ?? 'diagram'; + const sections = graphs.flatMap((graph, graphIndex) => { + const files = new Set(anchors.filter(anchor => anchor.graphIndex === graphIndex).map(({ source }) => source.file)); + const items = [...(Array.isArray(graph.meta?.sourceDrift) ? graph.meta.sourceDrift : []), ...driftItems(viewAlarms(live, graphIndex, files), graphIndex)]; + if (!items.length) return []; + const nodes = new Map(graph.nodes.map(node => [node.id, node])); + const name = id => { + const edge = (graph.edges ?? []).find(item => item.id === id); + if (edge) return `${nodes.get(edge.source)?.label ?? edge.source} → ${nodes.get(edge.target)?.label ?? edge.target}${edge.label ? `: ${edge.label}` : ''}`; + return nodes.get(id)?.label ?? (graph.groups ?? []).find(group => group.id === id)?.label ?? overviewSections(graph).find(section => section.id === id)?.label ?? id; + }; + const tick = text => `\`${String(text).replaceAll('`', "'").replace(/\s+/g, ' ')}\``; + return [`### ${graph.meta.title ?? graph.meta.viewId ?? diagramTypeOf(graph)}${graph.meta.viewId ? ` (${tick(graph.meta.viewId)})` : ''}`, '', + ...items.flatMap(item => [`- **${tick(`${item.file}:${item.line}`)}** ${item.change}`, + ...(item.elements?.length ? [` - Elements: ${item.elements.map(id => tick(name(id))).join(', ')}`] : []), + ...(item.removed?.length || item.added?.length ? [' ```diff', ...(item.removed ?? []).map(line => ` - ${line}`), ...(item.added ?? []).map(line => ` + ${line}`), ' ```'] : [])]), '']; + }); + return sections.length ? [`## Source changes affecting ${title}`, '', ...sections].join('\n') : `No source changes affect ${title}.\n`; +} + // ponytail: a whole-word text match on the symbol's last segment, not a definition parser. A mention left inside the // range (a comment, a call) still passes after the definition moved; add per-language definition rules if that bites. const symbolTerm = symbol => symbol.split(/[^\p{L}\p{N}_$]+/u).filter(Boolean).at(-1); @@ -280,6 +306,8 @@ function sourceReader(repoRoot) { // `relations` counts the edges that should record a site, so a delivery can say how much of the diagram is traceable. // With meta.sourceFiles, anchors first follow the lines they moved with (in memory; generation writes them out) and // changed code fails as source drift; unresolved meta.sourceDrift items fail until the author removes them. +// pendingDrift: 'fail' (validation), 'show' (generation: listed items pass and their elements skip the line check, so the +// Viewer can mark them; unlisted drift still fails) or 'allow' (--fix, which lists the drift itself). export function verifySourceEvidence(input, repoRoot, { pendingDrift = 'fail', exempt = new Set() } = {}) { const graphs = graphsOf(input), edges = graphs.flatMap(graph => graph.edges ?? []); const anchors = sourceAnchors(input); @@ -292,7 +320,8 @@ export function verifySourceEvidence(input, repoRoot, { pendingDrift = 'fail', e return { ...summary, status: anchors.length ? 'skipped' : 'not-applicable', ...(anchors.length ? { reason: 'repository-root-not-provided' } : {}) }; } const { read, files } = sourceReader(repoRoot), errors = []; - const drift = pendingDrift === 'fail' ? detectDrift(graphs, { repoRoot, anchors, read, term: symbolTerm }) : null; + const drift = pendingDrift === 'allow' ? null : detectDrift(graphs, { repoRoot, anchors, read, term: symbolTerm }); + const listed = pendingDrift === 'show' ? new Set(anchors.filter(({ graphIndex, id }) => (graphs[graphIndex].meta?.sourceDrift ?? []).some(item => item?.elements?.includes(id))).map(({ label }) => label)) : new Set(); if (drift) { for (const file of drift.unchecked) console.warn(`Source drift not checked for ${file}: its baseline is not in this repository (fetch full history, e.g. actions/checkout fetch-depth: 0); checking the working tree only.`); if (drift.alarms.length) throw new Error(`Source drift: ${drift.alarms.length} change${drift.alarms.length === 1 ? '' : 's'} since this diagram's meta.sourceFiles baseline${drift.realigned ? ` (${drift.realigned} anchors only moved and follow their lines)` : ''}. Run validate --fix --repo-root to realign and list them in meta.sourceDrift, then update the named elements.\n${formatDrift(drift.alarms)}`); @@ -300,7 +329,7 @@ export function verifySourceEvidence(input, repoRoot, { pendingDrift = 'fail', e } let symbols = 0; for (const { source, label } of anchors) { - if (exempt.has(label)) continue; + if (exempt.has(label) || listed.has(label)) continue; try { const lines = read(source.file), end = source.lineEnd ?? source.lineStart; if (end > lines.length) throw new Error(`line ${end} exceeds file length (${lines.length} lines)`); @@ -321,7 +350,7 @@ export function verifySourceEvidence(input, repoRoot, { pendingDrift = 'fail', e if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) { try { - const { positionals, values } = parseArgs({ allowPositionals: true, options: { 'repo-root': { type: 'string' }, 'input-only': { type: 'boolean', default: false }, fix: { type: 'boolean', default: false }, verbose: { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h', default: false } } }); + const { positionals, values } = parseArgs({ allowPositionals: true, options: { 'repo-root': { type: 'string' }, changes: { type: 'string' }, 'input-only': { type: 'boolean', default: false }, fix: { type: 'boolean', default: false }, verbose: { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h', default: false } } }); if (values.help) { console.log(USAGE); process.exit(0); } if (positionals.length !== 1) throw new Error(USAGE); if (values.fix) { @@ -337,6 +366,11 @@ if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process console.error(`regenerate the page and SVGs: node "${path.join(import.meta.dirname, 'generate-viewer.mjs')}" "${file}" "${directory}" --layout preserve --force${values['repo-root'] === undefined ? '' : ` --repo-root "${path.resolve(values['repo-root'])}"`}`); } } + if (values.changes !== undefined) { + if (values['repo-root'] === undefined) throw new Error('--changes needs --repo-root'); + fs.writeFileSync(values.changes, changesReport(JSON.parse(fs.readFileSync(positionals[0], 'utf8')), values['repo-root'])); + console.error(`wrote ${path.resolve(values.changes)}`); + } const graph = readAndValidateGraph(positionals[0], { inputOnly: values['input-only'] }); const sourceEvidence = verifySourceEvidence(graph, values['repo-root']); const warnings = [...printCompositionReview(graph, { print: values['input-only'] }), ...(values['input-only'] ? [] : printViewReview(graph))]; From 4d48445a9320a6e342df78acc6e21fa5664709cd Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 12:42:51 +0800 Subject: [PATCH 08/16] =?UTF-8?q?feat(drift):=20=E6=9C=AA=E9=94=9A?= =?UTF-8?q?=E5=AE=9A=E6=96=87=E4=BB=B6=E7=9A=84=E6=94=B9=E5=8A=A8=E4=B9=9F?= =?UTF-8?q?=E8=83=BD=E6=A0=87=E5=88=B0=E5=9B=BE=E4=B8=8A=EF=BC=9Bgenerate?= =?UTF-8?q?=20--compare=20=E6=A0=87=E5=87=BA=E5=9B=BE=E7=9A=84=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E3=80=81=E6=94=B9=E5=8A=A8=E4=B8=8E=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + docs/readme/README.de.md | 2 + docs/readme/README.es.md | 2 + docs/readme/README.ja.md | 2 + docs/readme/README.pt.md | 2 + docs/readme/README.ru.md | 2 + docs/readme/README.zh-CN.md | 2 + package.json | 1 + skills/q-flow/SKILL.md | 8 +-- skills/q-flow/assets/viewer-dist/index.html | 16 ++--- .../assets/viewer/src/DiagramCanvas.jsx | 19 +++-- .../q-flow/assets/viewer/src/ViewerShell.jsx | 25 +++++-- skills/q-flow/assets/viewer/src/graph-diff.js | 39 ++++++++++ .../assets/viewer/src/i18n-messages.json | 72 ++++++++++++++++--- skills/q-flow/assets/viewer/src/main.jsx | 2 + .../q-flow/assets/viewer/src/session-graph.js | 10 +++ skills/q-flow/assets/viewer/src/styles.css | 14 ++++ skills/q-flow/references/graph-schema.md | 3 +- skills/q-flow/scripts/generate-viewer.mjs | 28 +++++++- skills/q-flow/scripts/graph-diff.test.mjs | 46 ++++++++++++ skills/q-flow/scripts/source-drift.mjs | 51 ++++++++++++- skills/q-flow/scripts/source-drift.test.mjs | 20 ++++++ skills/q-flow/scripts/validate-graph.mjs | 15 ++-- 23 files changed, 335 insertions(+), 48 deletions(-) create mode 100644 skills/q-flow/assets/viewer/src/graph-diff.js create mode 100644 skills/q-flow/scripts/graph-diff.test.mjs diff --git a/README.md b/README.md index 3a7fe03..9fc816e 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow CI says docs/qgraphflow/order-sequence is out of date. Refres The skill realigns every anchor, lists each change in the graph's `meta.sourceDrift`, updates only the elements those items name and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. +Add `--compare HEAD` when regenerating to see what a refresh changed: the page colors added and changed elements, lists removed ones beside the key points, and leaves `graph.json` untouched. + ## What each of the eleven diagram types answers | View · PNG | Main question | Example scope | diff --git a/docs/readme/README.de.md b/docs/readme/README.de.md index 8c42ff5..3c905bc 100644 --- a/docs/readme/README.de.md +++ b/docs/readme/README.de.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow Laut CI ist docs/qgraphflow/order-sequence veraltet. Bitte ak Der Skill richtet alle Anker am aktuellen Code aus, listet jede Änderung in `meta.sourceDrift` des Graphen, aktualisiert nur die dort genannten Elemente und erzeugt Seite und SVGs neu, wobei bearbeitete Positionen und Texte erhalten bleiben. Er zeichnet das Diagramm nicht neu. +Mit `--compare HEAD` beim Neuerzeugen sehen Sie, was eine Aktualisierung geändert hat: Die Seite färbt hinzugefügte und geänderte Elemente, listet entfernte neben den Kernaussagen und lässt `graph.json` unverändert. + ## Welche Fragen die elf Diagrammarten beantworten | Ansicht · PNG | Hauptfrage | Umfang des Beispiels | diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index 0b564e4..6df4e71 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow La CI dice que docs/qgraphflow/order-sequence está desactual La habilidad realinea todos los anclajes, enumera cada cambio en `meta.sourceDrift` del grafo, actualiza solo lo que esas entradas señalan y vuelve a generar la página y los SVG conservando las posiciones y los textos editados. No redibuja el diagrama. +Añade `--compare HEAD` al regenerar para ver qué cambió una actualización: la página colorea los elementos añadidos y modificados, enumera los eliminados junto a los puntos clave y no toca `graph.json`. + ## Qué responde cada uno de los once tipos de diagramas | Vista · PNG | Pregunta principal | Alcance del ejemplo | diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index f6f4244..e17dd3f 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow CI で docs/qgraphflow/order-sequence の図が古いと出 スキルはすべてのアンカーを現在のコードに合わせ、各変更をグラフの `meta.sourceDrift` に列挙し、その項目が示す要素だけを更新して、編集した位置と文字を保ったままページと SVG を再生成します。図を描き直すことはしません。 +再生成時に `--compare HEAD` を付けると、今回の更新で何が変わったかが分かります。追加・変更された要素に色が付き、削除された要素は要点の横に一覧表示されます。`graph.json` は変わりません。 + ## 11 種類の図がそれぞれ答えること | ビュー · PNG | 主な問い | 本サンプルの範囲 | diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md index 58f4d48..09a7b28 100644 --- a/docs/readme/README.pt.md +++ b/docs/readme/README.pt.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow O CI diz que docs/qgraphflow/order-sequence está desatualiza A habilidade realinha todas as âncoras, lista cada mudança em `meta.sourceDrift` do grafo, atualiza apenas os elementos que esses itens indicam e gera de novo a página e os SVG, mantendo as posições e os textos que você editou. Ela não redesenha o diagrama. +Adicione `--compare HEAD` ao regenerar para ver o que uma atualização mudou: a página colore os elementos adicionados e alterados, lista os removidos ao lado dos pontos-chave e não altera `graph.json`. + ## O que cada um dos onze tipos de diagrama responde | Vista · PNG | Pergunta principal | Escopo do exemplo | diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index 66bbb94..50b41bf 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow CI сообщает, что диаграмма docs/qgraphflo Навык выравнивает все якоря по текущему коду, записывает каждое изменение в `meta.sourceDrift` графа, обновляет только названные там элементы и пересоздаёт страницу и SVG, сохраняя ваши позиции и тексты. Заново диаграмму он не рисует. +Добавьте `--compare HEAD` при повторной генерации, чтобы увидеть, что изменило обновление: страница выделяет цветом добавленные и изменённые элементы, перечисляет удалённые рядом с ключевыми выводами и не трогает `graph.json`. + ## На какие вопросы отвечает каждый из одиннадцати типов диаграмм | Вид · PNG | Главный вопрос | Область примера | diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index e4255d0..972d1c2 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -266,6 +266,8 @@ $qgraphflow:q-flow CI 提示 docs/qgraphflow/order-sequence 的图过时了, 技能会把所有锚点对齐到当前代码,把每处改动列进图的 `meta.sourceDrift`,只更新这些条目指出的元素,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 +重新生成时加上 `--compare HEAD`,就能看出这次刷新改了什么:页面把新增和改动的元素着色,在要点旁列出删掉的元素,`graph.json` 不受影响。 + ## 十一类图各自回答什么 | 视图 · PNG | 主要问题 | 本示例范围 | diff --git a/package.json b/package.json index 51f4788..d0fd3c0 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "skills/q-flow/assets/viewer/src/layout-refinement.js", "skills/q-flow/assets/viewer/src/layout-templates.js", "skills/q-flow/assets/viewer/src/presentation-graph.js", + "skills/q-flow/assets/viewer/src/graph-diff.js", "skills/q-flow/assets/viewer/src/layout-semantics.js" ], "scripts": { diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index 42f48df..ab1b190 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -59,16 +59,16 @@ Ordinary graph delivery ends with the three commands above. Run the browser chec ## Refresh an existing diagram -Read the supplied graph and collection metadata. Inherit type, scope, granularity, view count and directory. An explicit update approves `--force` for that directory; audit findings alone do not. Resolve only the requested views; ask if their identity is ambiguous. +Read the supplied graph and collection metadata. An explicit update approves `--force` for that directory; audit findings alone do not. Resolve only the requested views; ask if their identity is ambiguous. -Simplification uses verified facts in Author. Expansion returns to Evidence before Author. Preserve stable IDs; report gaps, aggregations, additions and exclusions. These changes authorize `--layout auto --force` for the requested views only. In a collection add `--view ` for each changed view; omit it only when all views need layout. Unselected views must pass preserve; never relayout them to clear a failure. Ordinary refresh preserves geometry: +Simplification uses verified facts in Author. Expansion returns to Evidence before Author. Preserve stable IDs; report gaps, aggregations, additions and exclusions. These changes authorize `--layout auto --force` for the requested views only. In a collection add `--view ` per changed view (omit only when all need layout); never relayout unselected views to clear a failure. Ordinary refresh preserves geometry: ```bash node scripts/validate-graph.mjs "/graph.json" --input-only --fix --repo-root "" -node scripts/generate-viewer.mjs "/graph.json" "" --layout preserve --force --repo-root "" +node scripts/generate-viewer.mjs "/graph.json" "" --layout preserve --force --repo-root "" --compare HEAD ``` -Between the two, work only what `--fix` left: update just the elements each `meta.sourceDrift` item names (relate uncovered new code), then delete the item; fix anchors still reported and report a symbol you cannot place. Validate the output as above. `preserve` keeps node positions and reroutes new or crowded edges; if that fails, report the nodes and ask before `--layout auto`. Regenerate a sequence view that lost messages with `--layout auto --view `; columns stay. Reply with the changed elements and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. +Between the two, work only what `--fix` left: update just the elements each `meta.sourceDrift` item names (relate uncovered new code), then delete the item; fix anchors still reported; report symbols you cannot place. Validate the output as above. `--compare HEAD` marks what changed; an uncommitted graph compares with a pre-edit copy. `preserve` keeps node positions and reroutes new or crowded edges; if that fails, report the nodes and ask before `--layout auto`. Regenerate a sequence view that lost messages with `--layout auto --view `; columns stay. Reply with the changed elements and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. ## Viewer maintenance diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index 2021b17..660129a 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -234,7 +234,7 @@ `,` +`).split(` `));return[t,t.reduce((e,t)=>e.concat(...t),[])]}return[[],[]]},[e]);return(0,y.useEffect)(()=>{let n=t?.target??qc,c=t?.actInsideInputWithModifier??!0;if(e!==null){let e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!c)&&So(e))return!1;let n=Xc(e.code,s);if(a.current.add(e[n]),Yc(o,a.current,!1)){let n=e.composedPath?.()?.[0]||e.target,a=n?.nodeName===`BUTTON`||n?.nodeName===`A`;t.preventDefault!==!1&&(i.current||!a)&&e.preventDefault(),r(!0)}},l=e=>{let t=Xc(e.code,s);Yc(o,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(e[t]),e.key===`Meta`&&a.current.clear(),i.current=!1},u=()=>{a.current.clear(),r(!1)};return n?.addEventListener(`keydown`,e),n?.addEventListener(`keyup`,l),window.addEventListener(`blur`,u),window.addEventListener(`contextmenu`,u),()=>{n?.removeEventListener(`keydown`,e),n?.removeEventListener(`keyup`,l),window.removeEventListener(`blur`,u),window.removeEventListener(`contextmenu`,u)}}},[e,r]),n}function Yc(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function Xc(e,t){return t.includes(e)?`code`:`key`}var Zc=()=>{let e=bc();return(0,y.useMemo)(()=>({zoomIn:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):!1},zoomOut:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):!1},zoomTo:async(t,n)=>{let{panZoom:r}=e.getState();return r?r.scaleTo(t,n):!1},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,i,a],panZoom:o}=e.getState();return o?(await o.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??a},n),!0):!1},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:i,minZoom:a,maxZoom:o,panZoom:s}=e.getState(),c=lo(t,r,i,a,o,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0):!1},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:i,snapToGrid:a,domNode:o}=e.getState();if(!o)return t;let{x:s,y:c}=o.getBoundingClientRect(),l={x:t.x-s,y:t.y-c},u=n.snapGrid??i;return io(l,r,n.snapToGrid??a,u)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:i,y:a}=r.getBoundingClientRect(),o=ao(t,n);return{x:o.x+i,y:o.y+a}}}),[])};function Qc(e,t){let n=[],r=new Map,i=[];for(let t of e)if(t.type===`add`){i.push(t);continue}else if(t.type===`remove`||t.type===`replace`)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if(t[0].type===`remove`)continue;if(t[0].type===`replace`){n.push({...t[0].item});continue}let i={...e};for(let e of t)$c(e,i);n.push(i)}return i.length&&i.forEach(e=>{e.index===void 0?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function $c(e,t){switch(e.type){case`select`:t.selected=e.selected;break;case`position`:e.position!==void 0&&(t.position=e.position),e.dragging!==void 0&&(t.dragging=e.dragging);break;case`dimensions`:e.dimensions!==void 0&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes===`width`)&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes===`height`)&&(t.height=e.dimensions.height))),typeof e.resizing==`boolean`&&(t.resizing=e.resizing)}}function el(e,t){return Qc(e,t)}function tl(e,t){return Qc(e,t)}function nl(e,t){return{id:e,type:`select`,selected:t}}function rl(e,t=new Set,n=!1){let r=[];for(let[i,a]of e){let e=t.has(i);!(a.selected===void 0&&!e)&&a.selected!==e&&(n&&(a.selected=e),r.push(nl(a.id,e)))}return r}function il({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,i]of e.entries()){let e=t.get(i.id),a=e?.internals?.userNode??e;a!==void 0&&a!==i&&n.push({id:i.id,item:i,type:`replace`}),a===void 0&&n.push({item:i,type:`add`,index:r})}for(let[e]of t)r.get(e)===void 0&&n.push({id:e,type:`remove`});return n}function al(e){return{id:e.id,type:`remove`}}var ol=no(`React Flow`,`https://reactflow.dev/`);function sl(e,t,n={}){return Fo(e,t,{...n,onError:n.onError??ol})}var cl=e=>Aa(e),ll=e=>ka(e);function ul(e){return(0,y.forwardRef)(e)}var dl=typeof window<`u`?y.useLayoutEffect:y.useEffect;function fl(e){let[t,n]=(0,y.useState)(BigInt(0)),[r]=(0,y.useState)(()=>pl(()=>n(e=>e+BigInt(1))));return dl(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}function pl(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var ml=(0,y.createContext)(null);function hl({children:e}){let t=bc(),n=fl((0,y.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:a,nodeLookup:o,fitViewQueued:s,onNodesChangeMiddlewareMap:c}=t.getState(),l=n;for(let t of e)l=typeof t==`function`?t(l):t;let u=il({items:l,lookup:o});for(let e of c.values())u=e(u);i&&r(l),u.length>0?a?.(u):s&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=fl((0,y.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:a,edgeLookup:o}=t.getState(),s=n;for(let t of e)s=typeof t==`function`?t(s):t;i?r(s):a&&a(il({items:s,lookup:o}))},[])),i=(0,y.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,x.jsx)(ml.Provider,{value:i,children:e})}function gl(){let e=(0,y.useContext)(ml);if(!e)throw Error(`useBatchContext must be used within a BatchProvider`);return e}var _l=e=>!!e.panZoom;function vl(){let e=Zc(),t=bc(),n=gl(),r=G(_l),i=(0,y.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},a=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),i=cl(e)?e:n.get(e.id),a=i.parentId?po(i.position,i.measured,i.parentId,n,r):i.position;return Ya({...i,position:a,width:i.measured?.width??i.width,height:i.measured?.height??i.height})},o=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&cl(e)?e:{...r,...e}}return r}))},s=(e,t,n={replace:!1})=>{i(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&ll(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,a,o]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:i,y:a,zoom:o}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:i,onNodesDelete:a,onEdgesDelete:o,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:l,onBeforeDelete:u}=t.getState(),{nodes:d,edges:f}=await Ba({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:u}),p=f.length>0,m=d.length>0;if(p){let e=f.map(al);o?.(f),c(e)}if(m){let e=d.map(al);a?.(d),s(e)}return(m||p)&&l?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let i=eo(e),o=i?e:a(e),s=r!==void 0;return o?(r||t.getState().nodes).filter(r=>{let a=t.getState().nodeLookup.get(r.id);if(a&&!i&&(r.id===e.id||!a.internals.positionAbsolute))return!1;let c=Ya(s?r:a),l=$a(c,o);return n&&l>0||l>=c.width*c.height||l>=o.width*o.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=eo(e)?e:a(e);if(!r)return!1;let i=$a(r,t);return n&&i>0||i>=t.width*t.height||i>=r.width*r.height},updateNode:o,updateNodeData:(e,t,n={replace:!1})=>{o(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return Na(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:``}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:``}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??ho();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,y.useMemo)(()=>({...i,...e,viewportInitialized:r}),[r])}var yl=e=>e.selected,bl=typeof window<`u`?window:void 0;function xl({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=bc(),{deleteElements:r}=vl(),i=Jc(e,{actInsideInputWithModifier:!1}),a=Jc(t,{target:bl});(0,y.useEffect)(()=>{if(i){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(yl),edges:e.filter(yl)}),n.setState({nodesSelectionActive:!1})}},[i]),(0,y.useEffect)(()=>{n.setState({multiSelectionActive:a})},[a])}function Sl(e){let t=bc();(0,y.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;let n=yo(e.current);(n.height===0||n.width===0)&&t.getState().onError?.(`004`,va.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener(`resize`,n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener(`resize`,n),t&&e.current&&t.unobserve(e.current)}}},[])}var Cl={position:`absolute`,width:`100%`,height:`100%`,top:0,left:0},wl=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function Tl({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panActivationKeyPressed:i,panOnScrollSpeed:a=.5,panOnScrollMode:o=Ca.Free,zoomOnDoubleClick:s=!0,panOnDrag:c=!0,defaultViewport:l,translateExtent:u,minZoom:d,maxZoom:f,zoomActivationKeyCode:p,preventScrolling:m=!0,children:h,noWheelClassName:g,noPanClassName:_,onViewportChange:v,isControlledViewport:b,paneClickDistance:S,selectionOnDrag:C}){let w=bc(),T=(0,y.useRef)(null),{userSelectionActive:E,lib:D,connectionInProgress:O}=G(wl,hc),k=Jc(p),A=(0,y.useRef)();Sl(T);let j=(0,y.useCallback)(e=>{v?.({x:e[0],y:e[1],zoom:e[2]}),b||w.setState({transform:e})},[v,b]);return(0,y.useEffect)(()=>{if(T.current){A.current=Ws({domNode:T.current,minZoom:d,maxZoom:f,translateExtent:u,viewport:l,onDraggingChange:e=>w.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=w.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=w.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=w.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=A.current.getViewport();return w.setState({panZoom:A.current,transform:[e,t,n],domNode:T.current.closest(`.react-flow`)}),()=>{A.current?.destroy()}}},[]),(0,y.useEffect)(()=>{A.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panActivationKeyPressed:i,panOnScrollSpeed:a,panOnScrollMode:o,zoomOnDoubleClick:s,panOnDrag:c,zoomActivationKeyPressed:k,preventScrolling:m,noPanClassName:_,userSelectionActive:E,noWheelClassName:g,lib:D,onTransformChange:j,connectionInProgress:O,selectionOnDrag:C,paneClickDistance:S})},[e,t,n,r,i,a,o,s,c,k,m,_,E,g,D,j,O,C,S]),(0,x.jsx)(`div`,{className:`react-flow__renderer`,ref:T,style:Cl,children:h})}var El=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Dl(){let{userSelectionActive:e,userSelectionRect:t}=G(El,hc);return e&&t?(0,x.jsx)(`div`,{className:`react-flow__selection react-flow__container`,style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var Ol=(e,t)=>n=>{n.target===t.current&&e?.(n)},kl=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function Al({isSelecting:e,selectionKeyPressed:t,selectionMode:n=wa.Full,panOnDrag:r,autoPanOnSelection:i,paneClickDistance:a,selectionOnDrag:o,onSelectionStart:s,onSelectionEnd:c,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:d,onPaneMouseEnter:f,onPaneMouseMove:p,onPaneMouseLeave:m,children:h}){let g=(0,y.useRef)(0),_=bc(),{userSelectionActive:v,elementsSelectable:b,dragging:C,panBy:w,autoPanSpeed:T}=G(kl,hc),E=b&&(e||v),D=(0,y.useRef)(null),O=(0,y.useRef)(),k=(0,y.useRef)(new Set),A=(0,y.useRef)(new Set),j=(0,y.useRef)(!1),M=(0,y.useRef)(!1),N=(0,y.useRef)({x:0,y:0}),P=(0,y.useRef)(!1),ee=e=>{if(M.current||j.current||_.getState().connection.inProgress){M.current=!1,j.current=!1;return}l?.(e),_.getState().resetSelectedElements(),_.setState({nodesSelectionActive:!1})},F=e=>{if(Array.isArray(r)&&r?.includes(2)){e.preventDefault();return}u?.(e)},I=d?e=>d(e):void 0,te=e=>{M.current&&=(e.stopPropagation(),!1)},ne=n=>{if(n.pointerType===`touch`&&r!==!1&&!t)return;let{domNode:i,transform:a}=_.getState();if(O.current=i?.getBoundingClientRect(),!O.current)return;let s=n.target===D.current;if(!s&&n.target.closest(`.nokey`)||!e||!(o&&s||t)||n.button!==0||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),M.current=!1;let{x:c,y:l}=wo(n.nativeEvent,O.current),u=io({x:c,y:l},a);_.setState({userSelectionRect:{width:0,height:0,startX:u.x,startY:u.y,x:c,y:l}}),s||(n.stopPropagation(),n.preventDefault())};function L(e,t){let{userSelectionRect:r}=_.getState();if(!r)return;let{transform:i,nodeLookup:a,edgeLookup:o,connectionLookup:s,triggerNodeChanges:c,triggerEdgeChanges:l,defaultEdgeOptions:u}=_.getState(),d={x:r.startX,y:r.startY},{x:f,y:p}=ao(d,i),m={startX:d.x,startY:d.y,x:ee.id)),A.current=new Set;let v=u?.selectable??!0;for(let e of k.current){let t=s.get(e);if(t)for(let{edgeId:e}of t.values()){let t=o.get(e);t&&(t.selectable??v)&&A.current.add(e)}}mo(h,k.current)||c(rl(a,k.current,!0)),mo(g,A.current)||l(rl(o,A.current)),_.setState({userSelectionRect:m,userSelectionActive:!0,nodesSelectionActive:!1})}function R(){if(!i||!O.current)return;let[e,t]=Ga(N.current,O.current,T);w({x:e,y:t}).then(e=>{if(!M.current||!e){g.current=requestAnimationFrame(R);return}let{x:t,y:n}=N.current;L(t,n),g.current=requestAnimationFrame(R)})}let z=()=>{cancelAnimationFrame(g.current),g.current=0,P.current=!1};(0,y.useEffect)(()=>()=>z(),[]);let B=e=>{let{userSelectionRect:n,transform:r,resetSelectedElements:i}=_.getState();if(!O.current||!n)return;let{x:o,y:c}=wo(e.nativeEvent,O.current);N.current={x:o,y:c};let l=ao({x:n.startX,y:n.startY},r);if(!M.current){let n=t?0:a;if(Math.hypot(o-l.x,c-l.y)<=n)return;i(),s?.(e)}M.current=!0,P.current||=(R(),!0),L(o,c)},re=e=>{if(!E){e.target===D.current&&_.getState().connection.inProgress&&(j.current=!0);return}e.button===0&&(e.target?.releasePointerCapture?.(e.pointerId),!v&&e.target===D.current&&_.getState().userSelectionRect&&ee?.(e),_.setState({userSelectionActive:!1,userSelectionRect:null}),M.current&&(c?.(e),_.setState({nodesSelectionActive:k.current.size>0})),z())},ie=e=>{e.target?.releasePointerCapture?.(e.pointerId),z()},ae=r===!0||Array.isArray(r)&&r.includes(0);return(0,x.jsxs)(`div`,{className:S([`react-flow__pane`,{draggable:ae,dragging:C,selection:e}]),onClick:E?void 0:Ol(ee,D),onContextMenu:Ol(F,D),onWheel:Ol(I,D),onPointerEnter:E?void 0:f,onPointerMove:E?B:p,onPointerUp:re,onPointerCancel:E?ie:void 0,onPointerDownCapture:E?ne:void 0,onClickCapture:E?te:void 0,onPointerLeave:m,ref:D,style:Cl,children:[h,(0,x.jsx)(Dl,{})]})}function jl({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:o,nodeLookup:s,onError:c}=t.getState(),l=s.get(e);if(!l){c?.(`012`,va.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&o)&&(a({nodes:[l],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):i([e])}function Ml({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,nodeClickDistance:o}){let s=bc(),[c,l]=(0,y.useState)(!1),u=(0,y.useRef)();return(0,y.useEffect)(()=>{if(!t)return u.current=ys({getStoreItems:()=>s.getState(),onNodeMouseDown:t=>{jl({id:t,store:s,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}}),()=>{u.current?.destroy(),u.current=void 0}},[t,s,e]),(0,y.useEffect)(()=>{t||!e.current||!u.current||u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:a,nodeId:i,nodeClickDistance:o})},[n,r,t,a,e,i,o]),c}var Nl=e=>t=>t.selected&&(t.draggable||e&&t.draggable===void 0);function Pl(){let e=bc();return(0,y.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:a,onError:o,updateNodePositions:s,nodeLookup:c,nodeOrigin:l}=e.getState(),u=new Map,d=Nl(a),f=r?i[0]:5,p=r?i[1]:5,m=t.direction.x*f*t.factor,h=t.direction.y*p*t.factor;for(let[,e]of c){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+h};r&&(t=ro(t,i));let{position:a,positionAbsolute:s}=za({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:l,onError:o});e.position=a,e.internals.positionAbsolute=s,u.set(e.id,e)}s(u)},[])}var Fl=(0,y.createContext)(null),Il=Fl.Provider;Fl.Consumer;var Ll=()=>(0,y.useContext)(Fl),Rl=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),zl=(0,y.createContext)(null);function Bl({children:e}){let t=G(Rl,hc);return(0,x.jsx)(zl.Provider,{value:t,children:e})}function K(){let e=(0,y.useContext)(zl);if(!e)throw Error(`useHandleConfig must be used within a HandleConfigProvider`);return e}var q={connectingFrom:!1,connectingTo:!1,clickConnecting:!1,isPossibleEndHandle:!0,connectionInProcess:!1,clickConnectionInProcess:!1,valid:!1},Vl=(e,t,n)=>r=>{let{connectionClickStartHandle:i,connectionMode:a,connection:o}=r,{fromHandle:s,toHandle:c,isValid:l}=o;if(!s&&!i)return q;let u=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:u,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:a===Sa.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:u&&l}};function Hl({type:e=`source`,position:t=H.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:o,onConnect:s,children:c,className:l,onMouseDown:u,onTouchStart:d,...f},p){let m=o||null,h=e===`target`,g=bc(),_=Ll(),{connectOnClick:v,noPanClassName:y,rfId:b}=K(),{connectingFrom:C,connectingTo:w,clickConnecting:T,isPossibleEndHandle:E,connectionInProcess:D,clickConnectionInProcess:O,valid:k}=G(Vl(_,m,e),hc);_||g.getState().onError?.(`010`,va.error010());let A=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=g.getState(),i={...t,...e};if(r){let{edges:e,setEdges:t,onError:n}=g.getState();t(sl(i,e,{onError:n}))}n?.(i),s?.(i)},j=e=>{if(!_)return;let t=Co(e.nativeEvent);if(i&&(t&&e.button===0||!t)){let t=g.getState();ks.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:h,handleId:m,nodeId:_,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>g.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:A,isValidConnection:n||((...e)=>g.getState().isValidConnection?.(...e)??!0),getTransform:()=>g.getState().transform,getFromHandle:()=>g.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):d?.(e)};return(0,x.jsx)(`div`,{"data-handleid":m,"data-nodeid":_,"data-handlepos":t,"data-id":`${b}-${_}-${m}-${e}`,className:S([`react-flow__handle`,`react-flow__handle-${t}`,`nodrag`,y,l,{source:!h,target:h,connectable:r,connectablestart:i,connectableend:a,clickconnecting:T,connectingfrom:C,connectingto:w,valid:k,connectionindicator:r&&(!D||E)&&(D||O?a:i)}]),onMouseDown:j,onTouchStart:j,onClick:v?t=>{let{onClickConnectStart:r,onClickConnectEnd:a,connectionClickStartHandle:o,connectionMode:s,isValidConnection:c,lib:l,rfId:u,nodeLookup:d,connection:f}=g.getState();if(!_||!o&&!i)return;if(!o){r?.(t.nativeEvent,{nodeId:_,handleId:m,handleType:e}),g.setState({connectionClickStartHandle:{nodeId:_,type:e,id:m}});return}let p=bo(t.target),h=n||c,{connection:v,isValid:y}=ks.isValid(t.nativeEvent,{handle:{nodeId:_,id:m,type:e},connectionMode:s,fromNodeId:o.nodeId,fromHandleId:o.id||null,fromType:o.type,isValidConnection:h,flowId:u,doc:p,lib:l,nodeLookup:d});y&&v&&A(v);let b=structuredClone(f);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,a?.(t,b),g.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f,children:c})}var Ul=(0,y.memo)(ul(Hl));function Wl({data:e,isConnectable:t,sourcePosition:n=H.Bottom}){return(0,x.jsxs)(x.Fragment,{children:[e?.label,(0,x.jsx)(Ul,{type:`source`,position:n,isConnectable:t})]})}function Gl({data:e,isConnectable:t,targetPosition:n=H.Top,sourcePosition:r=H.Bottom}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{type:`target`,position:n,isConnectable:t}),e?.label,(0,x.jsx)(Ul,{type:`source`,position:r,isConnectable:t})]})}function Kl(){return null}function ql({data:e,isConnectable:t,targetPosition:n=H.Top}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{type:`target`,position:n,isConnectable:t}),e?.label]})}var Jl={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Yl={input:Wl,default:Gl,output:ql,group:Kl};function Xl(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var Zl=e=>{let{width:t,height:n,x:r,y:i}=Pa(e.nodeLookup,{filter:e=>!!e.selected});return{width:to(t)?t:null,height:to(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function Ql({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=bc(),{width:i,height:a,transformString:o,userSelectionActive:s}=G(Zl,hc),c=Pl(),l=(0,y.useRef)(null);(0,y.useEffect)(()=>{n||l.current?.focus({preventScroll:!0})},[n]);let u=!s&&i!==null&&a!==null;if(Ml({nodeRef:l,disabled:!u}),!u)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,x.jsx)(`div`,{className:S([`react-flow__nodesselection`,`react-flow__container`,t]),style:{transform:o},children:(0,x.jsx)(`div`,{ref:l,className:`react-flow__nodesselection-rect`,onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(Jl,e.key)&&(e.preventDefault(),c({direction:Jl[e.key],factor:e.shiftKey?4:1}))},style:{width:i,height:a}})})}var $l=typeof window<`u`?window:void 0,eu=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function tu({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,paneClickDistance:s,deleteKeyCode:c,selectionKeyCode:l,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:g,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:b,panOnScrollSpeed:S,panOnScrollMode:C,zoomOnDoubleClick:w,panOnDrag:T,autoPanOnSelection:E,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,preventScrolling:j,onSelectionContextMenu:M,noWheelClassName:N,noPanClassName:P,disableKeyboardA11y:ee,onViewportChange:F,isControlledViewport:I}){let{nodesSelectionActive:te,userSelectionActive:ne}=G(eu,hc),L=Jc(l,{target:$l}),R=Jc(h,{target:$l}),z=R||T,B=R||b,re=u&&z!==!0,ie=L||ne||re;return xl({deleteKeyCode:c,multiSelectionKeyCode:m}),(0,x.jsx)(Tl,{onPaneContextMenu:a,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:B,panActivationKeyPressed:R,panOnScrollSpeed:S,panOnScrollMode:C,zoomOnDoubleClick:w,panOnDrag:!L&&z,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,zoomActivationKeyCode:g,preventScrolling:j,noWheelClassName:N,noPanClassName:P,onViewportChange:F,isControlledViewport:I,paneClickDistance:s,selectionOnDrag:re,children:(0,x.jsxs)(Al,{onSelectionStart:f,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,panOnDrag:z,autoPanOnSelection:E,isSelecting:!!ie,selectionMode:d,selectionKeyPressed:L,paneClickDistance:s,selectionOnDrag:re,children:[e,te&&(0,x.jsx)(Ql,{onSelectionContextMenu:M,noPanClassName:P,disableKeyboardA11y:ee})]})})}tu.displayName=`FlowRenderer`;var nu=(0,y.memo)(tu),ru=e=>t=>e?Fa(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys());function iu(e){return G((0,y.useCallback)(ru(e),[e]),hc)}var au=e=>e.updateNodeInternals;function ou(){let e=G(au),[t]=(0,y.useState)(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute(`data-id`);n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,y.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function su({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let i=bc(),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(e.sourcePosition),c=(0,y.useRef)(e.targetPosition),l=(0,y.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,y.useEffect)(()=>{a.current&&!e.hidden&&(!u||o.current!==a.current)&&(o.current&&r?.unobserve(o.current),r?.observe(a.current),o.current=a.current)},[u,e.hidden]),(0,y.useEffect)(()=>()=>{o.current&&=(r?.unobserve(o.current),null)},[]),(0,y.useEffect)(()=>{if(a.current){let n=l.current!==t,r=s.current!==e.sourcePosition,o=c.current!==e.targetPosition;(n||r||o)&&(l.current=t,s.current=e.sourcePosition,c.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:a.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),a}function cu({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:i,onContextMenu:a,onDoubleClick:o,nodesDraggable:s,elementsSelectable:c,nodesConnectable:l,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:p,disableKeyboardA11y:m,rfId:h,nodeTypes:g,nodeClickDistance:_,onError:v}){let{node:y,internals:b,isParent:C}=G(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},hc),w=y.type||`default`,T=g?.[w]||Yl[w];T===void 0&&(v?.(`003`,va.error003(w)),w=`default`,T=g?.default||Yl.default);let E=!!(y.draggable||s&&y.draggable===void 0),D=!!(y.selectable||c&&y.selectable===void 0),O=!!(y.connectable||l&&y.connectable===void 0),k=!!(y.focusable||u&&y.focusable===void 0),A=bc(),j=fo(y),M=su({node:y,nodeType:w,hasDimensions:j,resizeObserver:d}),N=Ml({nodeRef:M,disabled:y.hidden||!E,noDragClassName:f,handleSelector:y.dragHandle,nodeId:e,isSelectable:D,nodeClickDistance:_}),P=Pl();if(y.hidden)return null;let ee=uo(y),F=Xl(y),I=D||E||t||n||r||i,te=n?e=>n(e,{...b.userNode}):void 0,ne=r?e=>r(e,{...b.userNode}):void 0,L=i?e=>i(e,{...b.userNode}):void 0,R=a?e=>a(e,{...b.userNode}):void 0,z=o?e=>o(e,{...b.userNode}):void 0,B=n=>{let{selectNodesOnDrag:r,nodeDragThreshold:i}=A.getState();D&&(!r||!E||i>0)&&jl({id:e,store:A,nodeRef:M}),t&&t(n,{...b.userNode})},re=t=>{if(!(So(t.nativeEvent)||m)){if(ba.includes(t.key)&&D){let n=t.key===`Escape`;jl({id:e,store:A,unselect:n,nodeRef:M})}else if(E&&y.selected&&Object.prototype.hasOwnProperty.call(Jl,t.key)){t.preventDefault();let{ariaLabelConfig:e}=A.getState();A.setState({ariaLiveMessage:e[`node.a11yDescription.ariaLiveMessage`]({direction:t.key.replace(`Arrow`,``).toLowerCase(),x:~~b.positionAbsolute.x,y:~~b.positionAbsolute.y})}),P({direction:Jl[t.key],factor:t.shiftKey?4:1})}}},ie=()=>{if(m||!M.current?.matches(`:focus-visible`))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:i,setCenter:a}=A.getState();i&&(Fa(new Map([[e,y]]),{x:0,y:0,width:n,height:r},t,!0).length>0||a(y.position.x+ee.width/2,y.position.y+ee.height/2,{zoom:t[2]}))};return(0,x.jsx)(`div`,{className:S([`react-flow__node`,`react-flow__node-${w}`,{[p]:E},y.className,{selected:y.selected,selectable:D,parent:C,draggable:E,dragging:N}]),ref:M,style:{zIndex:b.z,transform:`translate(${b.positionAbsolute.x}px,${b.positionAbsolute.y}px)`,pointerEvents:I?`all`:`none`,visibility:j?`visible`:`hidden`,...y.style,...F},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:te,onMouseMove:ne,onMouseLeave:L,onContextMenu:R,onClick:B,onDoubleClick:z,onKeyDown:k?re:void 0,tabIndex:k?0:void 0,onFocus:k?ie:void 0,role:y.ariaRole??(k?`group`:void 0),"aria-roledescription":`node`,"aria-describedby":m?void 0:`${Cc}-${h}`,"aria-label":y.ariaLabel,...y.domAttributes,children:(0,x.jsx)(Il,{value:e,children:(0,x.jsx)(T,{id:e,data:y.data,type:w,positionAbsoluteX:b.positionAbsolute.x,positionAbsoluteY:b.positionAbsolute.y,selected:y.selected??!1,selectable:D,draggable:E,deletable:y.deletable??!0,isConnectable:O,sourcePosition:y.sourcePosition,targetPosition:y.targetPosition,dragging:N,dragHandle:y.dragHandle,zIndex:b.z,parentId:y.parentId,...ee})})})}var lu=(0,y.memo)(cu),uu=e=>({nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function du(e){let{nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,onError:i}=G(uu,hc),a=iu(e.onlyRenderVisibleElements),o=ou();return(0,x.jsx)(`div`,{className:`react-flow__nodes`,style:Cl,children:a.map(a=>(0,x.jsx)(lu,{id:a,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:o,nodesDraggable:e.nodesDraggable??!0,nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,nodeClickDistance:e.nodeClickDistance,onError:i},a))})}du.displayName=`NodeRenderer`;var fu=(0,y.memo)(du);function pu(e){return G((0,y.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&Mo({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),hc)}var mu=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e}};return(0,x.jsx)(`polyline`,{className:`arrow`,style:n,strokeLinecap:`round`,fill:`none`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4`})},hu=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e,fill:e}};return(0,x.jsx)(`polyline`,{className:`arrowclosed`,style:n,strokeLinecap:`round`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4 -5,-4`})},gu={[Da.Arrow]:mu,[Da.ArrowClosed]:hu};function _u(e){let t=bc();return(0,y.useMemo)(()=>Object.prototype.hasOwnProperty.call(gu,e)?gu[e]:(t.getState().onError?.(`009`,va.error009(e)),null),[e])}var vu=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a=`strokeWidth`,strokeWidth:o,orient:s=`auto-start-reverse`})=>{let c=_u(t);return c?(0,x.jsx)(`marker`,{className:`react-flow__arrowhead`,id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:`-10 -10 20 20`,markerUnits:a,orient:s,refX:`0`,refY:`0`,children:(0,x.jsx)(c,{color:n,strokeWidth:o})}):null},yu=({defaultColor:e,rfId:t})=>{let n=G(e=>e.edges),r=G(e=>e.defaultEdgeOptions),i=(0,y.useMemo)(()=>Yo(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return i.length?(0,x.jsx)(`svg`,{className:`react-flow__marker`,"aria-hidden":`true`,children:(0,x.jsx)(`defs`,{children:i.map(e=>(0,x.jsx)(vu,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};yu.displayName=`MarkerDefinitions`;var bu=(0,y.memo)(yu);function xu({x:e,y:t,label:n,labelStyle:r,labelShowBg:i=!0,labelBgStyle:a,labelBgPadding:o=[2,4],labelBgBorderRadius:s=2,children:c,className:l,...u}){let[d,f]=(0,y.useState)({x:1,y:0,width:0,height:0}),p=S([`react-flow__edge-textwrapper`,l]),m=(0,y.useRef)(null);return(0,y.useEffect)(()=>{if(m.current){let e=m.current.getBBox();f({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,x.jsxs)(`g`,{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?`visible`:`hidden`,...u,children:[i&&(0,x.jsx)(`rect`,{width:d.width+2*o[0],x:-o[0],y:-o[1],height:d.height+2*o[1],className:`react-flow__edge-textbg`,style:a,rx:s,ry:s}),(0,x.jsx)(`text`,{className:`react-flow__edge-text`,y:d.height/2,dy:`0.3em`,ref:m,style:r,children:n}),c]}):null}xu.displayName=`EdgeText`;var Su=(0,y.memo)(xu);function Cu({path:e,labelX:t,labelY:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c,interactionWidth:l=20,...u}){return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{...u,d:e,fill:`none`,className:S([`react-flow__edge-path`,u.className])}),l?(0,x.jsx)(`path`,{d:e,fill:`none`,strokeOpacity:0,strokeWidth:l,className:`react-flow__edge-interaction`}):null,r&&to(t)&&to(n)?(0,x.jsx)(Su,{x:t,y:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c}):null]})}function wu({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===H.Left||e===H.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function Tu({sourceX:e,sourceY:t,sourcePosition:n=H.Bottom,targetX:r,targetY:i,targetPosition:a=H.Top}){let[o,s]=wu({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,l]=wu({pos:a,x1:r,y1:i,x2:e,y2:t}),[u,d,f,p]=Eo({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:s,targetControlX:c,targetControlY:l});return[`M${e},${t} C${o},${s} ${c},${l} ${r},${i}`,u,d,f,p]}function Eu(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o,targetPosition:s,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})=>{let[v,y,b]=Tu({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s}),S=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:S,path:v,labelX:y,labelY:b,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})})}var Du=Eu({isInternal:!1}),Ou=Eu({isInternal:!0});Du.displayName=`SimpleBezierEdge`,Ou.displayName=`SimpleBezierEdgeInternal`;function ku(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:p=H.Bottom,targetPosition:m=H.Top,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,S]=Ho({sourceX:n,sourceY:r,sourcePosition:p,targetX:i,targetY:a,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition}),C=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:C,path:y,labelX:b,labelY:S,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:g,interactionWidth:v})})}var Au=ku({isInternal:!1}),ju=ku({isInternal:!0});Au.displayName=`SmoothStepEdge`,ju.displayName=`SmoothStepEdgeInternal`;function Mu(e){return(0,y.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,x.jsx)(Au,{...n,id:r,pathOptions:(0,y.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var Nu=Mu({isInternal:!1}),Pu=Mu({isInternal:!0});Nu.displayName=`StepEdge`,Pu.displayName=`StepEdgeInternal`;function Fu(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})=>{let[g,_,v]=Io({sourceX:n,sourceY:r,targetX:i,targetY:a}),y=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:y,path:g,labelX:_,labelY:v,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})})}var Iu=Fu({isInternal:!1}),Lu=Fu({isInternal:!0});Iu.displayName=`StraightEdge`,Lu.displayName=`StraightEdgeInternal`;function Ru(e){return(0,y.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o=H.Bottom,targetPosition:s=H.Top,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,S]=ko({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s,curvature:_?.curvature}),C=e.isInternal?void 0:t;return(0,x.jsx)(Cu,{id:C,path:y,labelX:b,labelY:S,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:v})})}var zu=Ru({isInternal:!1}),Bu=Ru({isInternal:!0});zu.displayName=`BezierEdge`,Bu.displayName=`BezierEdgeInternal`;var Vu={default:Bu,straight:Lu,step:Pu,smoothstep:ju,simplebezier:Ou},Hu={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null,zIndex:void 0},Uu=(e,t,n)=>n===H.Left?e-t:n===H.Right?e+t:e,Wu=(e,t,n)=>n===H.Top?e-t:n===H.Bottom?e+t:e,Gu=`react-flow__edgeupdater`;function Ku({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:o,type:s}){return(0,x.jsx)(`circle`,{onMouseDown:i,onMouseEnter:a,onMouseOut:o,className:S([Gu,`${Gu}-${s}`]),cx:Uu(t,r,e),cy:Wu(n,r,e),r,stroke:`transparent`,fill:`transparent`})}function qu({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:i,targetX:a,targetY:o,sourcePosition:s,targetPosition:c,onReconnect:l,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:p}){let m=bc(),h=(e,t)=>{if(e.button!==0)return;let{autoPanOnConnect:r,domNode:i,connectionMode:a,connectionRadius:o,lib:s,onConnectStart:c,cancelConnection:p,nodeLookup:h,rfId:g,panBy:_,updateConnection:v}=m.getState(),y=t.type===`target`;ks.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:o,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:y,edgeUpdaterType:t.type,lib:s,flowId:g,cancelConnection:p,panBy:_,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>l?.(n,e),onConnectStart:(r,i)=>{f(!0),u?.(e,n,t.type),c?.(r,i)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=e=>h(e,{nodeId:n.target,id:n.targetHandle??null,type:`target`}),_=e=>h(e,{nodeId:n.source,id:n.sourceHandle??null,type:`source`}),v=()=>p(!0),y=()=>p(!1);return(0,x.jsxs)(x.Fragment,{children:[(e===!0||e===`source`)&&(0,x.jsx)(Ku,{position:s,centerX:r,centerY:i,radius:t,onMouseDown:g,onMouseEnter:v,onMouseOut:y,type:`source`}),(e===!0||e===`target`)&&(0,x.jsx)(Ku,{position:c,centerX:a,centerY:o,radius:t,onMouseDown:_,onMouseEnter:v,onMouseOut:y,type:`target`})]})}function Ju({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:i,onDoubleClick:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,rfId:m,edgeTypes:h,noPanClassName:g,onError:_,disableKeyboardA11y:v}){let b=G(t=>t.edgeLookup.get(e)),C=G(e=>e.defaultEdgeOptions);b=C?{...C,...b}:b;let w=b.type||`default`,T=h?.[w]||Vu[w];T===void 0&&(_?.(`011`,va.error011(w)),w=`default`,T=h?.default||Vu.default);let E=!!(b.focusable||t&&b.focusable===void 0),D=d!==void 0&&(b.reconnectable||n&&b.reconnectable===void 0),O=!!(b.selectable||r&&b.selectable===void 0),k=(0,y.useRef)(null),[A,j]=(0,y.useState)(!1),[M,N]=(0,y.useState)(!1),P=bc(),{zIndex:ee=b.zIndex,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R}=G((0,y.useCallback)(t=>{let n=t.nodeLookup.get(b.source),r=t.nodeLookup.get(b.target);if(!n||!r)return Hu;let i=Wo({id:e,sourceNode:n,targetNode:r,sourceHandle:b.sourceHandle||null,targetHandle:b.targetHandle||null,connectionMode:t.connectionMode,onError:_}),a=jo({selected:b.selected,zIndex:b.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode});return{...i||Hu,zIndex:a}},[b.source,b.target,b.sourceHandle,b.targetHandle,b.selected,b.zIndex,_]),hc),z=(0,y.useMemo)(()=>b.markerStart?`url('#${Jo(b.markerStart,m)}')`:void 0,[b.markerStart,m]),B=(0,y.useMemo)(()=>b.markerEnd?`url('#${Jo(b.markerEnd,m)}')`:void 0,[b.markerEnd,m]);if(b.hidden||F===null||I===null||te===null||ne===null)return null;let re=t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:a}=P.getState();O&&(P.setState({nodesSelectionActive:!1}),b.selected&&a?(r({nodes:[],edges:[b]}),k.current?.blur()):n([e])),i&&i(t,b)},ie=a?e=>{a(e,{...b})}:void 0,ae=o?e=>{o(e,{...b})}:void 0,oe=s?e=>{s(e,{...b})}:void 0,se=c?e=>{c(e,{...b})}:void 0,ce=l?e=>{l(e,{...b})}:void 0;return(0,x.jsx)(`svg`,{style:{zIndex:ee},children:(0,x.jsxs)(`g`,{className:S([`react-flow__edge`,`react-flow__edge-${w}`,b.className,g,{selected:b.selected,animated:b.animated,inactive:!O&&!i,updating:A,selectable:O}]),onClick:re,onDoubleClick:ie,onContextMenu:ae,onMouseEnter:oe,onMouseMove:se,onMouseLeave:ce,onKeyDown:E?t=>{if(!v&&ba.includes(t.key)&&O){let{unselectNodesAndEdges:n,addSelectedEdges:r}=P.getState();t.key===`Escape`?(k.current?.blur(),n({edges:[b]})):r([e])}}:void 0,tabIndex:E?0:void 0,role:b.ariaRole??(E?`group`:`img`),"aria-roledescription":`edge`,"data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":b.ariaLabel===null?void 0:b.ariaLabel||`Edge from ${b.source} to ${b.target}`,"aria-describedby":E?`${wc}-${m}`:void 0,ref:k,...b.domAttributes,children:[!M&&(0,x.jsx)(T,{id:e,source:b.source,target:b.target,type:b.type,selected:b.selected,animated:b.animated,selectable:O,deletable:b.deletable??!0,label:b.label,labelStyle:b.labelStyle,labelShowBg:b.labelShowBg,labelBgStyle:b.labelBgStyle,labelBgPadding:b.labelBgPadding,labelBgBorderRadius:b.labelBgBorderRadius,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R,data:b.data,style:b.style,sourceHandleId:b.sourceHandle,targetHandleId:b.targetHandle,markerStart:z,markerEnd:B,pathOptions:`pathOptions`in b?b.pathOptions:void 0,interactionWidth:b.interactionWidth}),D&&(0,x.jsx)(qu,{edge:b,isReconnectable:D,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,sourceX:F,sourceY:I,targetX:te,targetY:ne,sourcePosition:L,targetPosition:R,setUpdateHover:j,setReconnecting:N})]})})}var Yu=(0,y.memo)(Ju),Xu=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Zu({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:i,onReconnect:a,onEdgeContextMenu:o,onEdgeMouseEnter:s,onEdgeMouseMove:c,onEdgeMouseLeave:l,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:h}){let{edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,onError:y}=G(Xu,hc),b=pu(t);return(0,x.jsxs)(`div`,{className:`react-flow__edges`,children:[(0,x.jsx)(bu,{defaultColor:e,rfId:n}),b.map(e=>(0,x.jsx)(Yu,{id:e,edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,noPanClassName:i,onReconnect:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,rfId:n,onError:y,edgeTypes:r,disableKeyboardA11y:h},e))]})}Zu.displayName=`EdgeRenderer`;var Qu=(0,y.memo)(Zu),$u=e=>`translate(${e[0]}px,${e[1]}px) scale(${e[2]})`;function ed({children:e}){let t=bc(),n=(0,y.useRef)(null),[r]=(0,y.useState)(()=>t.getState().transform);return dl(()=>{let e=null,r=()=>{let r=t.getState().transform;e&&r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2]||(e=r,n.current&&(n.current.style.transform=$u(r)))};return r(),t.subscribe(r)},[t]),(0,x.jsx)(`div`,{ref:n,className:`react-flow__viewport xyflow__viewport react-flow__container`,style:{transform:$u(r)},children:e})}function td(e){let t=vl(),n=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var nd=e=>e.panZoom?.syncViewport;function rd(e){let t=G(nd),n=bc();return(0,y.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function id(e){return e.connection.inProgress?{...e.connection,to:io(e.connection.to,e.transform)}:{...e.connection}}function ad(e){return e?t=>e(id(t)):id}function od(e){return G(ad(e),hc)}var sd=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function cd({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:i,width:a,height:o,isValid:s,inProgress:c}=G(sd,hc);return a&&i&&c?(0,x.jsx)(`svg`,{style:e,width:a,height:o,className:`react-flow__connectionline react-flow__container`,children:(0,x.jsx)(`g`,{className:S([`react-flow__connection`,_o(s)]),children:(0,x.jsx)(ld,{style:t,type:n,CustomComponent:r,isValid:s})})}):null}var ld=({style:e,type:t=Ea.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:i,from:a,fromNode:o,fromHandle:s,fromPosition:c,to:l,toNode:u,toHandle:d,toPosition:f,pointer:p}=od();if(!i)return;if(n)return(0,x.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:o,fromHandle:s,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:c,toPosition:f,connectionStatus:_o(r),toNode:u,toHandle:d,pointer:p});let m=``,h={sourceX:a.x,sourceY:a.y,sourcePosition:c,targetX:l.x,targetY:l.y,targetPosition:f};switch(t){case Ea.Bezier:[m]=ko(h);break;case Ea.SimpleBezier:[m]=Tu(h);break;case Ea.Step:[m]=Ho({...h,borderRadius:0});break;case Ea.SmoothStep:[m]=Ho(h);break;default:[m]=Io(h)}return(0,x.jsx)(`path`,{d:m,fill:`none`,className:`react-flow__connection-path`,style:e})};ld.displayName=`ConnectionLine`;var ud={};function dd(e=ud){(0,y.useRef)(e),bc(),(0,y.useEffect)(()=>{},[e])}function fd(){bc(),(0,y.useRef)(!1),(0,y.useEffect)(()=>{},[])}function pd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:i,onNodeDoubleClick:a,onEdgeDoubleClick:o,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:h,connectionLineComponent:g,connectionLineContainerStyle:_,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,multiSelectionKeyCode:S,panActivationKeyCode:C,zoomActivationKeyCode:w,deleteKeyCode:T,onlyRenderVisibleElements:E,elementsSelectable:D,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,preventScrolling:M,defaultMarkerColor:N,zoomOnScroll:P,zoomOnPinch:ee,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,zoomOnDoubleClick:ne,panOnDrag:L,autoPanOnSelection:R,onPaneClick:z,onPaneMouseEnter:B,onPaneMouseMove:re,onPaneMouseLeave:ie,onPaneScroll:ae,onPaneContextMenu:oe,paneClickDistance:se,nodeClickDistance:ce,onEdgeContextMenu:le,onEdgeMouseEnter:ue,onEdgeMouseMove:de,onEdgeMouseLeave:fe,reconnectRadius:pe,onReconnect:me,onReconnectStart:he,onReconnectEnd:ge,noDragClassName:_e,noWheelClassName:ve,noPanClassName:ye,disableKeyboardA11y:be,nodeExtent:xe,rfId:Se,viewport:Ce,onViewportChange:we,nodesDraggable:Te}){return dd(e),dd(t),fd(),td(n),rd(Ce),(0,x.jsx)(nu,{onPaneClick:z,onPaneMouseEnter:B,onPaneMouseMove:re,onPaneMouseLeave:ie,onPaneContextMenu:oe,onPaneScroll:ae,paneClickDistance:se,deleteKeyCode:T,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:S,panActivationKeyCode:C,zoomActivationKeyCode:w,elementsSelectable:D,zoomOnScroll:P,zoomOnPinch:ee,zoomOnDoubleClick:ne,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,panOnDrag:L,autoPanOnSelection:R,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,onSelectionContextMenu:d,preventScrolling:M,noDragClassName:_e,noWheelClassName:ve,noPanClassName:ye,disableKeyboardA11y:be,onViewportChange:we,isControlledViewport:!!Ce,children:(0,x.jsxs)(ed,{children:[(0,x.jsx)(Qu,{edgeTypes:t,onEdgeClick:i,onEdgeDoubleClick:o,onReconnect:me,onReconnectStart:he,onReconnectEnd:ge,onlyRenderVisibleElements:E,onEdgeContextMenu:le,onEdgeMouseEnter:ue,onEdgeMouseMove:de,onEdgeMouseLeave:fe,reconnectRadius:pe,defaultMarkerColor:N,noPanClassName:ye,disableKeyboardA11y:be,rfId:Se}),(0,x.jsx)(cd,{style:h,type:m,component:g,containerStyle:_}),(0,x.jsx)(`div`,{className:`react-flow__edgelabel-renderer`}),(0,x.jsx)(fu,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:a,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,nodeClickDistance:ce,onlyRenderVisibleElements:E,noPanClassName:ye,noDragClassName:_e,disableKeyboardA11y:be,nodeExtent:xe,rfId:Se,nodesDraggable:Te}),(0,x.jsx)(`div`,{className:`react-flow__viewport-portal`})]})})}pd.displayName=`GraphView`;var md=(0,y.memo)(pd),hd=no(`React Flow`,`https://reactflow.dev/`),gd=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c=.5,maxZoom:l=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f=`basic`}={})=>{let p=new Map,m=new Map,h=new Map,g=new Map,_=r??t??[],v=n??e??[],y=u??[0,0],b=d??ya;ps(h,g,_);let{nodesInitialized:x}=is(v,p,m,{nodeOrigin:y,nodeExtent:b,zIndexMode:f}),S=[0,0,1];if(o&&i&&a){let{x:e,y:t,zoom:n}=lo(Pa(p,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),i,a,c,l,s?.padding??.1);S=[e,t,n]}return{rfId:`1`,width:i??0,height:a??0,transform:S,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:m,edges:_,edgeLookup:g,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:l,translateExtent:ya,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Sa.Strict,domNode:null,paneDragging:!1,noPanClassName:`nopan`,nodeOrigin:y,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:o??!1,fitViewOptions:s,fitViewResolver:null,connection:{...Ta},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:``,autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:hd,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:`react`,debug:!1,ariaLabelConfig:xa,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},_d=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>mc((p,m)=>{async function h(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:a,minZoom:o,maxZoom:s}=m();t&&(await Ra({nodes:e,width:i,height:a,panZoom:t,minZoom:o,maxZoom:s},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...gd({nodes:e,edges:t,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,fitViewQueued:o,zIndexMode:s,nodesSelectionActive:c}=m(),{nodesInitialized:l,hasSelectedNodes:u}=is(e,t,n,{nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,checkEquality:!0,zIndexMode:s}),d=c&&u;o&&l?(h(),p({nodes:e,nodesInitialized:l,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:d})):p({nodes:e,nodesInitialized:l,nodesSelectionActive:d})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=m();ps(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:a,nodeExtent:o,debug:s,fitViewQueued:c,zIndexMode:l}=m(),{changes:u,updatedInternals:d}=us(e,n,r,i,a,o,l);d&&(ts(n,r,{nodeOrigin:a,nodeExtent:o,zIndexMode:l}),c?(h(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),u?.length>0&&(s&&console.log(`React Flow: trigger node changes`,u),t?.(u)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:i,triggerNodeChanges:a,connection:o,updateConnection:s,onNodesChangeMiddlewareMap:c}=m();for(let[a,c]of e){let e=i.get(a),l=!!(e?.expandParent&&e?.parentId&&c?.position),u={id:a,type:`position`,position:l?{x:Math.max(0,c.position.x),y:Math.max(0,c.position.y)}:c.position,dragging:t};if(e&&o.inProgress&&o.fromNode.id===e.id){let t=Ko(e,o.fromHandle,H.Left,!0);s({...o,from:t})}l&&e.parentId&&n.push({id:a,parentId:e.parentId,rect:{...c.internals.positionAbsolute,width:c.measured.width??0,height:c.measured.height??0}}),r.push(u)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=m(),a=ls(n,i,e,t);r.push(...a)}for(let e of c.values())r=e(r);a(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:a}=m();e?.length&&(i&&n(el(e,r)),a&&console.log(`React Flow: trigger node changes`,e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:a}=m();e?.length&&(i&&n(tl(e,r)),a&&console.log(`React Flow: trigger edge changes`,e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){i(e.map(e=>nl(e,!0)));return}i(rl(r,new Set([...e]),!0)),a(rl(n))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){a(e.map(e=>nl(e,!0)));return}a(rl(n,new Set([...e]))),i(rl(r,new Set,!0))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:a,triggerEdgeChanges:o}=m(),s=e||r,c=t||n,l=[];for(let e of s){if(!e.selected)continue;let t=i.get(e.id);t&&(t.selected=!1),l.push(nl(e.id,!1))}let u=[];for(let e of c)e.selected&&u.push(nl(e.id,!1));a(l),o(u)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=m();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=m();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:i}=m();if(!i)return;let a=t.reduce((e,t)=>t.selected?[...e,nl(t.id,!1)]:e,[]),o=e.reduce((e,t)=>t.selected?[...e,nl(t.id,!1)]:e,[]);n(a),r(o)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:a,nodeExtent:o,zIndexMode:s}=m();(e[0][0]!==o[0][0]||e[0][1]!==o[0][1]||e[1][0]!==o[1][0]||e[1][1]!==o[1][1])&&(is(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:a,checkEquality:!1,zIndexMode:s}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:i,translateExtent:a}=m();return ds({delta:e,panZoom:i,transform:t,translateExtent:a,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:i,maxZoom:a,panZoom:o}=m();if(!o)return!1;let s=n?.zoom===void 0?a:n.zoom;return await o.setViewport({x:r/2-e*s,y:i/2-t*s,zoom:s},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0},cancelConnection:()=>{p({connection:{...Ta}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...gd()})}},Object.is);function vd({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:i,initialHeight:a,initialMinZoom:o,initialMaxZoom:s,initialFitViewOptions:c,fitView:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:p}){let[m]=(0,y.useState)(()=>_d({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:l,minZoom:o,maxZoom:s,fitViewOptions:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,x.jsx)(vc,{value:m,children:(0,x.jsx)(hl,{children:(0,x.jsx)(Bl,{children:p})})})}function yd({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:i,width:a,height:o,fitView:s,fitViewOptions:c,minZoom:l,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p}){return(0,y.useContext)(_c)?(0,x.jsx)(x.Fragment,{children:e}):(0,x.jsx)(vd,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:i,initialWidth:a,initialHeight:o,fitView:s,initialFitViewOptions:c,initialMinZoom:l,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p,children:e})}var bd={width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`,zIndex:0};function xd({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a,edgeTypes:o,onNodeClick:s,onEdgeClick:c,onInit:l,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,onNodeMouseEnter:v,onNodeMouseMove:b,onNodeMouseLeave:C,onNodeContextMenu:w,onNodeDoubleClick:T,onNodeDragStart:E,onNodeDrag:D,onNodeDragStop:O,onNodesDelete:k,onEdgesDelete:A,onDelete:j,onSelectionChange:M,onSelectionDragStart:N,onSelectionDrag:P,onSelectionDragStop:ee,onSelectionContextMenu:F,onSelectionStart:I,onSelectionEnd:te,onBeforeDelete:ne,connectionMode:L,connectionLineType:R=Ea.Bezier,connectionLineStyle:z,connectionLineComponent:B,connectionLineContainerStyle:re,deleteKeyCode:ie=`Backspace`,selectionKeyCode:ae=`Shift`,selectionOnDrag:oe=!1,selectionMode:se=wa.Full,panActivationKeyCode:ce=`Space`,multiSelectionKeyCode:le=U()?`Meta`:`Control`,zoomActivationKeyCode:ue=U()?`Meta`:`Control`,snapToGrid:de,snapGrid:fe,onlyRenderVisibleElements:pe=!1,selectNodesOnDrag:me,nodesDraggable:he,autoPanOnNodeFocus:ge,nodesConnectable:_e,nodesFocusable:ve,nodeOrigin:ye=zc,edgesFocusable:be,edgesReconnectable:xe,elementsSelectable:Se=!0,defaultViewport:Ce=Bc,minZoom:we=.5,maxZoom:Te=2,translateExtent:Ee=ya,preventScrolling:De=!0,nodeExtent:Oe,defaultMarkerColor:ke=`#b1b1b7`,zoomOnScroll:Ae=!0,zoomOnPinch:je=!0,panOnScroll:Me=!1,panOnScrollSpeed:Ne=.5,panOnScrollMode:Pe=Ca.Free,zoomOnDoubleClick:Fe=!0,panOnDrag:Ie=!0,onPaneClick:Le,onPaneMouseEnter:Re,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:Ve,onPaneContextMenu:He,paneClickDistance:Ue=1,nodeClickDistance:We=0,children:Ge,onReconnect:Ke,onReconnectStart:qe,onReconnectEnd:Je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Xe,onEdgeMouseEnter:Ze,onEdgeMouseMove:Qe,onEdgeMouseLeave:$e,reconnectRadius:et=10,onNodesChange:tt,onEdgesChange:nt,noDragClassName:rt=`nodrag`,noWheelClassName:it=`nowheel`,noPanClassName:at=`nopan`,fitView:ot,fitViewOptions:st,connectOnClick:ct,attributionPosition:lt,proOptions:ut,defaultEdgeOptions:dt,elevateNodesOnSelect:ft=!0,elevateEdgesOnSelect:pt=!1,disableKeyboardA11y:mt=!1,autoPanOnConnect:ht,autoPanOnNodeDrag:gt,autoPanOnSelection:_t=!0,autoPanSpeed:vt,connectionRadius:yt,isValidConnection:bt,onError:xt,style:St,id:Ct,nodeDragThreshold:wt,connectionDragThreshold:Tt,viewport:Et,onViewportChange:Dt,width:Ot,height:kt,colorMode:At=`light`,debug:jt,onScroll:Mt,ariaLabelConfig:Nt,zIndexMode:Pt=`basic`,...Ft},It){let Lt=Ct||`1`,Rt=Kc(At),zt=(0,y.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:`instant`}),Mt?.(e)},[Mt]);return(0,x.jsx)(`div`,{"data-testid":`rf__wrapper`,...Ft,onScroll:zt,style:{...St,...bd},ref:It,className:S([`react-flow`,i,Rt]),id:Ct,role:`application`,children:(0,x.jsxs)(yd,{nodes:e,edges:t,width:Ot,height:kt,fitView:ot,fitViewOptions:st,minZoom:we,maxZoom:Te,nodeOrigin:ye,nodeExtent:Oe,zIndexMode:Pt,children:[(0,x.jsx)(Wc,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:_,nodesDraggable:he,autoPanOnNodeFocus:ge,nodesConnectable:_e,nodesFocusable:ve,edgesFocusable:be,edgesReconnectable:xe,elementsSelectable:Se,elevateNodesOnSelect:ft,elevateEdgesOnSelect:pt,minZoom:we,maxZoom:Te,nodeExtent:Oe,onNodesChange:tt,onEdgesChange:nt,snapToGrid:de,snapGrid:fe,connectionMode:L,translateExtent:Ee,connectOnClick:ct,defaultEdgeOptions:dt,fitView:ot,fitViewOptions:st,onNodesDelete:k,onEdgesDelete:A,onDelete:j,onNodeDragStart:E,onNodeDrag:D,onNodeDragStop:O,onSelectionDrag:P,onSelectionDragStart:N,onSelectionDragStop:ee,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:at,nodeOrigin:ye,rfId:Lt,autoPanOnConnect:ht,autoPanOnNodeDrag:gt,autoPanSpeed:vt,onError:xt,connectionRadius:yt,isValidConnection:bt,selectNodesOnDrag:me,nodeDragThreshold:wt,connectionDragThreshold:Tt,onBeforeDelete:ne,debug:jt,ariaLabelConfig:Nt,zIndexMode:Pt}),(0,x.jsx)(md,{onInit:l,onNodeClick:s,onEdgeClick:c,onNodeMouseEnter:v,onNodeMouseMove:b,onNodeMouseLeave:C,onNodeContextMenu:w,onNodeDoubleClick:T,nodeTypes:a,edgeTypes:o,connectionLineType:R,connectionLineStyle:z,connectionLineComponent:B,connectionLineContainerStyle:re,selectionKeyCode:ae,selectionOnDrag:oe,selectionMode:se,deleteKeyCode:ie,multiSelectionKeyCode:le,panActivationKeyCode:ce,zoomActivationKeyCode:ue,onlyRenderVisibleElements:pe,defaultViewport:Ce,translateExtent:Ee,minZoom:we,maxZoom:Te,preventScrolling:De,zoomOnScroll:Ae,zoomOnPinch:je,zoomOnDoubleClick:Fe,panOnScroll:Me,panOnScrollSpeed:Ne,panOnScrollMode:Pe,panOnDrag:Ie,autoPanOnSelection:_t,onPaneClick:Le,onPaneMouseEnter:Re,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:Ve,onPaneContextMenu:He,paneClickDistance:Ue,nodeClickDistance:We,onSelectionContextMenu:F,onSelectionStart:I,onSelectionEnd:te,onReconnect:Ke,onReconnectStart:qe,onReconnectEnd:Je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Xe,onEdgeMouseEnter:Ze,onEdgeMouseMove:Qe,onEdgeMouseLeave:$e,reconnectRadius:et,defaultMarkerColor:ke,noDragClassName:rt,noWheelClassName:it,noPanClassName:at,rfId:Lt,disableKeyboardA11y:mt,nodeExtent:Oe,viewport:Et,onViewportChange:Dt,nodesDraggable:he}),(0,x.jsx)(Rc,{onSelectionChange:M}),Ge,(0,x.jsx)(Mc,{proOptions:ut,position:lt}),(0,x.jsx)(kc,{rfId:Lt,disableKeyboardA11y:mt})]})})}var Sd=ul(xd),Cd=e=>e.domNode?.querySelector(`.react-flow__edgelabel-renderer`);function J({children:e}){let t=G(Cd);return t?(0,gc.createPortal)(e,t):null}var wd=e=>({x:e.transform[0],y:e.transform[1],zoom:e.transform[2]});function Td(){return G(wd,hc)}function Ed(e){let[t,n]=(0,y.useState)(e);return[t,n,(0,y.useCallback)(e=>n(t=>el(e,t)),[])]}function Dd(e){let[t,n]=(0,y.useState)(e);return[t,n,(0,y.useCallback)(e=>n(t=>tl(e,t)),[])]}va.error014();function Od({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,x.jsx)(`path`,{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:S([`react-flow__background-pattern`,n,r])})}function kd({radius:e,className:t}){return(0,x.jsx)(`circle`,{cx:e,cy:e,r:e,className:S([`react-flow__background-pattern`,`dots`,t])})}var Ad;(function(e){e.Lines=`lines`,e.Dots=`dots`,e.Cross=`cross`})(Ad||={});var jd={[Ad.Dots]:1,[Ad.Lines]:1,[Ad.Cross]:6},Md=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Nd({id:e,variant:t=Ad.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=0,color:o,bgColor:s,style:c,className:l,patternClassName:u}){let d=(0,y.useRef)(null),{transform:f,patternId:p}=G(Md,hc),m=r||jd[t],h=t===Ad.Dots,g=t===Ad.Cross,_=Array.isArray(n)?n:[n,n],v=[_[0]*f[2]||1,_[1]*f[2]||1],b=m*f[2],C=Array.isArray(a)?a:[a,a],w=g?[b,b]:v,T=[C[0]*f[2]+w[0]/2,C[1]*f[2]+w[1]/2],E=`${p}${e||``}`;return(0,x.jsxs)(`svg`,{className:S([`react-flow__background`,l]),style:{...c,...Cl,"--xy-background-color-props":s,"--xy-background-pattern-color-props":o},ref:d,"data-testid":`rf__background`,children:[(0,x.jsx)(`pattern`,{id:E,x:f[0]%v[0],y:f[1]%v[1],width:v[0],height:v[1],patternUnits:`userSpaceOnUse`,patternTransform:`translate(-${T[0]},-${T[1]})`,children:h?(0,x.jsx)(kd,{radius:b/2,className:u}):(0,x.jsx)(Od,{dimensions:w,lineWidth:i,variant:t,className:u})}),(0,x.jsx)(`rect`,{x:`0`,y:`0`,width:`100%`,height:`100%`,fill:`url(#${E})`})]})}Nd.displayName=`Background`,(0,y.memo)(Nd);function Pd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,children:(0,x.jsx)(`path`,{d:`M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z`})})}function Fd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 5`,children:(0,x.jsx)(`path`,{d:`M0 0h32v4.2H0z`})})}function Id(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 30`,children:(0,x.jsx)(`path`,{d:`M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z`})})}function Ld(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,x.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z`})})}function Rd(){return(0,x.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,x.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z`})})}function zd({children:e,className:t,...n}){return(0,x.jsx)(`button`,{type:`button`,className:S([`react-flow__controls-button`,t]),...n,children:e})}var Bd=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Vd({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:o,onFitView:s,onInteractiveChange:c,className:l,children:u,position:d=`bottom-left`,orientation:f=`vertical`,"aria-label":p}){let m=bc(),{isInteractive:h,minZoomReached:g,maxZoomReached:_,ariaLabelConfig:v}=G(Bd,hc),{zoomIn:y,zoomOut:b,fitView:C}=vl();return(0,x.jsxs)(Ac,{className:S([`react-flow__controls`,f===`horizontal`?`horizontal`:`vertical`,l]),position:d,style:e,"data-testid":`rf__controls`,"aria-label":p??v[`controls.ariaLabel`],children:[t&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zd,{onClick:()=>{y(),a?.()},className:`react-flow__controls-zoomin`,title:v[`controls.zoomIn.ariaLabel`],"aria-label":v[`controls.zoomIn.ariaLabel`],disabled:_,children:(0,x.jsx)(Pd,{})}),(0,x.jsx)(zd,{onClick:()=>{b(),o?.()},className:`react-flow__controls-zoomout`,title:v[`controls.zoomOut.ariaLabel`],"aria-label":v[`controls.zoomOut.ariaLabel`],disabled:g,children:(0,x.jsx)(Fd,{})})]}),n&&(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:()=>{C(i),s?.()},title:v[`controls.fitView.ariaLabel`],"aria-label":v[`controls.fitView.ariaLabel`],children:(0,x.jsx)(Id,{})}),r&&(0,x.jsx)(zd,{className:`react-flow__controls-interactive`,onClick:()=>{m.setState({nodesDraggable:!h,nodesConnectable:!h,elementsSelectable:!h}),c?.(!h)},title:v[`controls.interactive.ariaLabel`],"aria-label":v[`controls.interactive.ariaLabel`],children:h?(0,x.jsx)(Rd,{}):(0,x.jsx)(Ld,{})}),u]})}Vd.displayName=`Controls`;var Hd=(0,y.memo)(Vd);function Ud({id:e,x:t,y:n,width:r,height:i,style:a,color:o,strokeColor:s,strokeWidth:c,className:l,borderRadius:u,shapeRendering:d,selected:f,onClick:p}){let{background:m,backgroundColor:h}=a||{},g=o||m||h;return(0,x.jsx)(`rect`,{className:S([`react-flow__minimap-node`,{selected:f},l]),x:t,y:n,rx:u,ry:u,width:r,height:i,style:{fill:g,stroke:s,strokeWidth:c},shapeRendering:d,onClick:p?t=>p(t,e):void 0})}var Wd=(0,y.memo)(Ud),Gd=e=>e.nodes.map(e=>e.id),Kd=e=>e instanceof Function?e:()=>e;function qd({nodeStrokeColor:e,nodeColor:t,nodeClassName:n=``,nodeBorderRadius:r=5,nodeStrokeWidth:i,nodeComponent:a=Wd,onClick:o}){let s=G(Gd,hc),c=Kd(t),l=Kd(e),u=Kd(n),d=typeof window>`u`||window.chrome?`crispEdges`:`geometricPrecision`;return(0,x.jsx)(x.Fragment,{children:s.map(e=>(0,x.jsx)(Yd,{id:e,nodeColorFunc:c,nodeStrokeColorFunc:l,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:i,NodeComponent:a,onClick:o,shapeRendering:d},e))})}function Jd({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:i,nodeStrokeWidth:a,shapeRendering:o,NodeComponent:s,onClick:c}){let{node:l,x:u,y:d,width:f,height:p}=G(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:i,y:a}=n.internals.positionAbsolute,{width:o,height:s}=uo(r);return{node:r,x:i,y:a,width:o,height:s}},hc);return!l||l.hidden||!fo(l)?null:(0,x.jsx)(s,{x:u,y:d,width:f,height:p,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:i,strokeColor:n(l),strokeWidth:a,shapeRendering:o,onClick:c,id:l.id})}var Yd=(0,y.memo)(Jd),Xd=(0,y.memo)(qd),Zd=200,Qd=150,$d=e=>!e.hidden,ef=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]},n=!1;for(let t of e.nodeLookup.values())if(!t.hidden){n=!0;break}return{viewBB:t,boundingRect:n?Za(Pa(e.nodeLookup,{filter:$d}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},tf=(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,nf=(e,t)=>tf(e.viewBB,t.viewBB)&&tf(e.boundingRect,t.boundingRect)&&e.rfId===t.rfId&&e.panZoom===t.panZoom&&e.translateExtent===t.translateExtent&&e.flowWidth===t.flowWidth&&e.flowHeight===t.flowHeight&&e.ariaLabelConfig===t.ariaLabelConfig,rf=`react-flow__minimap-desc`;function af({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:i=``,nodeBorderRadius:a=5,nodeStrokeWidth:o,nodeComponent:s,bgColor:c,maskColor:l,maskStrokeColor:u,maskStrokeWidth:d,position:f=`bottom-right`,onClick:p,onNodeClick:m,pannable:h=!1,zoomable:g=!1,ariaLabel:_,inversePan:v,zoomStep:b=1,offsetScale:C=5}){let w=bc(),T=(0,y.useRef)(null),{boundingRect:E,panZoom:D,viewBB:O,rfId:k,translateExtent:A,flowWidth:j,flowHeight:M,ariaLabelConfig:N}=G(ef,nf),P=e?.width??Zd,ee=e?.height??Qd,F=E.width/P,I=E.height/ee,te=Math.max(F,I),ne=te*P,L=te*ee,R=C*te,z=E.x-(ne-E.width)/2-R,B=E.y-(L-E.height)/2-R,re=ne+R*2,ie=L+R*2,ae=`${rf}-${k}`,oe=(0,y.useRef)(0),se=(0,y.useRef)();oe.current=te,(0,y.useEffect)(()=>{let e=w.getState().panZoom;if(T.current&&e)return se.current=As({domNode:T.current,panZoom:e,getTransform:()=>w.getState().transform,getViewScale:()=>oe.current}),()=>{se.current?.destroy()}},[D]),(0,y.useEffect)(()=>{se.current?.update({translateExtent:A,width:j,height:M,inversePan:v,pannable:h,zoomStep:b,zoomable:g})},[h,g,v,b,A,j,M]);let ce=p?e=>{let[t,n]=se.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,le=(0,y.useCallback)((e,t)=>{let n=w.getState().nodeLookup.get(t).internals.userNode;m?.(e,n)},[m]),ue=m?le:void 0,de=_??N[`minimap.ariaLabel`];return(0,x.jsx)(Ac,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c==`string`?c:void 0,"--xy-minimap-mask-background-color-props":typeof l==`string`?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof u==`string`?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d==`number`?d*te:void 0,"--xy-minimap-node-background-color-props":typeof r==`string`?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n==`string`?n:void 0,"--xy-minimap-node-stroke-width-props":typeof o==`number`?o:void 0},className:S([`react-flow__minimap`,t]),"data-testid":`rf__minimap`,children:(0,x.jsxs)(`svg`,{width:P,height:ee,viewBox:`${z} ${B} ${re} ${ie}`,className:`react-flow__minimap-svg`,role:`img`,"aria-labelledby":ae,ref:T,onClick:ce,children:[de&&(0,x.jsx)(`title`,{id:ae,children:de}),(0,x.jsx)(Xd,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:o,nodeComponent:s}),(0,x.jsx)(`path`,{className:`react-flow__minimap-mask`,d:`M${z-R},${B-R}h${re+R*2}v${ie+R*2}h${-re-R*2}z - M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}af.displayName=`MiniMap`;var of=(0,y.memo)(af),sf=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,cf={[Gs.Line]:`right`,[Gs.Handle]:`bottom-right`};function lf({nodeId:e,position:t,variant:n=Gs.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let v=Ll(),b=typeof e==`string`?e:v,C=bc(),w=(0,y.useRef)(null),T=n===Gs.Handle,E=G((0,y.useCallback)(sf(T&&p),[T,p]),hc),D=(0,y.useRef)(null),O=t??cf[n];(0,y.useEffect)(()=>{if(!(!w.current||!b))return D.current||=nc({domNode:w.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=C.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=C.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=ls([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...po({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};C.getState().triggerNodeChanges([n])}}),D.current.update({controlPosition:O,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{D.current?.destroy()}},[O,s,c,l,u,d,h,g,_,m]);let k=O.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__resize-control`,`nodrag`,...k,n,r]),ref:w,style:{...i,scale:E,...o&&{[T?`backgroundColor`:`borderColor`]:o}},children:a})}(0,y.memo)(lf);var uf=e=>e?.meta?.viewId??e?.meta?.diagramType??`architecture`,df=e=>e?.meta?.architectureView??`relations`,ff=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&df(e)!==`relations`,pf={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`},mf=Object.freeze([{id:`capabilities`,type:`architecture`,label:pf.capabilities},{id:`engineering`,type:`architecture`,label:pf.engineering},{id:`relations`,type:`architecture`,label:pf.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]),hf=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?df(e):e.meta.diagramType,gf=e=>mf.find(t=>t.id===hf(e))?.label??e?.meta?.diagramType??pf.relations,_f=(e,t)=>{let n=e=>{let t=mf.findIndex(t=>t.id===hf(e));return t<0?mf.length:t};return n(e)-n(t)},vf={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`,"Source changes":`源码变化`,"Show source changes":`显示源码变化`,"Hide source changes":`隐藏源码变化`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`,"Source changes":`ソースの変更`,"Show source changes":`ソースの変更を表示`,"Hide source changes":`ソースの変更を隠す`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`,"Source changes":`소스 변경`,"Show source changes":`소스 변경 표시`,"Hide source changes":`소스 변경 숨기기`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`,"Source changes":`Quellcode-Änderungen`,"Show source changes":`Quellcode-Änderungen anzeigen`,"Hide source changes":`Quellcode-Änderungen ausblenden`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`,"Source changes":`Modifications du code`,"Show source changes":`Afficher les modifications du code`,"Hide source changes":`Masquer les modifications du code`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`,"Source changes":`Cambios en el código`,"Show source changes":`Mostrar cambios en el código`,"Hide source changes":`Ocultar cambios en el código`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости","Source changes":"Изменения в коде","Show source changes":"Показать изменения в коде","Hide source changes":"Скрыть изменения в коде"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`,"Source changes":`Alterações no código`,"Show source changes":`Mostrar alterações no código`,"Hide source changes":`Ocultar alterações no código`}},yf=[`en`,...Object.keys(vf)];function bf(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(vf,r)?vf[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function xf(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}var Sf=e=>!ff(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null;function Cf(e){let t=Sf(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function wf(e){let t=Sf(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!ff(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=xf(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function Tf(e){if(!Sf(e))return{...e,edges:wf(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of Cf(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:wf(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}var Ef=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),Df=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),Of=Object.freeze({...Ef,nodeGap:32,groupInset:24,groupGap:32});Object.freeze({...Df,nodeGap:40,layerGap:48});var kf=e=>e?.cardLayout?Of:Ef,Af=.75,jf=.45;Object.freeze({width:1392,height:688});var Mf=[`er`,`deployment`,`dataflow`,`usecase`],Nf=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[Mf.includes(e)?`right`:`down`],Pf=(e,t)=>(t?.direction??Nf(e)[0])===`down`,Ff={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},If=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],Lf={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},Rf=`MIT License + M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}af.displayName=`MiniMap`;var of=(0,y.memo)(af),sf=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,cf={[Gs.Line]:`right`,[Gs.Handle]:`bottom-right`};function lf({nodeId:e,position:t,variant:n=Gs.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:_}){let v=Ll(),b=typeof e==`string`?e:v,C=bc(),w=(0,y.useRef)(null),T=n===Gs.Handle,E=G((0,y.useCallback)(sf(T&&p),[T,p]),hc),D=(0,y.useRef)(null),O=t??cf[n];(0,y.useEffect)(()=>{if(!(!w.current||!b))return D.current||=nc({domNode:w.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=C.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=C.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=ls([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...po({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};C.getState().triggerNodeChanges([n])}}),D.current.update({controlPosition:O,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:_,shouldResize:m}),()=>{D.current?.destroy()}},[O,s,c,l,u,d,h,g,_,m]);let k=O.split(`-`);return(0,x.jsx)(`div`,{className:S([`react-flow__resize-control`,`nodrag`,...k,n,r]),ref:w,style:{...i,scale:E,...o&&{[T?`backgroundColor`:`borderColor`]:o}},children:a})}(0,y.memo)(lf);var uf=e=>e?.meta?.viewId??e?.meta?.diagramType??`architecture`,df=e=>e?.meta?.architectureView??`relations`,ff=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&df(e)!==`relations`,pf={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`},mf=Object.freeze([{id:`capabilities`,type:`architecture`,label:pf.capabilities},{id:`engineering`,type:`architecture`,label:pf.engineering},{id:`relations`,type:`architecture`,label:pf.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]),hf=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?df(e):e.meta.diagramType,gf=e=>mf.find(t=>t.id===hf(e))?.label??e?.meta?.diagramType??pf.relations,_f=(e,t)=>{let n=e=>{let t=mf.findIndex(t=>t.id===hf(e));return t<0?mf.length:t};return n(e)-n(t)},vf={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`,"Source changes":`源码变化`,"Show source changes":`显示源码变化`,"Hide source changes":`隐藏源码变化`,"This update":`本次更新`,"Show this update":`显示本次更新`,"Hide this update":`隐藏本次更新`,Added:`新增`,Changed:`改动`,Removed:`删除`,"View notes updated":`视图说明已更新`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`,"Source changes":`ソースの変更`,"Show source changes":`ソースの変更を表示`,"Hide source changes":`ソースの変更を隠す`,"This update":`今回の更新`,"Show this update":`今回の更新を表示`,"Hide this update":`今回の更新を隠す`,Added:`追加`,Changed:`変更`,Removed:`削除`,"View notes updated":`ビューの説明を更新`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`,"Source changes":`소스 변경`,"Show source changes":`소스 변경 표시`,"Hide source changes":`소스 변경 숨기기`,"This update":`이번 업데이트`,"Show this update":`이번 업데이트 표시`,"Hide this update":`이번 업데이트 숨기기`,Added:`추가`,Changed:`변경`,Removed:`삭제`,"View notes updated":`뷰 설명이 갱신됨`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`,"Source changes":`Quellcode-Änderungen`,"Show source changes":`Quellcode-Änderungen anzeigen`,"Hide source changes":`Quellcode-Änderungen ausblenden`,"This update":`Diese Aktualisierung`,"Show this update":`Diese Aktualisierung anzeigen`,"Hide this update":`Diese Aktualisierung ausblenden`,Added:`Hinzugefügt`,Changed:`Geändert`,Removed:`Entfernt`,"View notes updated":`Ansichtsbeschreibung aktualisiert`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`,"Source changes":`Modifications du code`,"Show source changes":`Afficher les modifications du code`,"Hide source changes":`Masquer les modifications du code`,"This update":`Cette mise à jour`,"Show this update":`Afficher cette mise à jour`,"Hide this update":`Masquer cette mise à jour`,Added:`Ajouté`,Changed:`Modifié`,Removed:`Supprimé`,"View notes updated":`Description de la vue mise à jour`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`,"Source changes":`Cambios en el código`,"Show source changes":`Mostrar cambios en el código`,"Hide source changes":`Ocultar cambios en el código`,"This update":`Esta actualización`,"Show this update":`Mostrar esta actualización`,"Hide this update":`Ocultar esta actualización`,Added:`Añadido`,Changed:`Modificado`,Removed:`Eliminado`,"View notes updated":`Descripción de la vista actualizada`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости","Source changes":"Изменения в коде","Show source changes":"Показать изменения в коде","Hide source changes":"Скрыть изменения в коде","This update":"Это обновление","Show this update":"Показать это обновление","Hide this update":"Скрыть это обновление","Added":"Добавлено","Changed":"Изменено","Removed":"Удалено","View notes updated":"Описание представления обновлено"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`,"Source changes":`Alterações no código`,"Show source changes":`Mostrar alterações no código`,"Hide source changes":`Ocultar alterações no código`,"This update":`Esta atualização`,"Show this update":`Mostrar esta atualização`,"Hide this update":`Ocultar esta atualização`,Added:`Adicionado`,Changed:`Alterado`,Removed:`Removido`,"View notes updated":`Descrição da visão atualizada`}},yf=[`en`,...Object.keys(vf)];function bf(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(vf,r)?vf[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function xf(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}var Sf=e=>!ff(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null;function Cf(e){let t=Sf(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function wf(e){let t=Sf(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!ff(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=xf(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function Tf(e){if(!Sf(e))return{...e,edges:wf(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of Cf(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:wf(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}var Ef=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),Df=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),Of=Object.freeze({...Ef,nodeGap:32,groupInset:24,groupGap:32});Object.freeze({...Df,nodeGap:40,layerGap:48});var kf=e=>e?.cardLayout?Of:Ef,Af=.75,jf=.45;Object.freeze({width:1392,height:688});var Mf=[`er`,`deployment`,`dataflow`,`usecase`],Nf=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[Mf.includes(e)?`right`:`down`],Pf=(e,t)=>(t?.direction??Nf(e)[0])===`down`,Ff={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},If=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],Lf={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},Rf=`MIT License Copyright (c) 2021-2022 Modulz Copyright (c) 2022-Present WorkOS @@ -276,15 +276,15 @@ ${t}.member{font:500 ${X.body}px ui-monospace,monospace;fill:${e.ink2}} ${t}.field-type{font:400 ${X.body}px ui-monospace,monospace;fill:${e.ink3}} `}function Xp(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return em(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+xp.pad,v=g+xp.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*xp.chipLine;return`${Q(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>Q(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>Q(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>Q(v,b+14+t*f.lineHeight,e,`meta`)).join(``),E={x:g+xp.pad,y:_+(xp.titleLine-xp.plate)/2},D=t+e.size.width-c-xp.pad-p.width-l;return`${Zp(e,t,n,r,i,s)}${Qp(e,E.x,E.y,xp.plate,a)}${Q(D+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}var Zp=(e,t,n,r,i,a)=>Ip(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function Qp(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:Yf(e)?i.accent:Jf.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${$p(e)}`}var $p=e=>Jf.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function em(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Tp({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>Q(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>Q(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${Zp(e,t,n,r,i,s)}${Qp(e,t+15+c,n+13,25,a)}${Q(t+47+c,n+29,wp(e,o).text,`stereotype`)}${d}${f}`}var tm=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],nm=[[.08,0],[1,0],[.92,1],[0,1]];function rm(e,t,n){let{width:r,height:i}=e.size;if(Cg(e))return Lp(e,t,n,16);if(e.kind===`external`)return Bp(e,t,n,zp);if(e.kind===`security`)return Lp(e,t,n,22);if(e.kind===`failure`)return Bp(e,t,n,tm);if(e.kind===`config`)return Bp(e,t,n,nm);if(e.kind===`business`)return Lp(e,t,n,Math.min(28,i/2));let a=Lp(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}var im=(e,t,n)=>Cg(e)?Gp(e,t,n,16):e.kind===`external`?qp(e,t,n,zp):e.kind===`security`?Gp(e,t,n,22):e.kind===`failure`?qp(e,t,n,tm):e.kind===`config`?qp(e,t,n,nm):e.kind===`business`?Gp(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):Wp(e,t,n),am=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0,om={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Cg(e)?Mg(e,t,n,a,r,i):Xp(e,t,n,r,i,a,o,rm,am(e)),outline:rm,anchor:im,cardLayout:!0,contentInset:am},sm=.12,cm=(e,t,n)=>e.kind===`decision`?Vp(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*sm},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:Lp(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),lm=(e,t,n)=>e.kind===`decision`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?qp(e,t,n,[[sm,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Gp(e,t,n,e.size.height/2):Wp(e,t,n),um=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*sm+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function dm(e,t,n,r,i){let{width:a,height:o}=e.size,s=um(e),c=Fp(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${Ip(cm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var fm={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:dm,outline:cm,anchor:lm,textArea:um,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?bf(t,e.kind):``)},pm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n):Lp(e,t,n,7,mm(e));function mm(e){let t=(e.size?.width??280)-28,n=Z(e.label,t,20,26).lines.length,r=e.subtitle?Z(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?X.sequenceActorHeader+(e.subtitle?22:0):X.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function hm(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=mm(e),u=Ip(pm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=Z(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:Q(s,n+20,bf(o,up[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>Q(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?Z(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>Q(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Np([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var gm={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:hm,outline:pm,sequence:!0,selectionHeight:mm,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}},_m=(e,t,n)=>Lp(e,t,n,9);function vm(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=dp(e),u=Pp(e.subtitle??bf(o,`Entity`),e.size.width-60),d=e.subtitle?X.body:X.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,Z(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?Q(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${Q(t+45,u,Pp(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${Q(t+e.size.width-10,u-1,Pp(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${Ip(_m(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${Q(t+13,n+s*.43,Pp(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(X.title,s*.38)}px;fill:${a.ink}"`)}${Q(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${Q(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var ym={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:vm,outline:_m,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}},bm=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function xm(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Bp(e,t,n,bm),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...Lp(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Rp(e,t,n):e.kind===`external`?Bp(e,t,n,zp):e.kind===`service`?Lp(e,t,n,16):Lp(e,t,n,10)}var Sm=(e,t,n)=>e.kind===`device`?Wp(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?qp(e,t,n,bm):e.kind===`database`?Wp(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?qp(e,t,n,zp):e.kind===`service`?Gp(e,t,n,16):Wp(e,t,n),Cm=e=>({container:24,artifact:18,node:20})[e.kind]??0,wm=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0,Tm={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>Xp(e,...t,xm,wm(e),Cm(e)),outline:xm,anchor:Sm,cardLayout:!0,contentInset:wm,cardCorner:Cm},Em=(e,t,n)=>Lp(e,t,n,9);function Dm(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=dp(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>Q(t+13,d+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``),g=s.map((e,n)=>Q(t+13,f+6+l/2+X.body*.35+n*l,Pp(e,m),`member`)).join(``);return`${Ip(Em(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?Q(t+13,n+24,p,`stereotype`):``}${Q(t+13,n+(p?50:X.classHeader/2+7),Pp(e.label,m),`shape-title`)}${e.subtitle?Q(t+13,n+c-10,Pp(e.subtitle,m),`body`):``}${h}${g}`}var Om={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:Dm,outline:Em,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?bf(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\d+)(?:\.\.(\d+|\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=kp(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}},km=e=>e.subtitle?14:e.size.width/2,Am=[`entry`,`do`,`exit`],jm={side:16,pad:8,line:20,keyWidth:64};function Mm(e){let t=e.kind===`state`?Am.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:Z(e[t],e.size.width-2*jm.side-jm.keyWidth,X.small,jm.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*jm.line+2*jm.pad:0}}var Nm=2*jm.side+jm.keyWidth,Pm=e=>{let{height:t}=Mm(e);return t?{x:jm.side,y:e.size.height-t,width:e.size.width-2*jm.side,height:t}:null},Fm=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+km(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Vp(e,t,n):Lp(e,t,n,12),Im=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=km(e)-e.size.width/2;return Kp({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?qp(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):Wp(e,t,n)},Lm=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=Mm(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function Rm(e,t,n,r,i){let{rows:a,height:o}=Mm(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+jm.pad+c++*jm.line+15;return(r?``:Q(t+jm.side,a,`${e.key} /`,`field-key`))+Q(t+jm.side+jm.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function zm(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=Lm(e),o=e.kind===`final`;return`${Ip(Fm(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Fp(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=Lm(e),l=n+(e.size.height-Mm(e).height)/2;return`${Ip(Fm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,l,e.label,c.width,c.height,e.subtitle)}${Rm(e,t,n,i,a)}`}var Bm=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text),Vm={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:zm,outline:Fm,anchor:Im,textArea:Lm,activityArea:Pm,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>Bm(e).map(e=>e.text).join(` `),edgeLabelParts:Bm,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of Am)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}},Hm=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Um=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Wm=(e,t,n)=>e.kind===`actor`?Hp(e,t,n+Hm(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Gm=(e,t,n)=>e.kind===`actor`?Jp(e,t,n,Hm(e)):Kp(e,t,n);function Km(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${Q(o,n+Hm(e)+98,Pp(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?Q(o,n+Hm(e)+122,Pp(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Um(e);return`${Ip(Wm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var qm={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:Km,outline:Wm,anchor:Gm,textArea:Um,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}},Jm=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:Lp(e,t,n,e.kind===`process`?24:10),Ym=e=>({width:e.size.width-32,height:e.size.height-20});function Xm(e,t,n,r,i){let a=Ym(e);return`${Ip(Jm(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Fp(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}var Zm=[om,fm,gm,ym,Tm,Om,Vm,qm,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Xm,outline:Jm,textArea:Ym,anchor:(e,t,n)=>e.kind===`process`?Gp(e,t,n,24):Wp(e,t,n)}],Qm=Zm.map(e=>e.id);Object.fromEntries(Zm.map(e=>[e.id,e.label]));var $m=new Map(Zm.map(e=>[e.id,e]));if($m.size!==Zm.length)throw Error(`Duplicate diagram type`);var eh=e=>e?.meta?.diagramType??`architecture`,$=(e=`architecture`)=>$m.get(e),th=(e,t,n,r=!1)=>t===`architecture`&&Cg(e)?Tg(e):Tp({...e,size:{...e.size,width:e.size.width-2*($(t).contentInset?.(e)??0)}},n,r,$(t).cardCorner?.(e)),nh=e=>{let t=eh(e);return!$(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=th(n,t,e.meta?.locale).minHeight)},rh=(e,t)=>!($(t).undirected??[]).includes(e.kind),ih=(e,t)=>(t!==`sequence`||e.kind!==`sync`)&&([`framework`,`inference`].includes(e.evidence)||($(t).dashedKinds??[]).includes(e.kind)),ah=(e,t)=>Object.fromEntries(Object.entries($(e)?.labelRoleColors??{}).map(([e,n])=>[e,t[n]])),oh=(e,t)=>({start:null,end:rh(e,t)?`arrow`:null,...$(t).markers?.[e.kind]}),sh=e=>/^templates-v([4-9]|\d{2,})-/.test(e.layout?.version??``),ch=e=>/^templates-v([3-9]|\d{2,})-/.test(e.layout?.version??``),lh=e=>/^templates-v([2-9]|\d{2,})-/.test(e.layout?.version??``);Object.freeze({bends:.5,crossings:2});var uh=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,dh=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),fh=(e,t)=>e?.id??String(t);function ph(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(fh(i,t))}`);return n}function mh(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===fh(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>mh(e,t,n,r,a)))]}function hh(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>fh(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=fh(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=mh(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function gh(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}function _h(e,t=[],n){let r=e.x+e.width/2,i=e.y+e.height/2,a=t.filter(e=>e.position&&e.size&&r>=e.position.x&&r<=e.position.x+e.size.width&&i>=e.position.y&&i<=e.position.y+e.size.height).sort((e,n)=>gh(n,t)-gh(e,t))[0];return a?n?.get(a.id)?.fill:void 0}var vh=e=>Z(e.label,Math.min(Df.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function yh(e,t){let n={...e.position,...e.size},r=vh(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>uh(e,t,4)))}function bh(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...dh(e)]),...r],f=Z(bf(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>uh(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:fh(null,0)}]}}function xh(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,f=r.find(t=>t.id===e.parentId);f&&!(u.x>=f.position.x+8&&u.x+u.width<=f.position.x+f.size.width-8&&u.y>=f.position.y+36&&d<=f.position.y+f.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${f.id}`);let p=new Set,m=f;for(;m&&!p.has(m.id);)p.add(m.id),m=r.find(e=>e.id===m.parentId);for(let t of r)if(t.id!==e.id&&!p.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;uh(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let h=yh(e,i);h||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let g=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!g.length){let r=bh(e,t,n,i,h);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:h}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let _=Math.max(u.y+36,h?h.y+h.height+6:0),v=e.operands.map((n,i)=>{let a=g.filter(e=>e.parentOperandId===fh(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=mh(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...dh(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(Df.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:Z(c,l,14,20).height+16+(n.body?Z(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=v[n].textHeight,n+1mh(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...dh(e)]);return b.push(...i),v.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let f=o?l[o-1]:_,p=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...dh(e)])])(i.xu.x+u.width-4||i.yp-2)&&a.push(`layout: group ${e.id} cannot contain operand ${fh(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let m=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=[...b,...r,...s,...c],g=(n,r,l)=>{let d=r===`body`?16:14,f=r===`body`?24:20,m=Z(n,Math.min(Df.labelWidth,Math.max(1,u.width-40)),d,f),g={width:m.width+8,height:m.height+4},_=[u.x+16,...h.map(e=>e.x+e.width+8),u.x+u.width-g.width-16],v=[l,...h.map(e=>e.y+e.height+8),i-g.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>_.map(t=>({x:t,y:e,...g}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=p-6&&!h.some(t=>uh(e,t,2)));return v?(v.lines=m.lines,v.fontSize=d,v.lineHeight=f,v.operandId=fh(t,o),h.push(v),(r===`guard`?s:c).push(v)):a.push(`layout: group ${e.id} has no room for ${r} ${fh(t,o)}; adjust frame/message spacing`),v},v=g(m,`guard`,f+6);t.body&&g(t.body,`body`,v?v.y+v.height+8:f+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:h}}function Sh(e,t,n=0,r=0,i=`currentColor`,a=`var(--canvas)`){return e.separators.map(e=>``).join(``)+[...e.guards,...e.bodies??[]].map(i=>`${i.lines.map((e,t)=>Q(i.x+n+4,i.y+r+(i.fontSize===16?18:16)+t*(i.lineHeight??20),e,i.fontSize===16?`body`:`group`)).join(``)}`).join(``)}function Ch(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wh(e,t,n=Ch(e),r=ph(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}var Th=140,Eh=54,Dh=(e,t)=>(e.route?.messageY??Th+e.order*Eh)+(t===`receive`&&e.source===e.target?30:0);function Oh(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Dh(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ph(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Dh(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Dh(n.get(i.end.edgeId),i.end.at)-l}})}function Ah(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}var jh=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),Mh=(e,t,n)=>$(t)?.edgeLabel?.(e,n)??e.label??``;function Nh(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Ph(e,t=Yh(e)){e=Tf(e);let n=[...bg(e),...e.groups??[],...e.nodes,...kh(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if($(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[Nh(n.sourceCardinality,e.points[0],e.points[1]),Nh(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function Fh(e,t,n=0,r=`architecture`){let i=$(r)?.anchor;if(i)return i(e,t,n);let a=jh(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Ih(e,t,n=Ef.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Lh(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Rh(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function zh(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Bh(e,t,n,r){let i={clearance:-1,length:-1,point:zh(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Vh(e,t){let n=jh(e),r=jh(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function Hh(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?tg(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[d]===e[d]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let f=[e,Ih(e,n,a)];[`left`,`right`].includes(n)&&i.length&&f[1].y!==i[0].y&&f.push({x:f[1].x,y:i[0].y});for(let e of i)Rh(f,e);return Rh(f,Ih(t,r,a)),f.push(t),Lh(f)}function Wh(e,t,n,r,i,a=Ef.endpoint,o=`architecture`){let s=Fh(e,n.sourceSide,r,o),c=Fh(t,n.targetSide,i,o),l=Ih(s,n.sourceSide,a),u=Ih(c,n.targetSide,a),d=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+d;return Lh([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let f=(l.y+u.y)/2+d;return Lh([s,l,{x:l.x,y:f},{x:u.x,y:f},u,c])}function Gh(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Kh(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}var qh=(e,t=0,n=0)=>e.curved&&Kh(e,t,n)||Gh(e.points,t,n);function Jh(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Dh(e,`send`),u=Dh(e,`receive`),d=Ah(o,t.id,e,`send`,l,s.get(e.id)),f=Ah(o,n.id,e,`receive`,u,s.get(e.id)),p=t.id===n.id||jh(t).x<=jh(n).x,m=d?d.x+(p?d.width:0):jh(t).x,h=f?f.x+(t.id===n.id||!p?f.width:0):jh(n).x,g=wh(a,e,c,s),_=Math.abs(h-m),v=Dp(g,t.id===n.id?Df.labelWidth:Math.min(Df.labelWidth,Math.max(1,_-32-12))),y=t.id===n.id?null:Dp(g,Math.max(1,_-64)),b=y&&(e.route?.labelAt??{x:(m+h)/2,y:l-6-y.height/2}),x=y&&y.lines.lengthuh({x:b.x-y.width/2,y:b.y-y.height/2,width:y.width,height:y.height},e,2))?y:v,S={width:x.width,height:x.height};if(t.id===n.id){let t=48+r*Ef.parallelGap,n={x:m,y:l},i={x:h,y:u},a=e.route?.via?.length?Uh(n,i,`right`,`right`,e.route.via):[n,{x:m+t,y:l},{x:m+t,y:l+30},i];return{points:a,label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+S.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Uh({x:m,y:l},{x:h,y:l},m<=h?`right`:`left`,m<=h?`left`:`right`,e.route.via):[{x:m,y:l},{x:h,y:l}],label:g,labelLines:x.lines,labelSize:S,labelPoint:e.route?.labelAt??{x:(m+h)/2,y:l-6-S.height/2},sourceSide:m<=h?`right`:`left`,targetSide:m<=h?`left`:`right`}}function Yh(e){e=Tf(e);let t=eh(e),n=$(t).endpointStub??Ef.endpoint,r=new Map(e.nodes.map(e=>[e.id,e])),i=e.edges.map(e=>{let t=r.get(e.source),n=r.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Vh(t,n)}}),a=t===`sequence`?{graph:e,executions:kh(e),scopes:ph(e),pairs:Ch(e)}:null,o=new Map;for(let e of i.filter(e=>!$(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,s=e.orientation===`horizontal`?jh(i).y:jh(i).x;o.has(a)||o.set(a,[]),o.get(a).push({id:e.edge.id,role:t,coordinate:s})}let s=new Map;for(let e of o.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>s.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*Ef.parallelGap));let c=new Map,l=new Map;for(let e of i.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function Zh(e,t){return $(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,mm(e))}:{...e.position,...e.size}}function Qh(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function $h(e,t,n,r){let i=tg(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=jh(t),o=Fh(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function eg(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&eg(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=jh(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=Fh(n,`left`,o,r).x,c=Fh(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=Fh(n,`top`,o,r).y,c=Fh(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function sg(e){e=Tf(e);let t=eh(e),n=[],r=Yh(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...kh(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightuh(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=$(t).cardLayout&&!nh(e);if($(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:xp.minHeight))continue;let{minHeight:r}=t===`architecture`&&Cg(n)?Tg(n):Tp(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;eEf.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${Ef.endpoint}px`);let f=og(o,l,s,u);f.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:f.length,required:null,bounds:f.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,f.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!$(t).sequence&&(!$h(i.points[0],a,i.sourceSide,t)||!$h(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),$(t).cardinalities){let r=$(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Ih(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if($(t).sequence&&n.source!==n.target){let e=Math.abs(jh(a).x-jh(o).x),t=Math.max(160,i.labelBox.width+32);eXh(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),rg(t).some(([e,t])=>eg(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Xh(i.labelBox,tg(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=rg(r);for(let i=1;ieg(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>ag(a,o,e,t)>Ef.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}var cg=e=>({node:ff(e)?6:12,preferred:ff(e)?8:24,boundary:6}),lg=(e,t,n)=>Math.max(t,Math.min(n,e)),ug=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=lg(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function dg(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(ug(e,n,r),ug(t,n,r),ug(n,e,t),ug(r,e,t))}function fg(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function pg(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function mg(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:lg(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:lg((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>ug({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>dg(e,t,r,n[(i+1)%n.length])))}var gg=new WeakMap;function _g(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=gg.get(e);if(r?.signature===n)return r.probe;let i=$(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Hm(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,Z(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,ug({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>dg(e,a,t,n)),...i.map(t=>fg(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>mg(t,n,e);else if(s===`polygon`){let e=c.points.split(/\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>hg(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,ug({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>pg(e,t,c);else{let n=s===`rect`?c:tg(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,fg(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),fg(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},gg.set(e,{signature:n,probe:l}),l}function vg(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return rg(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function yg(e,t,n=[]){let r=new Set(n),i=eh(t),a=cg(t).node,o=t.nodes.filter(t=>JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=Zh(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=Yh(e),d=kf($(i)).labelGap,f=[...o.map(e=>Zh(e,i)),...l.flatMap(ig)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>eg(r,e,t))||l.some(n=>vg(r,e,n).distanceeg(r,e,t)))}))&&r.add(n.id)}return r}var bg=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},xg=e=>e&&typeof e==`object`&&!Array.isArray(e),Sg=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Cg=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function wg(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=ff(e),o=(e,t)=>{e!==void 0&&!zf.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{xg(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Sg(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!xg(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let c=new Map(e.nodes.map(e=>[e.id,e])),l=new Map((e.groups??[]).map(e=>[e.id,e])),u=new Set,d=new Set,f=new Set,p=e=>{c.has(e)?u.has(e)?i.push(`section repeats node ${e}`):u.add(e):i.push(`section nodeId does not name a node: ${e}`)},m=(t,n=new Set)=>{if(!l.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||f.has(t)){i.push(`section repeats or cycles group ${t}`);return}f.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>p(e.id)),[...l.values()].filter(e=>e.parentId===t).forEach(e=>m(e.id,r))},h=(e,n=0)=>{if(!xg(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||d.has(e.id)||c.has(e.id)||l.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),d.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Sg(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!c.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!xg(e.position)||!xg(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Sg(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!xg(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?h(t,n+1):m(t.groupId):p(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>h(e));for(let e of c.keys())u.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Tg(e,t=e.size.width){let n=e.overviewTone===`plain`?0:Y.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>Z(e.label,r*.45-16,Y.badge,Y.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=Z(r.label,a-16,Y.badge,Y.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=Z(e.label,r-(a?a+10:0),Y.title,Y.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+Y.title+t*Y.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&Z(e.subtitle,1/0,Y.body,Y.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+Y.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=Z(t,r,Y.body,Y.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+Y.body+t*Y.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}var Eg=e=>e.frame===`none`?0:Y.padding,Dg=(e,t)=>{let n=t-Eg(e)*2;return Eg(e)+Z(e.title,n,Y.sectionTitle,Y.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+Z(t,n,Y.body,Y.bodyLine).height,0)};function Og(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Eg(e),n=e.position.x+t,r=e.size.width-t*2,i=Z(e.title,r,Y.sectionTitle,Y.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*Y.sectionLine,width:Z(r,1/0,Y.sectionTitle,Y.sectionLine).width,height:Y.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=Z(t,r,Y.body,Y.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*Y.bodyLine,width:Z(e,1/0,Y.body,Y.bodyLine).width,height:Y.bodyLine}))),o+=e.height}return a}function kg(e,t,n){let r=structuredClone(e),i=r.nodes.find(e=>e.id===t);if(!i)return r;let a=bg(r).find(e=>e.items?.some(e=>e.nodeId===t));if(a){let e=a.items.filter(e=>e.nodeId).map(e=>r.nodes.find(t=>t.id===e.nodeId)).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=a.items.findIndex(e=>e.nodeId===t),r=a.items.findIndex(t=>t.nodeId===e.id);a.items.splice(r,0,a.items.splice(n,1)[0])}}else if(i.groupId){let e=r.nodes.filter(e=>e.groupId===i.groupId).sort((e,t)=>Math.hypot(e.position.x-n.x,e.position.y-n.y)-Math.hypot(t.position.x-n.x,t.position.y-n.y))[0];if(e&&e.id!==t){let n=r.nodes.findIndex(e=>e.id===t),i=r.nodes.findIndex(t=>t.id===e.id);r.nodes.splice(i,0,r.nodes.splice(n,1)[0])}}return r}var Ag=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),jg=(e,t,n,r,i=``)=>`${Ag(n)}`;function Mg(e,t,n,r){let i=Hf(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Tg(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>jg(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?Y.title:Y.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>jg(t+e.x+8,n+e.y+3+Y.badge+i*Y.badgeLine,r,`meta`,`fill:${o.ink};font-size:${Y.badge}px;font-weight:600`)).join(``)}`}).join(``)}function Ng(e,t,n=0,r=0){let i=Hf(t),a=i[e.tone??`white`]??i.white,o=e.position.x+n,s=e.position.y+r,c=e.size.width,l=Eg(e),u=Z(e.title,c-l*2,Y.sectionTitle,Y.sectionLine),d=s+l+u.height,f=``;for(let t of e.text??[]){d+=8;let e=Z(t,c-l*2,Y.body,Y.bodyLine);f+=e.lines.map((e,t)=>jg(o+l,d+Y.body+t*Y.bodyLine,e,`body`,`fill:${i.body};font-size:${Y.body}px`)).join(``),d+=e.height}let p=`overview-band-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,m=a.band&&e.frame!==`none`?``:``,h=e.frame===`none`?``:``;return`${m}${h}${u.lines.map((e,t)=>jg(o+l,s+l+Y.sectionTitle+t*Y.sectionLine,e,`title`,`fill:${i.ink};font-size:${Y.sectionTitle}px;font-weight:700`)).join(``)}${f}`}function Pg(e,t=new Map){if(!ff(e))return[];let n=[],r=bg(e);for(let t of r){let r=Dg(t,t.size.width)+Eg(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Eg(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Eg(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Og(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function Fg(e,t,n=0,r=0,i,a,o){let s=$(t);if(!s)throw Error(`Unsupported diagram type: ${t}`);let c=ip(e,i,o),{fill:l,stroke:u,ring:d}=c,f=e.position.x+n,p=e.position.y+r,m=s.render({...e,appearance:c},f,p,l,u,i,a),h=d&&![`actor`,`initial`,`final`].includes(e.kind)?Ip(s.outline(e,f,p),{class:`role-ring`,fill:`none`,stroke:d,"stroke-width":5}):``,g=[e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).map(e=>`${e.key?e.key+` `:``}${e.name}: ${e.type}${e.nullable===void 0?``:` (nullable: ${e.nullable})`}`),...e.attributes??[],...e.methods??[]].filter(Boolean).join(` -`);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}var zg=e=>Array.isArray(e.meta?.sourceDrift)?e.meta.sourceDrift:[],Bg=e=>new Set(zg(e).flatMap(e=>Array.isArray(e?.elements)?e.elements:[]));function Vg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function Hg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${e.drifted?`is-drifted`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(Vg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Ug({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` -`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Wg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Gg({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Wg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Wg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan${r.drifted?` is-drifted`:``}`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Kg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var qg={diagram:Hg,boundary:Ug,overview:Kg},Jg={routed:Gg};function Yg(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e])),a=Bg(e);return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r,drifted:a.has(n.id)},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function Xg(e,t){let n=Bg(e);return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t,drifted:n.has(e.id)}}))}var Zg=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function Qg(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var $g='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`,"Source changes":`源码变化`,"Show source changes":`显示源码变化`,"Hide source changes":`隐藏源码变化`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`,"Source changes":`ソースの変更`,"Show source changes":`ソースの変更を表示`,"Hide source changes":`ソースの変更を隠す`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`,"Source changes":`소스 변경`,"Show source changes":`소스 변경 표시`,"Hide source changes":`소스 변경 숨기기`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`,"Source changes":`Quellcode-Änderungen`,"Show source changes":`Quellcode-Änderungen anzeigen`,"Hide source changes":`Quellcode-Änderungen ausblenden`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`,"Source changes":`Modifications du code`,"Show source changes":`Afficher les modifications du code`,"Hide source changes":`Masquer les modifications du code`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`,"Source changes":`Cambios en el código`,"Show source changes":`Mostrar cambios en el código`,"Hide source changes":`Ocultar cambios en el código`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости","Source changes":"Изменения в коде","Show source changes":"Показать изменения в коде","Hide source changes":"Скрыть изменения в коде"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`,"Source changes":`Alterações no código`,"Show source changes":`Mostrar alterações no código`,"Hide source changes":`Ocultar alterações no código`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t,{keepColumns:n=!1}={}){let r=structuredClone(e),i=r.groups??[],a=new Map(r.edges.map(e=>[e.id,e])),o=new Map,s=r.nodes.every(e=>e.position);for(let e of[...r.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])o.has(t)||o.set(t,o.size);let c=e=>s?e.position.x:o.get(e.id)??1/0,l=(r.layout?.participantOrder??[...r.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||c(e)-c(t)||(e.ide.id)).map(e=>r.nodes.find(t=>t.id===e)),u=d.nodeGap+t*8,p=12+t*4,m=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=(e,t)=>A(m(e,t),f.labelWidth,14,20),g=e=>A(e.body,f.labelWidth,16,24),_=32;for(let e of l){let t=n&&s?e.position.x:_;e.size=Hr(e,`sequence`,r.meta.locale),e.position={x:Math.max(_,t),y:48},_=e.position.x+e.size.width+u}Tt(r,l);for(let e of r.edges)e.route={messageY:200+e.order*100};let v=H(r),y=Ot(r),b=new Set(i.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).order),S=e=>e.edge?e.edge.order:Math.min(1/0,...x(e.group)),C=e=>e.sort((e,t)=>S(e)-S(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),w=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>v.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),T=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=i.find(e=>e.id===n.parentId)){t.add(n.id);let e=w(n);if(e.length)return e}return[...v.values()].flatMap(e=>e.points)};for(let e of[...i].sort((e,t)=>vt(t,i)-vt(e,i)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=T(e),n=i.filter(t=>t.parentId===e.id),r=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[h(e,t).width,g(t).width])),o=e.operands.flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).route.messageY),s=Math.min(...o),c=Math.max(...o),u=y.filter(e=>!o.length||e.y<=c&&e.y+e.height>=s).sort((e,t)=>e.x-t.x),d=t.length?Math.min(...t.map(e=>e.x)):l[0].position.x,f=Math.min(d,...u.filter(e=>e.x=d-8).map(e=>e.x))-r-40,p=Math.min(f,...n.map(e=>e.position.x-32)),m=Math.max(p+r+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of u)e.xm-56-16&&(m=Math.max(m,e.x+e.width+56));e.position={x:p,y:0},e.size={width:Math.ceil(m-p),height:0}}function ee(e,t){let n=v.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+p}function E(e,t){for(let n of C(e))t=n.edge?ee(n.edge,t):te(n.group,t);return t}function te(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+p;for(let[t,r]of e.operands.entries()){n+=h(e,r).height+16,r.body&&(n+=g(r).height+16);let o=i.filter(n=>n.parentId===e.id&&n.parentOperandId===z(r,t));n=E([...r.edgeIds.map(e=>({edge:a.get(e)})),...o.map(e=>({group:e}))],n),n+=p}return e.size.height=n-t+16,t+e.size.height+p}let ne=E([...r.edges.filter(e=>!b.has(e.id)).map(e=>({edge:e})),...i.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...l.map(Ke))+d.labelGap),re=[...r.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...l.map(e=>e.position.x)));for(let e of[...l,...i])e.position.x+=D;for(let e of r.nodes)e.size.height=ne+32-e.position.y;return r}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',e_=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,$g],{type:`text/javascript;charset=utf-8`});function t_(e){let t;try{if(t=e_&&(self.URL||self.webkitURL).createObjectURL(e_),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent($g),{name:e?.name})}}var n_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),r_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function i_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=n_(e.label,X.title),a=n_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return r_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>n_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return r_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=n_(e.name,X.body),n=n_(e.type,X.body);return Math.max(t+n+74,n/.55)});return r_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return r_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>n_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,n_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,r_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return r_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var a_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o_(e){return e.layout?.tier?a_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var s_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),c_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function l_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function u_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function d_(e,t,n){l_(e.file,`${t}.file`,n),u_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function h_(e,t){m_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function g_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!c_(e))return[`graph must be an object`];c_(e.meta)||r.push(`meta must be an object`),l_(e.meta?.title,`meta.title`,r),l_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&l_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])u_(e.meta?.[t],`meta.${t}`,r);h_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!c_(c)){r.push(`${e} must be an object`);continue}l_(c?.id,`${e}.id`,r),l_(c?.label,`${e}.label`,r),u_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&l_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),f_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!c_(c.source)?r.push(`${e}.source must be an object`):c.source&&(d_(c.source,`${e}.source`,r),c.source.kind!==void 0&&!s_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])m_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!c_(n)){r.push(`${i} must be an object`);continue}l_(n.name,`${i}.name`,r),l_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:l_,validateStringArray:m_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!c_(s)){r.push(`${e} must be an object`);continue}l_(s?.id,`${e}.id`,r),l_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),f_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!c_(o)){r.push(`${e} must be an object`);continue}l_(o?.id,`${e}.id`,r),u_(o.label,`${e}.label`,r),o.module!==void 0&&l_(o.module,`${e}.module`,r),l_(o?.source,`${e}.source`,r),l_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),s_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!c_(o.site)?r.push(`${e}.site must be an object`):o.site&&d_(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>p_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&p_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:l_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:d_,evidenceKinds:s_})),r.length===0&&r.push(...__(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function __(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(c_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),c_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!c_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(c_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var v_=e=>({...e.position,...e.size}),y_=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,b_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function S_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` +`);return`${Np(g)}${h}${m}`}function Ig(e,t){let n=$(t);return{markup:Ip(n.outline(e,0,0)),height:n.selectionHeight?.(e)??e.size.height}}function Lg(e,t,n,r,i,a,o,s,c){let l=$(t),u={...e,position:{x:n,y:r},size:{width:i,height:a}};return Ip(l.outline(u,n,r),{fill:o,stroke:s,"stroke-width":c})}function Rg({data:e,pulse:t}){let{markup:n,height:r}=Ig(e,e.diagramType);return(0,x.jsxs)(`svg`,{className:`selection-feedback selection-outline selection-node-outline ${t>0?`is-animated`:``}`,"data-selection-pulse":t,viewBox:`0 0 ${e.size.width} ${r}`,style:{height:r},"aria-hidden":`true`,children:[(0,x.jsx)(`g`,{className:`selection-node-halo`,dangerouslySetInnerHTML:{__html:n}}),(0,x.jsx)(`g`,{className:`selection-node-shine`,dangerouslySetInnerHTML:{__html:n}})]})}var zg=e=>Array.isArray(e.meta?.sourceDrift)?e.meta.sourceDrift:[],Bg=e=>new Set(zg(e).flatMap(e=>Array.isArray(e?.elements)?e.elements:[]));function Vg(e,t){let n=t=>e.nodes.find(e=>e.id===t)?.label??t,r=(e.edges??[]).find(e=>e.id===t);return r?`${n(r.source)} → ${n(r.target)}${r.label?`: ${r.label}`:``}`:e.nodes.find(e=>e.id===t)?.label??(e.groups??[]).find(e=>e.id===t)?.label??t}var Hg=null,Ug=e=>{Hg=e},Wg=e=>Hg?.views?.[uf(e)]??null,Gg=e=>e?e.added.length+e.changed.length+e.removed.length+ +!!e.meta:0;function Kg({sequence:e=!1}){return e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left,style:{top:X.sequenceHeader,opacity:0}}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right,style:{top:X.sequenceHeader,opacity:0}})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ul,{id:`target-left`,type:`target`,position:H.Left}),(0,x.jsx)(Ul,{id:`source-left`,type:`source`,position:H.Left}),(0,x.jsx)(Ul,{id:`target-right`,type:`target`,position:H.Right}),(0,x.jsx)(Ul,{id:`source-right`,type:`source`,position:H.Right}),(0,x.jsx)(Ul,{id:`target-top`,type:`target`,position:H.Top}),(0,x.jsx)(Ul,{id:`source-top`,type:`source`,position:H.Top}),(0,x.jsx)(Ul,{id:`target-bottom`,type:`target`,position:H.Bottom}),(0,x.jsx)(Ul,{id:`source-bottom`,type:`source`,position:H.Bottom})]})}function qg({data:e,selected:t}){let n=e.moduleColors?.get(e.module),r=Fg({...e,position:{x:0,y:0}},e.diagramType,0,0,e.palette,e.locale,e.moduleColors);return(0,x.jsxs)(`article`,{className:`diagram-node diagram-${e.diagramType} kind-${e.kind} ${n?`has-module`:``} ${Yf(e)?`is-core`:``} ${e.dimmed?`is-dimmed`:``} ${e.diff?`is-${e.diff}`:``} ${e.drifted?`is-drifted`:``} ${t?`is-selected`:``}`,style:n?{"--node-module":n.accent}:void 0,title:e.label,children:[(0,x.jsx)(Kg,{sequence:$(e.diagramType).sequence}),(0,x.jsx)(`svg`,{className:`node-visual`,viewBox:`0 0 ${e.size.width} ${e.size.height}`,"aria-label":e.label,dangerouslySetInnerHTML:{__html:r}}),t&&(0,x.jsx)(Rg,{data:e,pulse:e.selectionPulse},e.selectionPulse)]})}function Jg({data:e}){let t=e.fragment,n=t?.heading?{left:t.heading.x-e.position.x,top:t.heading.y-e.position.y,maxWidth:t.heading.width}:void 0,r=[`alt`,`opt`,`loop`,`par`].includes(e.kind);return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`section`,{className:`boundary boundary-${e.kind}`,"aria-label":e.label,children:[(0,x.jsx)(`svg`,{className:`boundary-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Mp(e,e.appearance)}}),t?(0,x.jsx)(`span`,{style:n,children:t.heading?.lines?.join(` +`)??e.label}):(0,x.jsx)(`svg`,{className:`boundary-heading`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:jp(e)}}),r&&!t&&(0,x.jsx)(`small`,{children:e.kind}),t&&(0,x.jsx)(`svg`,{className:`fragment-visual`,width:`100%`,height:`100%`,dangerouslySetInnerHTML:{__html:Sh({...t,guards:[],bodies:[]},e,-e.position.x,-e.position.y)}})]}),t&&(0,x.jsx)(J,{children:(0,x.jsxs)(`div`,{className:`fragment-overlay`,style:{position:`absolute`,pointerEvents:`none`,width:e.size.width,height:e.size.height,transform:`translate(${e.position.x}px, ${e.position.y}px)`},children:[(0,x.jsx)(`svg`,{className:`fragment-text`,width:e.size.width,height:e.size.height,dangerouslySetInnerHTML:{__html:Sh({...t,separators:[]},e,-e.position.x,-e.position.y,`currentColor`,e.appearance?.fill??`var(--canvas)`)}}),r&&(0,x.jsx)(`small`,{children:e.kind})]})})]})}function Yg({value:e,point:t,neighbor:n,color:r}){let i=Nh(e,t,n);return(0,x.jsxs)(`g`,{className:`cardinality-mark`,stroke:r,strokeWidth:`1.5`,fill:`none`,children:[(0,x.jsx)(`path`,{d:i.path}),i.circle&&(0,x.jsx)(`circle`,{...i.circle,fill:`var(--canvas)`})]})}function Xg({id:e,markerEnd:t,style:n,data:r}){let{route:i}=r,a=$(r.diagramType).sequence,o=r.directed&&r.flowRunning,s=`sequence-flow-${(0,y.useId)().replaceAll(`:`,``)}`,c=i.points.map(e=>e.x),l=i.points.map(e=>e.y),u={x:Math.min(...c)-32,y:Math.min(...l)-32,width:Math.max(64,Math.max(...c)-Math.min(...c)+64),height:Math.max(64,Math.max(...l)-Math.min(...l)+64)},d=$(r.diagramType).cardinalities,f=oh(r,r.diagramType),p=f.end===`arrow`?t:f.end?`url(#codegraph-${f.end})`:void 0,m=f.start?`url(#codegraph-${f.start})`:void 0;return(0,x.jsxs)(x.Fragment,{children:[a&&r.dashed&&o&&(0,x.jsx)(`defs`,{children:(0,x.jsx)(`mask`,{id:s,maskUnits:`userSpaceOnUse`,maskContentUnits:`userSpaceOnUse`,...u,children:(0,x.jsx)(`path`,{d:i.path,fill:`none`,stroke:`white`,strokeWidth:`3.2`,strokeDasharray:`5 5`})})}),r.selectionLinked&&(0,x.jsxs)(`g`,{className:`selection-feedback ${o?`has-flow`:``} ${r.selectionPulse>0?`is-animated`:``}`,"data-selection-pulse":r.selectionPulse,style:{stroke:r.selectionColor},children:[(0,x.jsx)(`path`,{className:`selection-edge-halo`,d:i.path}),(0,x.jsx)(`path`,{className:`selection-edge-shine`,d:i.path})]},`${r.selectionId}:${r.selectionPulse}`),(0,x.jsx)(Cu,{id:e,path:i.path,markerEnd:p,markerStart:m,style:{...n,strokeOpacity:1}}),r.directed&&o&&(0,x.jsx)(`path`,{className:`edge-flow ${a?`sequence-edge-flow`:``}`,d:i.path,mask:a&&r.dashed?`url(#${s})`:void 0,style:{stroke:n.stroke}}),d&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Yg,{value:r.sourceCardinality,point:i.points[0],neighbor:i.points[1],color:r.relationColor}),(0,x.jsx)(Yg,{value:r.targetCardinality,point:i.points.at(-1),neighbor:i.points.at(-2),color:r.relationColor})]}),(i.endpointLabels??[]).map(e=>(0,x.jsxs)(`g`,{className:`edge-multiplicity`,"data-endpoint":e.role,children:[(0,x.jsx)(`rect`,{...e.labelBox,rx:`4`,fill:`var(--canvas)`}),(0,x.jsx)(`text`,{x:e.labelPoint.x,y:e.labelBox.y+3+X.body,fontSize:X.body,fontWeight:`500`,textAnchor:`middle`,fill:r.labelColor,children:e.label})]},e.role)),i.label&&(0,x.jsx)(J,{children:(0,x.jsx)(`button`,{type:`button`,className:`edge-label nodrag nopan${r.diff?` is-${r.diff}`:``}${r.drifted?` is-drifted`:``}`,"data-edge-id":e,onClick:e=>{e.stopPropagation(),r.onSelect()},onKeyDown:e=>{[`Enter`,` `].includes(e.key)&&(e.stopPropagation(),e.repeat&&e.preventDefault())},style:{width:i.labelBox.width,height:i.labelBox.height,color:r.labelColor,background:r.labelSurface,fontWeight:r.selectionLinked?650:500,transform:`translate(-50%, -50%) translate(${i.labelPoint.x}px, ${i.labelPoint.y}px)`},children:i.labelLines.map((e,t)=>(0,x.jsx)(`span`,{children:i.labelRuns?i.labelRuns[t].map((e,t)=>(0,x.jsx)(`span`,{style:{color:r.roleColors?.[e.role]},children:e.text},t)):t===0&&r.pair&&e.startsWith(r.pair.label)?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`b`,{className:`pair-label`,style:{borderColor:n.stroke},children:r.pair.label}),e.slice(r.pair.label.length)]}):e},t))})})]})}function Zg({data:e}){return(0,x.jsxs)(`section`,{className:`overview-section`,children:[(0,x.jsx)(`svg`,{className:`node-visual`,width:e.size.width,height:e.size.height,"aria-label":e.title,dangerouslySetInnerHTML:{__html:Ng(e,e.palette,-e.position.x,-e.position.y)}}),(0,x.jsx)(`button`,{className:`overview-section-select nodrag nopan`,onClick:t=>{t.stopPropagation(),e.onSelect?.()},"aria-label":e.title,children:e.title})]})}var Qg={diagram:qg,boundary:Jg,overview:Zg},$g={routed:Xg};function e_(e){let t=Wg(e);return e=>t?.added.includes(e)?`added`:t?.changed.includes(e)?`changed`:void 0}function t_(e,t){let n=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(t=>({id:t.id,type:`boundary`,position:t.position,data:{...t},style:{width:t.size.width,height:t.size.height,pointerEvents:`none`},selectable:!1,draggable:!1,connectable:!1,zIndex:-(e.groups?.length??0)+gh(t,e.groups??[])})),r=!nh(e),i=new Map(Tf(e).nodes.map(e=>[e.id,e])),a=Bg(e),o=e_(e);return[...bg(e).map((e,t)=>({id:e.id,type:`overview`,position:e.position,data:{...e},style:{width:e.size.width,height:e.size.height,pointerEvents:`none`},draggable:!1,selectable:!1,zIndex:-100+t})),...n,...e.nodes.map(n=>({id:n.id,type:`diagram`,className:t===`sequence`?`sequence-column`:void 0,position:n.position,data:{...i.get(n.id),diagramType:t,locale:e.meta.locale,classicCard:r,drifted:a.has(n.id),diff:o(n.id)},style:{width:n.size.width,height:n.size.height,...t===`sequence`?{pointerEvents:`none`}:{}},zIndex:2}))]}function n_(e,t){let n=Bg(e),r=e_(e);return wf(e).map(e=>({id:e.id,source:e.source,target:e.target,type:`routed`,zIndex:t===`sequence`?3:0,markerEnd:rh(e,t)?{type:Da.ArrowClosed}:void 0,data:{...e,diagramType:t,drifted:n.has(e.id),diff:r(e.id)}}))}var r_=e=>`linear-gradient(90deg, ${e.map((t,n)=>`${t} ${n/e.length*100}% ${(n+1)/e.length*100}%`).join(`, `)})`;function i_(e,t,n){e=Tf(e);let r=$(e.meta.diagramType),i=new Map,a=new Map;for(let o of e.nodes){let e=ip(o,t,n),s=e.role===`flight`?`ramp`:o.kind===`actor`?`actor`:[`initial`,`final`].includes(o.kind)?o.kind:r.compartments?`compartment`:`box`,c=`${e.role}-${s}`;s===`ramp`&&a.set(e.toneIndex,e.stroke),i.set(c,{id:c,...e,label:r.legend?.[e.role]??e.label,shape:s})}a.size&&(i.get(`flight-ramp`).ramp=[...new Set([...a].sort(([e],[t])=>e-t).map(([,e])=>e))]);for(let t of[...new Set([...e.nodes.map(e=>e.module),...e.edges.map(e=>e.module)].filter(Boolean))].sort()){let e=n?.get(t);e&&i.set(`module-${t}`,{id:`module-${t}`,role:`module`,label:t,shape:`module`,fill:e.chip,stroke:e.accent})}if(e.edges.some(t=>!ih(t,e.meta.diagramType))&&i.set(`solid`,{id:`solid`,label:r.legend?.solid??`Solid relation`,shape:`solid`,stroke:t.edge}),e.edges.some(t=>ih(t,e.meta.diagramType))&&i.set(`dashed`,{id:`dashed`,label:`Dashed: notation / convention / inference`,shape:`dashed`,stroke:t.edge}),r.curvedSelfLoops&&e.edges.some(e=>e.source===e.target)&&i.set(`self`,{id:`self`,label:`Self-transition: handled without leaving the state`,shape:`self`,stroke:t.edge}),r.sequence)for(let[n,r]of[[`sync`,`Synchronous message`],[`async`,`Asynchronous message`],[`return`,`Return message`]])e.edges.some(e=>e.kind===n)&&i.set(n,{id:n,label:r,shape:n,stroke:t.edge});return r.sequence&&e.executions?.length&&i.set(`execution`,{id:`execution`,label:`Activation: execution interval; offset means nesting`,shape:`execution`,fill:t.accentSoft,stroke:t.accent}),r.sequence&&e.edges.some(e=>e.replyTo)&&i.set(`pair`,{id:`pair`,label:`C ID: paired call and return share a color`,shape:`solid`,stroke:t.accent}),r.sequence&&e.groups?.some(e=>e.kind===`par`)&&i.set(`parallel`,{id:`parallel`,label:`par: concurrent branches; vertical position is not order`,shape:`dashed`,stroke:t.edge}),[...i.values()].map(t=>({...t,label:bf(e.meta.locale,t.label)}))}var a_='(function(){let e=`templates-v4-clearance-compact-elkjs-0.11.0`,t=e=>/^templates-v([4-9]|\\d{2,})-/.test(e.layout?.version??``),n=e=>/^templates-v([3-9]|\\d{2,})-/.test(e.layout?.version??``),r=e=>/^templates-v([2-9]|\\d{2,})-/.test(e.layout?.version??``),i=Object.freeze({bends:.5,crossings:2}),a=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function o(e){return e.layout?.tier?a.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}let s=e=>e?.meta?.architectureView??`relations`,c=e=>(e?.meta?.diagramType??`architecture`)===`architecture`&&s(e)!==`relations`,l={relations:`Component relationship architecture`,capabilities:`Platform capability architecture`,engineering:`Engineering layer architecture`};Object.freeze([{id:`capabilities`,type:`architecture`,label:l.capabilities},{id:`engineering`,type:`architecture`,label:l.engineering},{id:`relations`,type:`architecture`,label:l.relations},{id:`flowchart`,type:`flowchart`,label:`Flowchart`},{id:`sequence`,type:`sequence`,label:`Sequence`},{id:`er`,type:`er`,label:`ER diagram`},{id:`deployment`,type:`deployment`,label:`Deployment`},{id:`class`,type:`class`,label:`Class diagram`},{id:`state`,type:`state`,label:`State diagram`},{id:`usecase`,type:`usecase`,label:`Use cases`},{id:`dataflow`,type:`dataflow`,label:`Data flow`}]);let u=e=>(e?.meta?.diagramType??`architecture`)===`architecture`?s(e):e.meta.diagramType,d=Object.freeze({nodeGap:48,labelGap:24,labelEdgeGap:6,groupHeadingGap:24,groupInset:32,groupGap:48,endpoint:12,parallelGap:24}),f=Object.freeze({nodeGap:64,layerGap:80,edgeNodeGap:24,labelWidth:320,headingWidth:360}),p=Object.freeze({...d,nodeGap:32,groupInset:24,groupGap:32}),m=Object.freeze({...f,nodeGap:40,layerGap:48}),h=e=>e?.cardLayout?p:d,g=e=>e?.cardLayout?m:f;Object.freeze({width:1392,height:688});let _=[`er`,`deployment`,`dataflow`,`usecase`],v=e=>e===`architecture`||e===`deployment`?[`down`,`right`]:[_.includes(e)?`right`:`down`],y=(e,t)=>(t?.direction??v(e)[0])===`down`;function b(e){let t=new Map,n=e.groups??[],r=(t,i=new Set)=>{if(i.has(t))return[];let a=new Set([...i,t]);return[...e.nodes.filter(e=>e.groupId===t).map(e=>e.id),...n.filter(e=>e.parentId===t).flatMap(e=>r(e.id,a))]},i=e=>{for(let n of e.items??[])if(n.mode)i(n);else for(let i of n.nodeId?[n.nodeId]:r(n.groupId))t.set(i,e.id)};return(e.layout?.sections??[]).forEach(i),t}let x=e=>!c(e)&&(e.meta?.diagramType??`architecture`)===`architecture`&&Array.isArray(e.layout?.sharedDependencies)&&e.layout.sharedDependencies.length?new Set(e.layout.sharedDependencies):null,S=e=>!!x(e);function C(e){let t=x(e);return t?e.edges.filter(e=>t.has(e.target)&&e.source!==e.target):[]}function w(e){let t=x(e);if(t)return e.edges.filter(e=>!t.has(e.target)||e.source===e.target);if(!c(e)||e.layout?.overviewConnections===`all`)return e.edges;let n=b(e);return e.edges.filter(e=>n.has(e.source)&&n.get(e.source)===n.get(e.target))}function T(e){if(!x(e))return{...e,edges:w(e)};let t=new Map(e.nodes.map(e=>[e.id,e.label])),n=new Map;for(let r of C(e))n.set(r.source,[...new Set([...n.get(r.source)??[],`→ ${t.get(r.target)}`])]);let{sharedDependencies:r,...i}=e.layout;return{...e,layout:i,edges:w(e),nodes:e.nodes.map(e=>n.has(e.id)?{...e,dependencyTags:n.get(e.id)}:e)}}function ee(e,t){let n=new Map(t.edges.map(e=>[e.id,e]));return e.edges.map(e=>n.get(e.id)??e)}function E(e,t){let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map(t.edges.map(e=>[e.id,e]));return{...t,layout:{...t.layout,sharedDependencies:e.layout.sharedDependencies},nodes:e.nodes.map(e=>{let{dependencyTags:t,...r}=n.get(e.id)??e;return r}),edges:e.edges.map(e=>{if(r.has(e.id))return r.get(e.id);let{route:t,...n}=e;return n})}}let te={light:{neutral:[null,`#fcfcfd`,`#f9f9fb`,`#f0f0f3`,`#e8e8ec`,`#e0e1e6`,`#d9d9e0`,`#cdced6`,`#b9bbc6`,`#8b8d98`,`#80838d`,`#60646c`,`#1c2024`],accent:[null,`#fdfdff`,`#f8f8ff`,`#f0f1fe`,`#e6e7ff`,`#dadcff`,`#cbcdff`,`#b8baf8`,`#9b9ef0`,`#5b5bd6`,`#5151cd`,`#5753c6`,`#272962`],data:[null,`#fafdfe`,`#f2fafb`,`#def7f9`,`#caf1f6`,`#b5e9f0`,`#9ddde7`,`#7dcedc`,`#3db9cf`,`#00a2c7`,`#0797b9`,`#107d98`,`#0d3c48`],warn:[null,`#fffcfc`,`#fff7f7`,`#feebec`,`#ffdbdc`,`#ffcdce`,`#fdbdbe`,`#f4a9aa`,`#eb8e90`,`#e5484d`,`#dc3e42`,`#ce2c31`,`#641723`],guard:[null,`#fefdfb`,`#fefbe9`,`#fff7c2`,`#ffee9c`,`#fbe577`,`#f3d673`,`#e9c162`,`#e2a336`,`#ffc53d`,`#ffba18`,`#ab6400`,`#4f3422`]},dark:{neutral:[null,`#111113`,`#18191b`,`#212225`,`#272a2d`,`#2e3135`,`#363a3f`,`#43484e`,`#5a6169`,`#696e77`,`#777b84`,`#b0b4ba`,`#edeef0`],accent:[null,`#13131e`,`#171625`,`#202248`,`#262a65`,`#303374`,`#3d3e82`,`#4a4a95`,`#5958b1`,`#5b5bd6`,`#6e6ade`,`#b1a9ff`,`#e0dffe`],data:[null,`#0b161a`,`#101b20`,`#082c36`,`#003848`,`#004558`,`#045468`,`#12677e`,`#11809c`,`#00a2c7`,`#23afd0`,`#4ccce6`,`#b6ecf7`],warn:[null,`#191111`,`#201314`,`#3b1219`,`#500f1c`,`#611623`,`#72232d`,`#8c333a`,`#b54548`,`#e5484d`,`#ec5d5e`,`#ff9592`,`#ffd1d9`],guard:[null,`#16120c`,`#1d180f`,`#302008`,`#3f2700`,`#4d3000`,`#5c3d05`,`#714f19`,`#8f6424`,`#ffc53d`,`#ffd60a`,`#ffca16`,`#ffe7b3`]}},ne=[`blue`,`orange`,`teal`,`crimson`,`violet`,`grass`,`plum`,`indigo`],re={light:{blue:[null,`#fbfdff`,`#f4faff`,`#e6f4fe`,`#d5efff`,`#c2e5ff`,`#acd8fc`,`#8ec8f6`,`#5eb1ef`,`#0090ff`,`#0588f0`,`#0d74ce`,`#113264`],orange:[null,`#fefcfb`,`#fff7ed`,`#ffefd6`,`#ffdfb5`,`#ffd19a`,`#ffc182`,`#f5ae73`,`#ec9455`,`#f76b15`,`#ef5f00`,`#cc4e00`,`#582d1d`],teal:[null,`#fafefd`,`#f3fbf9`,`#e0f8f3`,`#ccf3ea`,`#b8eae0`,`#a1ded2`,`#83cdc1`,`#53b9ab`,`#12a594`,`#0d9b8a`,`#008573`,`#0d3d38`],crimson:[null,`#fffcfd`,`#fef7f9`,`#ffe9f0`,`#fedce7`,`#facedd`,`#f3bed1`,`#eaacc3`,`#e093b2`,`#e93d82`,`#df3478`,`#cb1d63`,`#621639`],violet:[null,`#fdfcfe`,`#faf8ff`,`#f4f0fe`,`#ebe4ff`,`#e1d9ff`,`#d4cafe`,`#c2b5f5`,`#aa99ec`,`#6e56cf`,`#654dc4`,`#6550b9`,`#2f265f`],grass:[null,`#fbfefb`,`#f5fbf5`,`#e9f6e9`,`#daf1db`,`#c9e8ca`,`#b2ddb5`,`#94ce9a`,`#65ba74`,`#46a758`,`#3e9b4f`,`#2a7e3b`,`#203c25`],plum:[null,`#fefcff`,`#fdf7fd`,`#fbebfb`,`#f7def8`,`#f2d1f3`,`#e9c2ec`,`#deade3`,`#cf91d8`,`#ab4aba`,`#a144af`,`#953ea3`,`#53195d`],indigo:[null,`#fdfdfe`,`#f7f9ff`,`#edf2fe`,`#e1e9ff`,`#d2deff`,`#c1d0ff`,`#abbdf9`,`#8da4ef`,`#3e63dd`,`#3358d4`,`#3a5bc7`,`#1f2d5c`]},dark:{blue:[null,`#0d1520`,`#111927`,`#0d2847`,`#003362`,`#004074`,`#104d87`,`#205d9e`,`#2870bd`,`#0090ff`,`#3b9eff`,`#70b8ff`,`#c2e6ff`],orange:[null,`#17120e`,`#1e160f`,`#331e0b`,`#462100`,`#562800`,`#66350c`,`#7e451d`,`#a35829`,`#f76b15`,`#ff801f`,`#ffa057`,`#ffe0c2`],teal:[null,`#0d1514`,`#111c1b`,`#0d2d2a`,`#023b37`,`#084843`,`#145750`,`#1c6961`,`#207e73`,`#12a594`,`#0eb39e`,`#0bd8b6`,`#adf0dd`],crimson:[null,`#191114`,`#201318`,`#381525`,`#4d122f`,`#5c1839`,`#6d2545`,`#873356`,`#b0436e`,`#e93d82`,`#ee518a`,`#ff92ad`,`#fdd3e8`],violet:[null,`#14121f`,`#1b1525`,`#291f43`,`#33255b`,`#3c2e69`,`#473876`,`#56468b`,`#6958ad`,`#6e56cf`,`#7d66d9`,`#baa7ff`,`#e2ddfe`],grass:[null,`#0e1511`,`#141a15`,`#1b2a1e`,`#1d3a24`,`#25482d`,`#2d5736`,`#366740`,`#3e7949`,`#46a758`,`#53b365`,`#71d083`,`#c2f0c2`],plum:[null,`#181118`,`#201320`,`#351a35`,`#451d47`,`#512454`,`#5e3061`,`#734079`,`#92549c`,`#ab4aba`,`#b658c4`,`#e796f3`,`#f4d4f4`],indigo:[null,`#11131f`,`#141726`,`#182449`,`#1d2e62`,`#253974`,`#304384`,`#3a4f97`,`#435db1`,`#3e63dd`,`#5472e4`,`#9eb1ff`,`#d6e1ff`]}},D=Object.freeze({width:1440,margin:42,padding:22,cardPadding:18,cardGap:14,bandGap:28,connectedGap:56,cardRadius:14,sectionRadius:20,title:22,titleLine:28,body:18,bodyLine:26,badge:16,badgeLine:20,sectionTitle:24,sectionLine:30}),ie=[`white`,`subtle`,`blue`,`green`,`lavender`,`plain`],ae={paper:`#ffffff`,ink:`#242628`,body:`#566475`,line:`#e1e5e8`,edge:`#7d8798`,white:{fill:`#ffffff`,stroke:`#e1e5e8`},subtle:{fill:`#f5fafc`,stroke:`#e1e5e8`},blue:{fill:`#eef7fd`,stroke:`#87cdee`,band:[`#e5f3fb`,`#cde8f5`],accent:`#327d9f`},green:{fill:`#edf9f5`,stroke:`#a7e5d3`,band:[`#edf9f5`,`#dff4ed`],accent:`#2d8269`},lavender:{fill:`#eaf0fe`,stroke:`#aac6fd`,band:[`#edf2fe`,`#d7e4fc`],accent:`#5375aa`},badge:{fill:`#e9edf0`,ink:`#5f6a7a`},success:{fill:`#e7f5e9`,ink:`#2b763d`}},oe={paper:`#171b22`,ink:`#eef1f5`,body:`#b4bdcb`,line:`#404955`,edge:`#a8b6c9`,white:{fill:`#242b35`,stroke:`#404955`},subtle:{fill:`#222d38`,stroke:`#404955`},blue:{fill:`#223746`,stroke:`#457d9e`,band:[`#243c4d`,`#294b5f`],accent:`#8bc4e0`},green:{fill:`#203c34`,stroke:`#437d6b`,band:[`#243f37`,`#294e43`],accent:`#89cbb2`},lavender:{fill:`#2c354d`,stroke:`#657eaf`,band:[`#2f3c58`,`#364b70`],accent:`#aec6f1`},badge:{fill:`#3b4552`,ink:`#c0c9d6`},success:{fill:`#294c38`,ink:`#a6d9af`}},se=e=>parseInt(e.paper.slice(1,3),16)<128?oe:ae;function ce(e,t,n){let r=r=>Math.round(parseInt(e.slice(r,r+2),16)*n+parseInt(t.slice(r,r+2),16)*(1-n)).toString(16).padStart(2,`0`);return`#${r(1)}${r(3)}${r(5)}`}let le=[`orange`,`blue`,`teal`,`violet`,`plum`,`indigo`];Object.fromEntries(Object.entries(te).map(([e,{neutral:t,accent:n,data:r,warn:i,guard:a}])=>[e,{paper:t[1],surface:t[1],surface2:t[2],ink:t[12],ink2:t[11],ink3:t[11],rule:t[6],ruleSoft:t[4],accent:e===`dark`?`#67c4aa`:`#126b5a`,accentSoft:n[2],ringCore:n[5],data:e===`dark`?`#d9b16c`:`#886019`,warn:i[11],ringWarn:i[5],guard:a[11],badge:t[3],outline:e===`dark`?t[10]:t[9],card:e===`dark`?t[3]:t[1],groupFill:t[2],groupFillNested:e===`dark`?ce(t[2],t[3],.5):t[1],groupLine:t[5],moduleTones:(e===`dark`?[`#80b5ea`,`#67c4aa`,`#bb9add`,`#d9b16c`,`#9eafa7`]:[`#3677bb`,`#16816d`,`#8c64ac`,`#b27e2a`,`#6a7c75`]).map((n,r)=>({name:[`blue`,`teal`,`purple`,`amber`,`sage`][r],chip:n,accent:n,wash:ce(n,e===`dark`?t[3]:t[1],.09),header:ce(n,t[2],e===`dark`?.16:.09)})),sequenceTones:ne.map(t=>re[e][t][10]),stateTones:(()=>{let n=e===`dark`?10:11,r=re[e],a=e=>({name:e,fill:r[e][3],stroke:r[e][n]});return{goal:a(`grass`),ended:{name:`slate`,fill:t[3],stroke:t[n]},failed:{name:`red`,fill:i[3],stroke:i[n]},flight:le.map(a)}})(),edge:e===`dark`?t[10]:`#747982`,mask:e===`dark`?`rgba(17,17,19,.75)`:`rgba(252,252,253,.75)`,group:t[2]}]));let ue=new Set([`data`,`database`,`dataStore`,`entity`]),O={title:20,body:16,small:14,edgeLineHeight:24,sequenceHeader:72,sequenceActorHeader:108,erHeader:72,erRow:32,classHeader:68,classRow:28},de=e=>e.kind===`business`||(e.tags??[]).some(e=>[`core`,`business`].includes(String(e).trim().toLowerCase())),fe={external:`External`,config:`Configuration`,framework:`Framework`,security:`Security`,service:`Service`,business:`Business`,data:`Data`,failure:`Failure`,system:`System`,component:`Component`,database:`Database`,start:`Start`,end:`End`,process:`Process`,decision:`Decision`,input:`Input`,output:`Output`,subprocess:`Subprocess`,actor:`Actor`,participant:`Participant`,entity:`Entity`,device:`Device`,node:`Nodes`,container:`Container`,artifact:`Artifact`,class:`Class`,interface:`Interface`,abstract:`Abstract class`,state:`State`,initial:`Initial`,final:`End`,choice:`Choice`,usecase:`Use case`,dataStore:`Data store`};function pe(e){let t=Math.min(O.erHeader,e.size.height*.4),n=Math.min(O.erRow,(e.size.height-t)/Math.max(1,e.fields?.length??0));return{erHeaderHeight:t,erRowHeight:n,erFontSize:Math.max(O.small,Math.min(O.body,n-6)),classHeaderHeight:O.classHeader+(e.subtitle?24:0),classRowHeight:O.classRow}}var me={"zh-CN":{"Layout suggestions":`布局优化建议`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`整理此图可改善连线间距与布局;整理前保留现有位置。`,Architecture:`架构图`,Flowchart:`流程图`,Sequence:`时序图`,"ER diagram":`ER 图`,Deployment:`部署图`,"Class diagram":`类图`,"State diagram":`状态图`,"Use cases":`用例图`,"Data flow":`数据流图`,"Source code":`源码`,Code:`代码`,Configuration:`配置`,Schema:`数据结构`,Test:`测试`,Document:`文档`,"Framework convention":`框架约定`,Inference:`推断`,External:`外部`,Framework:`框架`,Security:`安全`,Service:`服务`,Business:`业务`,Data:`数据`,Failure:`失败`,System:`系统`,Component:`组件`,Database:`数据库`,Start:`开始`,End:`结束`,Process:`处理`,Decision:`判断`,Input:`输入`,Output:`输出`,Subprocess:`子流程`,Actor:`角色`,Participant:`参与者`,Entity:`实体`,Device:`设备`,Nodes:`节点`,Container:`容器`,Artifact:`制品`,Class:`类`,Interface:`接口`,"Abstract class":`抽象类`,State:`状态`,Initial:`初始`,Choice:`选择`,"Use case":`用例`,"Data store":`数据存储`,"Initial state":`初始状态`,"Final state":`结束状态`,"Core component":`核心组件`,"Data / storage":`数据与存储`,"Start / end":`起止节点`,"Components / actors":`普通组件 / 角色`,"Solid relation":`实线关系`,"Dashed: notation / convention / inference":`虚线:关系记法 / 框架约定 / 推断`,Reset:`重置`,Dark:`深色`,Light:`浅色`,Locked:`布局锁定`,Draggable:`可拖动`,"Unlock the layout first":`请先解除布局锁定`,"Space the selected node and its direct neighbors":`整理选中节点及直接邻居的间距`,"Space all nodes":`整理全部节点的间距`,Arrange:`整理间距`,"Hide details":`隐藏右侧详情栏`,"Show details":`显示右侧详情栏`,Overview:`模型概览`,Edges:`关系`,Groups:`边界`,"Diagram types":`图类型`,"Search nodes":`搜索节点`,"Edge animation":`连线流动`,On:`开`,Off:`关`,"System reduced-motion preference is respected":`已遵循系统减少动态效果设置`,"Matches · {count}":`匹配结果 · {count}`,"Nodes · {count}":`节点目录 · {count}`,"No matches. Try a name or responsibility.":`未找到匹配节点,请试试名称或职责。`,Legend:`图例`,"Interactive {type}":`可交互{type}`,"Fit canvas":`适应画布`,"Exit fullscreen":`退出全屏`,"Enter fullscreen":`进入全屏`,"Exit fullscreen (Esc)":`退出全屏(Esc)`,"Fullscreen is not available in this browser or page":`当前浏览器或页面不支持全屏`,"Could not exit fullscreen. Press Esc to try again.":`无法退出全屏,请按 Esc 重试`,"Could not enter fullscreen. Check browser or page permissions and try again.":`无法进入全屏,请检查浏览器或页面权限后重试`,"{count} relations":`{count} 条关系`,"Node notes":`节点说明`,"Close details":`关闭详情`,Fields:`字段`,Attributes:`属性`,Methods:`方法`,Source:`来源`,"Start with a node":`从一个节点开始`,"Select a component or a list entry to explore its role, fields, methods and source.":`点击图中组件或左侧目录,查看职责、字段、方法与来源。`,"Evidence facts":`证据事实`,"Unlock the layout before arranging nodes":`请先解除布局锁定,再整理间距`,Local:`局部`,"Full diagram":`全图`,"{scope} arranged: {count} nodes moved":`{scope}间距已整理:移动 {count} 个节点`,"Cannot arrange further within the current constraints":`当前约束下无法继续整理`,"No spacing changes needed":`当前间距无需调整`,"Generating {format}…":`正在生成 {format}…`,"{format} downloaded":`{format} 已下载`,"The browser could not generate the PNG":`浏览器未能生成 PNG`,"The browser could not read the exported SVG":`浏览器未能读取导出 SVG`,"Zoom in":`放大`,"Zoom out":`缩小`,Minimap:`小地图`,"Graph navigation":`图谱导航`,"Show graph navigation":`显示图谱导航`,"Hide graph navigation":`隐藏图谱导航`,More:`更多`,"Export SVG":`导出 SVG`,"Export PNG":`导出 PNG`,Close:`关闭`,"View details":`查看详情`,Appearance:`外观`,"Follow system":`跟随系统`,"Restore the original layout and view, and clear search and selection.":`恢复原始位置和阅读视角,清除搜索与选择`,"Reset: original positions and reading view restored":`已重置:恢复原始位置和阅读视角`,Details:`详情`,Name:`名称`,Description:`说明`,"Name is required":`名称不能为空`,Cancel:`取消`,Save:`保存`,"Edit text":`编辑文字`,Evidence:`证据`,"Save changes":`保存修改`,"Graph JSON saved":`Graph JSON 已保存`,"Saved into this page, its sibling graph.json and SVGs":`已保存到当前页面、同级 graph.json 和 SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`已保存到当前页面和同级 graph.json;SVG 未更新:布局需要调整`,"Choose the folder containing this page ({page}); edits remain in this page":`请选择当前页面 {page} 所在的文件夹,修改仍保留在当前页面`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON 已下载,请保留文件以保存修改`,"Save cancelled; edits remain in this page":`已取消保存,修改仍保留在当前页面`,"Save failed; edits remain in this page":`保存失败,修改仍保留在当前页面`,"Synchronous message":`同步消息`,"Asynchronous message":`异步消息`,"Return message":`返回消息`,"Branch conditions unspecified":`分支条件未标注`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`布局需要调整,仍可保存 JSON 草稿`,"Card wash":`卡片微底色`,yes:`是`,no:`否`,composition:`组合`,aggregation:`聚合`,inheritance:`继承`,implementation:`实现`,"Core state":`核心状态`,"Ended state":`终结状态`,"Failed state":`失败状态`,"In-progress state":`进行中状态`,"In-progress state: warm to cool as it advances":`进行中状态:由暖到冷表示推进顺序`,Transition:`转移`,"Self-transition: handled without leaving the state":`自转移:留在原状态内处理的事件`,"Key points":`要点`,"Show key points":`显示要点`,"Hide key points":`隐藏要点`,"Component relations":`组件关系`,"Platform capabilities":`平台能力总览`,"Engineering layers":`工程分层总览`,"Overview text":`总览正文`,Badges:`徽章`,"Badge type":`徽章类型`,"Add badge":`添加徽章`,"Remove badge":`移除徽章`,Status:`状态`,Version:`版本`,Requirement:`接入要求`,"Overview aligned":`总览已对齐`,Section:`分区`,Cancelled:`已取消`,"Component relationship architecture":`组件关系架构图`,"Platform capability architecture":`平台能力架构图`,"Engineering layer architecture":`工程分层架构图`,"Shared dependencies":`公共依赖`,"Source changes":`源码变化`,"Show source changes":`显示源码变化`,"Hide source changes":`隐藏源码变化`,"This update":`本次更新`,"Show this update":`显示本次更新`,"Hide this update":`隐藏本次更新`,Added:`新增`,Changed:`改动`,Removed:`删除`,"View notes updated":`视图说明已更新`},ja:{Architecture:`アーキテクチャ`,Flowchart:`フローチャート`,Sequence:`シーケンス図`,"ER diagram":`ER 図`,Deployment:`配置図`,"Class diagram":`クラス図`,"State diagram":`状態図`,"Use cases":`ユースケース図`,"Data flow":`データフロー図`,"Source code":`ソースコード`,Code:`コード`,Configuration:`設定`,Schema:`スキーマ`,Test:`テスト`,Document:`ドキュメント`,"Framework convention":`フレームワークの規約`,Inference:`推論`,External:`外部`,Framework:`フレームワーク`,Security:`セキュリティ`,Service:`サービス`,Business:`業務`,Data:`データ`,Failure:`失敗`,System:`システム`,Component:`コンポーネント`,Database:`データベース`,Start:`開始`,End:`終了`,Process:`処理`,Decision:`分岐`,Input:`入力`,Output:`出力`,Subprocess:`サブプロセス`,Actor:`アクター`,Participant:`参加者`,Entity:`エンティティ`,Device:`デバイス`,Nodes:`ノード`,Container:`コンテナ`,Artifact:`成果物`,Class:`クラス`,Interface:`インターフェース`,"Abstract class":`抽象クラス`,State:`状態`,Initial:`初期`,Choice:`選択`,"Use case":`ユースケース`,"Data store":`データストア`,"Initial state":`初期状態`,"Final state":`終了状態`,"Core component":`主要コンポーネント`,"Data / storage":`データ / ストレージ`,"Start / end":`開始 / 終了`,"Components / actors":`コンポーネント / アクター`,"Solid relation":`実線の関係`,"Dashed: notation / convention / inference":`破線:記法 / 規約 / 推論`,Reset:`リセット`,Dark:`ダーク`,Light:`ライト`,Locked:`配置を固定`,Draggable:`移動可能`,"Unlock the layout first":`先に配置の固定を解除してください`,"Space the selected node and its direct neighbors":`選択ノードと隣接ノードの間隔を調整`,"Space all nodes":`すべてのノードの間隔を調整`,Arrange:`間隔を調整`,"Hide details":`詳細を隠す`,"Show details":`詳細を表示`,Overview:`概要`,Edges:`関係`,Groups:`グループ`,"Diagram types":`図の種類`,"Search nodes":`ノードを検索`,"Edge animation":`接続線の動き`,On:`オン`,Off:`オフ`,"System reduced-motion preference is respected":`システムの視差効果を減らす設定に従っています`,"Matches · {count}":`検索結果 · {count}`,"Nodes · {count}":`ノード · {count}`,"No matches. Try a name or responsibility.":`一致するノードがありません。名前や役割を変えて検索してください。`,Legend:`凡例`,"Interactive {type}":`操作可能な{type}`,"Fit canvas":`キャンバスに合わせる`,"Exit fullscreen":`全画面表示を終了`,"Enter fullscreen":`全画面表示`,"Exit fullscreen (Esc)":`全画面表示を終了(Esc)`,"Fullscreen is not available in this browser or page":`このブラウザーまたはページでは全画面表示を利用できません`,"Could not exit fullscreen. Press Esc to try again.":`全画面表示を終了できません。Esc キーを押してください`,"Could not enter fullscreen. Check browser or page permissions and try again.":`全画面表示を開始できません。ブラウザーやページの権限を確認してください`,"{count} relations":`{count} 関係`,"Node notes":`ノードの説明`,"Close details":`詳細を閉じる`,Fields:`フィールド`,Attributes:`属性`,Methods:`メソッド`,Source:`根拠`,"Start with a node":`ノードを選んで始めましょう`,"Select a component or a list entry to explore its role, fields, methods and source.":`図や一覧からコンポーネントを選ぶと、役割、フィールド、メソッド、根拠を確認できます。`,"Evidence facts":`根拠に基づく情報`,"Unlock the layout before arranging nodes":`間隔を調整する前に配置の固定を解除してください`,Local:`選択範囲`,"Full diagram":`図全体`,"{scope} arranged: {count} nodes moved":`{scope}の間隔を調整:{count} ノードを移動`,"Cannot arrange further within the current constraints":`現在の制約ではこれ以上調整できません`,"No spacing changes needed":`間隔の調整は不要です`,"Generating {format}…":`{format} を生成中…`,"{format} downloaded":`{format} をダウンロードしました`,"The browser could not generate the PNG":`ブラウザーで PNG を生成できませんでした`,"The browser could not read the exported SVG":`ブラウザーで出力 SVG を読み込めませんでした`,"Zoom in":`拡大`,"Zoom out":`縮小`,Minimap:`ミニマップ`,"Graph navigation":`グラフナビ`,"Show graph navigation":`グラフナビを表示`,"Hide graph navigation":`グラフナビを非表示`,More:`その他`,"Export SVG":`SVG を書き出す`,"Export PNG":`PNG を書き出す`,Close:`閉じる`,"View details":`詳細を見る`,Appearance:`外観`,"Follow system":`システム`,"Restore the original layout and view, and clear search and selection.":`元の配置と表示に戻し、検索と選択を解除します。`,"Reset: original positions and reading view restored":`リセットしました:元の配置と表示に戻りました`,Details:`詳細`,Name:`名前`,Description:`説明`,"Name is required":`名前は必須です`,Cancel:`キャンセル`,Save:`保存`,"Edit text":`テキストを編集`,Evidence:`根拠`,"Save changes":`変更を保存`,"Graph JSON saved":`Graph JSON を保存しました`,"Saved into this page, its sibling graph.json and SVGs":`このページと同じ階層の graph.json、SVG に保存しました`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`このページと同じ階層の graph.json に保存しました。SVG は更新していません。レイアウトの調整が必要です`,"Choose the folder containing this page ({page}); edits remain in this page":`このページ({page})があるフォルダーを選択してください。編集内容はこのページに残っています`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON をダウンロードしました。編集内容を残すにはファイルを保管してください`,"Save cancelled; edits remain in this page":`保存をキャンセルしました。編集内容はこのページに残っています`,"Save failed; edits remain in this page":`保存に失敗しました。編集内容はこのページに残っています`,"Synchronous message":`同期メッセージ`,"Asynchronous message":`非同期メッセージ`,"Return message":`戻りメッセージ`,"Branch conditions unspecified":`分岐条件未指定`,"Activation: execution interval; offset means nesting":`実行区間:横のずれは入れ子を示す`,"C ID: paired call and return share a color":`C 番号:呼び出しと戻りは同じ色`,"par: concurrent branches; vertical position is not order":`par:並行分岐。上下の位置は実行順ではない`,"Layout needs adjustment; JSON drafts can still be saved":`レイアウトの調整が必要です。JSON の下書きは保存できます`,"Card wash":`カードの淡い下地`,yes:`はい`,no:`いいえ`,composition:`コンポジション`,aggregation:`集約`,inheritance:`継承`,implementation:`実装`,"Core state":`主要な状態`,"Ended state":`終了した状態`,"Failed state":`失敗した状態`,"In-progress state":`進行中の状態`,"In-progress state: warm to cool as it advances":`進行中の状態:進むにつれて暖色から寒色へ`,Transition:`遷移`,"Self-transition: handled without leaving the state":`自己遷移:状態を離れずに処理するイベント`,"Key points":`要点`,"Show key points":`要点を表示`,"Hide key points":`要点を隠す`,"Component relations":`コンポーネント関係`,"Platform capabilities":`プラットフォーム機能`,"Engineering layers":`プロジェクト階層`,"Overview text":`概要本文`,Badges:`バッジ`,"Badge type":`バッジの種類`,"Add badge":`バッジを追加`,"Remove badge":`バッジを削除`,Status:`状態`,Version:`バージョン`,Requirement:`要件`,"Overview aligned":`概要を整列しました`,Section:`セクション`,Cancelled:`キャンセルしました`,"Component relationship architecture":`コンポーネント関係アーキテクチャ図`,"Platform capability architecture":`プラットフォーム機能アーキテクチャ図`,"Engineering layer architecture":`プロジェクト階層アーキテクチャ図`,"Layout suggestions":`レイアウトの提案`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`このビューを整列すると、接続線の余白と間隔を改善できます。それまでは現在の位置が保持されます。`,"Shared dependencies":`共通の依存先`,"Source changes":`ソースの変更`,"Show source changes":`ソースの変更を表示`,"Hide source changes":`ソースの変更を隠す`,"This update":`今回の更新`,"Show this update":`今回の更新を表示`,"Hide this update":`今回の更新を隠す`,Added:`追加`,Changed:`変更`,Removed:`削除`,"View notes updated":`ビューの説明を更新`},ko:{Architecture:`아키텍처`,Flowchart:`순서도`,Sequence:`시퀀스 다이어그램`,"ER diagram":`ER 다이어그램`,Deployment:`배포 다이어그램`,"Class diagram":`클래스 다이어그램`,"State diagram":`상태 다이어그램`,"Use cases":`유스케이스 다이어그램`,"Data flow":`데이터 흐름도`,"Source code":`소스 코드`,Code:`코드`,Configuration:`설정`,Schema:`스키마`,Test:`테스트`,Document:`문서`,"Framework convention":`프레임워크 규약`,Inference:`추론`,External:`외부`,Framework:`프레임워크`,Security:`보안`,Service:`서비스`,Business:`비즈니스`,Data:`데이터`,Failure:`실패`,System:`시스템`,Component:`컴포넌트`,Database:`데이터베이스`,Start:`시작`,End:`종료`,Process:`처리`,Decision:`판단`,Input:`입력`,Output:`출력`,Subprocess:`하위 프로세스`,Actor:`행위자`,Participant:`참여자`,Entity:`엔티티`,Device:`장치`,Nodes:`노드`,Container:`컨테이너`,Artifact:`아티팩트`,Class:`클래스`,Interface:`인터페이스`,"Abstract class":`추상 클래스`,State:`상태`,Initial:`초기`,Choice:`선택`,"Use case":`유스케이스`,"Data store":`데이터 저장소`,"Initial state":`초기 상태`,"Final state":`최종 상태`,"Core component":`핵심 컴포넌트`,"Data / storage":`데이터 / 저장소`,"Start / end":`시작 / 종료`,"Components / actors":`컴포넌트 / 행위자`,"Solid relation":`실선 관계`,"Dashed: notation / convention / inference":`점선: 표기법 / 규약 / 추론`,Reset:`초기화`,Dark:`어둡게`,Light:`밝게`,Locked:`배치 잠금`,Draggable:`드래그 가능`,"Unlock the layout first":`먼저 배치 잠금을 해제하세요`,"Space the selected node and its direct neighbors":`선택한 노드와 인접 노드의 간격 조정`,"Space all nodes":`모든 노드의 간격 조정`,Arrange:`간격 정리`,"Hide details":`상세 정보 숨기기`,"Show details":`상세 정보 표시`,Overview:`개요`,Edges:`관계`,Groups:`그룹`,"Diagram types":`다이어그램 유형`,"Search nodes":`노드 검색`,"Edge animation":`연결선 애니메이션`,On:`켜짐`,Off:`꺼짐`,"System reduced-motion preference is respected":`시스템의 동작 줄이기 설정을 따릅니다`,"Matches · {count}":`검색 결과 · {count}`,"Nodes · {count}":`노드 · {count}`,"No matches. Try a name or responsibility.":`일치하는 노드가 없습니다. 이름이나 역할로 검색하세요.`,Legend:`범례`,"Interactive {type}":`대화형 {type}`,"Fit canvas":`캔버스에 맞추기`,"Exit fullscreen":`전체 화면 종료`,"Enter fullscreen":`전체 화면`,"Exit fullscreen (Esc)":`전체 화면 종료 (Esc)`,"Fullscreen is not available in this browser or page":`이 브라우저나 페이지에서는 전체 화면을 사용할 수 없습니다`,"Could not exit fullscreen. Press Esc to try again.":`전체 화면을 종료할 수 없습니다. Esc 키를 누르세요`,"Could not enter fullscreen. Check browser or page permissions and try again.":`전체 화면을 시작할 수 없습니다. 브라우저나 페이지 권한을 확인하세요`,"{count} relations":`관계 {count}개`,"Node notes":`노드 설명`,"Close details":`상세 정보 닫기`,Fields:`필드`,Attributes:`속성`,Methods:`메서드`,Source:`근거`,"Start with a node":`노드를 선택해 시작하세요`,"Select a component or a list entry to explore its role, fields, methods and source.":`다이어그램이나 목록에서 컴포넌트를 선택하면 역할, 필드, 메서드와 근거를 볼 수 있습니다.`,"Evidence facts":`근거로 확인한 내용`,"Unlock the layout before arranging nodes":`간격을 정리하기 전에 배치 잠금을 해제하세요`,Local:`선택 영역`,"Full diagram":`전체 다이어그램`,"{scope} arranged: {count} nodes moved":`{scope} 간격 정리: 노드 {count}개 이동`,"Cannot arrange further within the current constraints":`현재 제약 조건에서는 더 정리할 수 없습니다`,"No spacing changes needed":`간격 조정이 필요하지 않습니다`,"Generating {format}…":`{format} 생성 중…`,"{format} downloaded":`{format} 다운로드 완료`,"The browser could not generate the PNG":`브라우저에서 PNG를 생성하지 못했습니다`,"The browser could not read the exported SVG":`브라우저에서 내보낸 SVG를 읽지 못했습니다`,"Zoom in":`확대`,"Zoom out":`축소`,Minimap:`미니맵`,"Graph navigation":`그래프 탐색`,"Show graph navigation":`그래프 탐색 표시`,"Hide graph navigation":`그래프 탐색 숨기기`,More:`더보기`,"Export SVG":`SVG 내보내기`,"Export PNG":`PNG 내보내기`,Close:`닫기`,"View details":`상세 보기`,Appearance:`화면 모드`,"Follow system":`시스템`,"Restore the original layout and view, and clear search and selection.":`원래 배치와 보기를 복원하고 검색과 선택을 지웁니다.`,"Reset: original positions and reading view restored":`초기화됨: 원래 위치와 보기 복원`,Details:`세부 정보`,Name:`이름`,Description:`설명`,"Name is required":`이름은 필수입니다`,Cancel:`취소`,Save:`저장`,"Edit text":`텍스트 편집`,Evidence:`근거`,"Save changes":`변경 사항 저장`,"Graph JSON saved":`Graph JSON을 저장했습니다`,"Saved into this page, its sibling graph.json and SVGs":`현재 페이지와 같은 폴더의 graph.json, SVG에 저장했습니다`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`현재 페이지와 같은 폴더의 graph.json에 저장했습니다. SVG는 업데이트하지 않았습니다. 레이아웃을 조정해야 합니다`,"Choose the folder containing this page ({page}); edits remain in this page":`현재 페이지({page})가 있는 폴더를 선택하세요. 수정 사항은 현재 페이지에 남아 있습니다`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON을 다운로드했습니다. 수정 사항을 보관하려면 파일을 저장하세요`,"Save cancelled; edits remain in this page":`저장을 취소했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Save failed; edits remain in this page":`저장에 실패했습니다. 수정 사항은 현재 페이지에 남아 있습니다`,"Synchronous message":`동기 메시지`,"Asynchronous message":`비동기 메시지`,"Return message":`반환 메시지`,"Branch conditions unspecified":`분기 조건 미지정`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`레이아웃을 조정해야 합니다. JSON 초안은 저장할 수 있습니다`,"Card wash":`카드 연한 배경`,yes:`예`,no:`아니요`,composition:`합성`,aggregation:`집합`,inheritance:`상속`,implementation:`구현`,"Core state":`핵심 상태`,"Ended state":`종료된 상태`,"Failed state":`실패한 상태`,"In-progress state":`진행 중인 상태`,"In-progress state: warm to cool as it advances":`진행 중인 상태: 진행될수록 따뜻한 색에서 차가운 색으로`,Transition:`전이`,"Self-transition: handled without leaving the state":`자기 전이: 상태를 벗어나지 않고 처리하는 이벤트`,"Key points":`요점`,"Show key points":`요점 보기`,"Hide key points":`요점 숨기기`,"Component relations":`구성 요소 관계`,"Platform capabilities":`플랫폼 기능`,"Engineering layers":`프로젝트 계층`,"Overview text":`개요 본문`,Badges:`배지`,"Badge type":`배지 유형`,"Add badge":`배지 추가`,"Remove badge":`배지 제거`,Status:`상태`,Version:`버전`,Requirement:`요구 사항`,"Overview aligned":`개요 정렬 완료`,Section:`섹션`,Cancelled:`취소됨`,"Component relationship architecture":`구성 요소 관계 아키텍처`,"Platform capability architecture":`플랫폼 기능 아키텍처`,"Engineering layer architecture":`엔지니어링 계층 아키텍처`,"Layout suggestions":`레이아웃 제안`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`이 보기를 정리하여 연결선의 여백과 간격을 개선하세요. 정리하기 전까지 기존 위치가 유지됩니다.`,"Shared dependencies":`공통 의존성`,"Source changes":`소스 변경`,"Show source changes":`소스 변경 표시`,"Hide source changes":`소스 변경 숨기기`,"This update":`이번 업데이트`,"Show this update":`이번 업데이트 표시`,"Hide this update":`이번 업데이트 숨기기`,Added:`추가`,Changed:`변경`,Removed:`삭제`,"View notes updated":`뷰 설명이 갱신됨`},de:{Architecture:`Architektur`,Flowchart:`Flussdiagramm`,Sequence:`Sequenzdiagramm`,"ER diagram":`ER-Diagramm`,Deployment:`Deployment-Diagramm`,"Class diagram":`Klassendiagramm`,"State diagram":`Zustandsdiagramm`,"Use cases":`Anwendungsfalldiagramm`,"Data flow":`Datenflussdiagramm`,"Source code":`Quellcode`,Code:`Code`,Configuration:`Konfiguration`,Schema:`Schema`,Test:`Test`,Document:`Dokumentation`,"Framework convention":`Framework-Konvention`,Inference:`Annahme`,External:`Extern`,Framework:`Framework`,Security:`Sicherheit`,Service:`Dienst`,Business:`Fachlogik`,Data:`Daten`,Failure:`Fehler`,System:`System`,Component:`Komponente`,Database:`Datenbank`,Start:`Start`,End:`Ende`,Process:`Prozess`,Decision:`Entscheidung`,Input:`Eingabe`,Output:`Ausgabe`,Subprocess:`Teilprozess`,Actor:`Akteur`,Participant:`Teilnehmer`,Entity:`Entität`,Device:`Gerät`,Nodes:`Knoten`,Container:`Container`,Artifact:`Artefakt`,Class:`Klasse`,Interface:`Schnittstelle`,"Abstract class":`Abstrakte Klasse`,State:`Zustand`,Initial:`Initial`,Choice:`Auswahl`,"Use case":`Anwendungsfall`,"Data store":`Datenspeicher`,"Initial state":`Anfangszustand`,"Final state":`Endzustand`,"Core component":`Kernkomponente`,"Data / storage":`Daten / Speicher`,"Start / end":`Start / Ende`,"Components / actors":`Komponenten / Akteure`,"Solid relation":`Durchgezogene Beziehung`,"Dashed: notation / convention / inference":`Gestrichelt: Notation / Konvention / Annahme`,Reset:`Zurücksetzen`,Dark:`Dunkel`,Light:`Hell`,Locked:`Gesperrt`,Draggable:`Verschiebbar`,"Unlock the layout first":`Zuerst das Layout entsperren`,"Space the selected node and its direct neighbors":`Abstände der Auswahl und direkter Nachbarn anpassen`,"Space all nodes":`Alle Knotenabstände anpassen`,Arrange:`Abstände`,"Hide details":`Details ausblenden`,"Show details":`Details anzeigen`,Overview:`Überblick`,Edges:`Beziehungen`,Groups:`Gruppen`,"Diagram types":`Diagrammtypen`,"Search nodes":`Knoten suchen`,"Edge animation":`Kantenanimation`,On:`Ein`,Off:`Aus`,"System reduced-motion preference is respected":`Die Systemeinstellung für reduzierte Bewegung wird beachtet`,"Matches · {count}":`Treffer · {count}`,"Nodes · {count}":`Knoten · {count}`,"No matches. Try a name or responsibility.":`Keine Treffer. Versuchen Sie einen Namen oder eine Rolle.`,Legend:`Legende`,"Interactive {type}":`Interaktiv: {type}`,"Fit canvas":`An Zeichenfläche anpassen`,"Exit fullscreen":`Vollbild verlassen`,"Enter fullscreen":`Vollbild`,"Exit fullscreen (Esc)":`Vollbild verlassen (Esc)`,"Fullscreen is not available in this browser or page":`Vollbild ist in diesem Browser oder auf dieser Seite nicht verfügbar`,"Could not exit fullscreen. Press Esc to try again.":`Vollbild konnte nicht beendet werden. Drücken Sie Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Vollbild konnte nicht gestartet werden. Prüfen Sie die Browser- oder Seitenberechtigungen.`,"{count} relations":`{count} Beziehungen`,"Node notes":`Knotenbeschreibung`,"Close details":`Details schließen`,Fields:`Felder`,Attributes:`Attribute`,Methods:`Methoden`,Source:`Beleg`,"Start with a node":`Wählen Sie einen Knoten`,"Select a component or a list entry to explore its role, fields, methods and source.":`Wählen Sie eine Komponente im Diagramm oder in der Liste, um Rolle, Felder, Methoden und Belege zu sehen.`,"Evidence facts":`Belegte Fakten`,"Unlock the layout before arranging nodes":`Entsperren Sie das Layout vor dem Anpassen der Abstände`,Local:`Auswahl`,"Full diagram":`Gesamtes Diagramm`,"{scope} arranged: {count} nodes moved":`{scope}: Abstände angepasst, {count} Knoten verschoben`,"Cannot arrange further within the current constraints":`Unter diesen Bedingungen ist keine weitere Anpassung möglich`,"No spacing changes needed":`Keine Abstandsanpassung erforderlich`,"Generating {format}…":`{format} wird erstellt…`,"{format} downloaded":`{format} heruntergeladen`,"The browser could not generate the PNG":`Der Browser konnte kein PNG erstellen`,"The browser could not read the exported SVG":`Der Browser konnte die exportierte SVG-Datei nicht lesen`,"Zoom in":`Vergrößern`,"Zoom out":`Verkleinern`,Minimap:`Minikarte`,"Graph navigation":`Graph-Navigation`,"Show graph navigation":`Graph-Navigation einblenden`,"Hide graph navigation":`Graph-Navigation ausblenden`,More:`Mehr`,"Export SVG":`SVG exportieren`,"Export PNG":`PNG exportieren`,Close:`Schließen`,"View details":`Details ansehen`,Appearance:`Erscheinungsbild`,"Follow system":`System`,"Restore the original layout and view, and clear search and selection.":`Ursprüngliche Anordnung und Ansicht wiederherstellen, Suche und Auswahl löschen.`,"Reset: original positions and reading view restored":`Zurückgesetzt: ursprüngliche Positionen und Ansicht wiederhergestellt`,Details:`Details`,Name:`Name`,Description:`Beschreibung`,"Name is required":`Name ist erforderlich`,Cancel:`Abbrechen`,Save:`Speichern`,"Edit text":`Text bearbeiten`,Evidence:`Nachweis`,"Save changes":`Änderungen speichern`,"Graph JSON saved":`Graph JSON gespeichert`,"Saved into this page, its sibling graph.json and SVGs":`In diese Seite, die benachbarte graph.json und die SVGs gespeichert`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`In diese Seite und die benachbarte graph.json gespeichert; SVGs nicht aktualisiert: Das Layout muss angepasst werden`,"Choose the folder containing this page ({page}); edits remain in this page":`Bitte den Ordner dieser Seite ({page}) wählen; die Änderungen bleiben auf dieser Seite`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON heruntergeladen; Datei zum Erhalten der Änderungen aufbewahren`,"Save cancelled; edits remain in this page":`Speichern abgebrochen; Änderungen bleiben auf dieser Seite`,"Save failed; edits remain in this page":`Speichern fehlgeschlagen; Änderungen bleiben auf dieser Seite`,"Synchronous message":`Synchrone Nachricht`,"Asynchronous message":`Asynchrone Nachricht`,"Return message":`Antwortnachricht`,"Branch conditions unspecified":`Zweigbedingungen fehlen`,"Activation: execution interval; offset means nesting":`Aktivierung: Ausführungsdauer; Versatz zeigt Verschachtelung`,"C ID: paired call and return share a color":`C-ID: Aufruf und Rückgabe haben dieselbe Farbe`,"par: concurrent branches; vertical position is not order":`par: parallele Zweige; vertikale Lage ist keine Reihenfolge`,"Layout needs adjustment; JSON drafts can still be saved":`Layout anpassen; JSON-Entwürfe können gespeichert werden`,"Card wash":`Karten-Grundton`,yes:`ja`,no:`nein`,composition:`Komposition`,aggregation:`Aggregation`,inheritance:`Vererbung`,implementation:`Implementierung`,"Core state":`Kernzustand`,"Ended state":`Beendeter Zustand`,"Failed state":`Fehlgeschlagener Zustand`,"In-progress state":`Zustand in Bearbeitung`,"In-progress state: warm to cool as it advances":`Zustand in Bearbeitung: von warm nach kalt, je weiter er fortschreitet`,Transition:`Übergang`,"Self-transition: handled without leaving the state":`Selbstübergang: Ereignis, das im Zustand bleibt`,"Key points":`Kernaussagen`,"Show key points":`Kernaussagen anzeigen`,"Hide key points":`Kernaussagen ausblenden`,"Component relations":`Komponentenbeziehungen`,"Platform capabilities":`Plattformfunktionen`,"Engineering layers":`Projektebenen`,"Overview text":`Übersichtstext`,Badges:`Abzeichen`,"Badge type":`Abzeichentyp`,"Add badge":`Abzeichen hinzufügen`,"Remove badge":`Abzeichen entfernen`,Status:`Status`,Version:`Version`,Requirement:`Anforderung`,"Overview aligned":`Übersicht ausgerichtet`,Section:`Abschnitt`,Cancelled:`Abgebrochen`,"Component relationship architecture":`Komponentenarchitektur`,"Platform capability architecture":`Plattformfähigkeitsarchitektur`,"Engineering layer architecture":`Schichtenarchitektur`,"Layout suggestions":`Layoutvorschläge`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Ordnen Sie diese Ansicht an, um Abstände der Verbindungslinien zu verbessern. Bis dahin bleiben die bisherigen Positionen erhalten.`,"Shared dependencies":`Gemeinsame Abhängigkeiten`,"Source changes":`Quellcode-Änderungen`,"Show source changes":`Quellcode-Änderungen anzeigen`,"Hide source changes":`Quellcode-Änderungen ausblenden`,"This update":`Diese Aktualisierung`,"Show this update":`Diese Aktualisierung anzeigen`,"Hide this update":`Diese Aktualisierung ausblenden`,Added:`Hinzugefügt`,Changed:`Geändert`,Removed:`Entfernt`,"View notes updated":`Ansichtsbeschreibung aktualisiert`},fr:{Architecture:`Architecture`,Flowchart:`Organigramme`,Sequence:`Diagramme de séquence`,"ER diagram":`Diagramme ER`,Deployment:`Diagramme de déploiement`,"Class diagram":`Diagramme de classes`,"State diagram":`Diagramme d’états`,"Use cases":`Cas d’utilisation`,"Data flow":`Flux de données`,"Source code":`Code source`,Code:`Code`,Configuration:`Configuration`,Schema:`Schéma`,Test:`Test`,Document:`Documentation`,"Framework convention":`Convention du framework`,Inference:`Déduction`,External:`Externe`,Framework:`Framework`,Security:`Sécurité`,Service:`Service`,Business:`Métier`,Data:`Données`,Failure:`Échec`,System:`Système`,Component:`Composant`,Database:`Base de données`,Start:`Début`,End:`Fin`,Process:`Traitement`,Decision:`Décision`,Input:`Entrée`,Output:`Sortie`,Subprocess:`Sous-processus`,Actor:`Acteur`,Participant:`Participant`,Entity:`Entité`,Device:`Appareil`,Nodes:`Nœuds`,Container:`Conteneur`,Artifact:`Artefact`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstraite`,State:`État`,Initial:`Initial`,Choice:`Choix`,"Use case":`Cas d’utilisation`,"Data store":`Stockage de données`,"Initial state":`État initial`,"Final state":`État final`,"Core component":`Composant central`,"Data / storage":`Données / stockage`,"Start / end":`Début / fin`,"Components / actors":`Composants / acteurs`,"Solid relation":`Relation en trait plein`,"Dashed: notation / convention / inference":`Pointillés : notation / convention / déduction`,Reset:`Réinitialiser`,Dark:`Sombre`,Light:`Clair`,Locked:`Verrouillé`,Draggable:`Déplaçable`,"Unlock the layout first":`Déverrouillez d’abord la disposition`,"Space the selected node and its direct neighbors":`Espacer la sélection et ses voisins directs`,"Space all nodes":`Espacer tous les nœuds`,Arrange:`Espacer`,"Hide details":`Masquer les détails`,"Show details":`Afficher les détails`,Overview:`Vue d’ensemble`,Edges:`Relations`,Groups:`Groupes`,"Diagram types":`Types de diagrammes`,"Search nodes":`Rechercher un nœud`,"Edge animation":`Animation des liens`,On:`Activée`,Off:`Désactivée`,"System reduced-motion preference is respected":`Le réglage système de réduction des animations est respecté`,"Matches · {count}":`Résultats · {count}`,"Nodes · {count}":`Nœuds · {count}`,"No matches. Try a name or responsibility.":`Aucun résultat. Essayez un nom ou un rôle.`,Legend:`Légende`,"Interactive {type}":`Vue interactive : {type}`,"Fit canvas":`Ajuster au canevas`,"Exit fullscreen":`Quitter le plein écran`,"Enter fullscreen":`Plein écran`,"Exit fullscreen (Esc)":`Quitter le plein écran (Échap)`,"Fullscreen is not available in this browser or page":`Le plein écran n’est pas disponible dans ce navigateur ou sur cette page`,"Could not exit fullscreen. Press Esc to try again.":`Impossible de quitter le plein écran. Appuyez sur Échap.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Impossible de passer en plein écran. Vérifiez les autorisations du navigateur ou de la page.`,"{count} relations":`{count} relations`,"Node notes":`Notes du nœud`,"Close details":`Fermer les détails`,Fields:`Champs`,Attributes:`Attributs`,Methods:`Méthodes`,Source:`Preuve`,"Start with a node":`Commencez par un nœud`,"Select a component or a list entry to explore its role, fields, methods and source.":`Sélectionnez un composant du diagramme ou de la liste pour consulter son rôle, ses champs, ses méthodes et ses preuves.`,"Evidence facts":`Faits étayés`,"Unlock the layout before arranging nodes":`Déverrouillez la disposition avant d’ajuster les espacements`,Local:`Sélection`,"Full diagram":`Diagramme entier`,"{scope} arranged: {count} nodes moved":`{scope} : espacement ajusté, {count} nœuds déplacés`,"Cannot arrange further within the current constraints":`Impossible d’ajuster davantage avec ces contraintes`,"No spacing changes needed":`Aucun ajustement d’espacement nécessaire`,"Generating {format}…":`Génération de {format}…`,"{format} downloaded":`{format} téléchargé`,"The browser could not generate the PNG":`Le navigateur n’a pas pu générer le PNG`,"The browser could not read the exported SVG":`Le navigateur n’a pas pu lire le SVG exporté`,"Zoom in":`Agrandir`,"Zoom out":`Réduire`,Minimap:`Mini-carte`,"Graph navigation":`Navigation du graphe`,"Show graph navigation":`Afficher la navigation`,"Hide graph navigation":`Masquer la navigation`,More:`Plus`,"Export SVG":`Exporter en SVG`,"Export PNG":`Exporter en PNG`,Close:`Fermer`,"View details":`Voir les détails`,Appearance:`Apparence`,"Follow system":`Système`,"Restore the original layout and view, and clear search and selection.":`Rétablir la disposition et la vue, puis effacer la recherche et la sélection.`,"Reset: original positions and reading view restored":`Réinitialisé : positions et vue d’origine rétablies`,Details:`Détails`,Name:`Nom`,Description:`Description`,"Name is required":`Le nom est obligatoire`,Cancel:`Annuler`,Save:`Enregistrer`,"Edit text":`Modifier le texte`,Evidence:`Preuve`,"Save changes":`Enregistrer les modifications`,"Graph JSON saved":`Graph JSON enregistré`,"Saved into this page, its sibling graph.json and SVGs":`Enregistré dans cette page, dans le graph.json voisin et dans les SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Enregistré dans cette page et dans le graph.json voisin ; SVG non mis à jour : la disposition doit être ajustée`,"Choose the folder containing this page ({page}); edits remain in this page":`Choisissez le dossier contenant cette page ({page}) ; les modifications restent sur cette page`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON téléchargé ; conservez le fichier pour garder les modifications`,"Save cancelled; edits remain in this page":`Enregistrement annulé ; les modifications restent sur cette page`,"Save failed; edits remain in this page":`Échec de l’enregistrement ; les modifications restent sur cette page`,"Synchronous message":`Message synchrone`,"Asynchronous message":`Message asynchrone`,"Return message":`Message de retour`,"Branch conditions unspecified":`Conditions de branche non précisées`,"Activation: execution interval; offset means nesting":`激活条:执行区间,错位表示嵌套`,"C ID: paired call and return share a color":`C 编号:调用与返回配对,同组同色`,"par: concurrent branches; vertical position is not order":`par:分支并行,上下排列不代表先后`,"Layout needs adjustment; JSON drafts can still be saved":`La disposition doit être ajustée ; le brouillon JSON peut être enregistré`,"Card wash":`Fond léger des cartes`,yes:`oui`,no:`non`,composition:`composition`,aggregation:`agrégation`,inheritance:`héritage`,implementation:`implémentation`,"Core state":`État central`,"Ended state":`État terminé`,"Failed state":`État en échec`,"In-progress state":`État en cours`,"In-progress state: warm to cool as it advances":`État en cours : du chaud au froid à mesure qu’il avance`,Transition:`Transition`,"Self-transition: handled without leaving the state":`Auto-transition : événement traité sans quitter l’état`,"Key points":`Points clés`,"Show key points":`Afficher les points clés`,"Hide key points":`Masquer les points clés`,"Component relations":`Relations entre composants`,"Platform capabilities":`Capacités de la plateforme`,"Engineering layers":`Couches du projet`,"Overview text":`Texte de présentation`,Badges:`Badges`,"Badge type":`Type de badge`,"Add badge":`Ajouter un badge`,"Remove badge":`Supprimer le badge`,Status:`Statut`,Version:`Version`,Requirement:`Exigence`,"Overview aligned":`Présentation alignée`,Section:`Section`,Cancelled:`Annulé`,"Component relationship architecture":`Architecture des composants`,"Platform capability architecture":`Architecture des capacités`,"Engineering layer architecture":`Architecture en couches`,"Layout suggestions":`Suggestions de disposition`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Réorganisez cette vue pour améliorer les dégagements et les espacements des connecteurs. Les positions actuelles sont conservées jusque-là.`,"Shared dependencies":`Dépendances partagées`,"Source changes":`Modifications du code`,"Show source changes":`Afficher les modifications du code`,"Hide source changes":`Masquer les modifications du code`,"This update":`Cette mise à jour`,"Show this update":`Afficher cette mise à jour`,"Hide this update":`Masquer cette mise à jour`,Added:`Ajouté`,Changed:`Modifié`,Removed:`Supprimé`,"View notes updated":`Description de la vue mise à jour`},es:{Architecture:`Arquitectura`,Flowchart:`Diagrama de flujo`,Sequence:`Diagrama de secuencia`,"ER diagram":`Diagrama ER`,Deployment:`Diagrama de despliegue`,"Class diagram":`Diagrama de clases`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Flujo de datos`,"Source code":`Código fuente`,Code:`Código`,Configuration:`Configuración`,Schema:`Esquema`,Test:`Prueba`,Document:`Documentación`,"Framework convention":`Convención del framework`,Inference:`Inferencia`,External:`Externo`,Framework:`Framework`,Security:`Seguridad`,Service:`Servicio`,Business:`Negocio`,Data:`Datos`,Failure:`Error`,System:`Sistema`,Component:`Componente`,Database:`Base de datos`,Start:`Inicio`,End:`Fin`,Process:`Proceso`,Decision:`Decisión`,Input:`Entrada`,Output:`Salida`,Subprocess:`Subproceso`,Actor:`Actor`,Participant:`Participante`,Entity:`Entidad`,Device:`Dispositivo`,Nodes:`Nodos`,Container:`Contenedor`,Artifact:`Artefacto`,Class:`Clase`,Interface:`Interfaz`,"Abstract class":`Clase abstracta`,State:`Estado`,Initial:`Inicial`,Choice:`Elección`,"Use case":`Caso de uso`,"Data store":`Almacén de datos`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente principal`,"Data / storage":`Datos / almacenamiento`,"Start / end":`Inicio / fin`,"Components / actors":`Componentes / actores`,"Solid relation":`Relación continua`,"Dashed: notation / convention / inference":`Discontinua: notación / convención / inferencia`,Reset:`Restablecer`,Dark:`Oscuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Movible`,"Unlock the layout first":`Primero desbloquea la disposición`,"Space the selected node and its direct neighbors":`Espaciar la selección y sus vecinos directos`,"Space all nodes":`Espaciar todos los nodos`,Arrange:`Espaciar`,"Hide details":`Ocultar detalles`,"Show details":`Mostrar detalles`,Overview:`Resumen`,Edges:`Relaciones`,Groups:`Grupos`,"Diagram types":`Tipos de diagramas`,"Search nodes":`Buscar nodos`,"Edge animation":`Animación de enlaces`,On:`Activada`,Off:`Desactivada`,"System reduced-motion preference is respected":`Se respeta la preferencia del sistema de reducir el movimiento`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nodos · {count}`,"No matches. Try a name or responsibility.":`No hay resultados. Prueba con un nombre o una función.`,Legend:`Leyenda`,"Interactive {type}":`Vista interactiva: {type}`,"Fit canvas":`Ajustar al lienzo`,"Exit fullscreen":`Salir de pantalla completa`,"Enter fullscreen":`Pantalla completa`,"Exit fullscreen (Esc)":`Salir de pantalla completa (Esc)`,"Fullscreen is not available in this browser or page":`La pantalla completa no está disponible en este navegador o página`,"Could not exit fullscreen. Press Esc to try again.":`No se pudo salir de pantalla completa. Pulsa Esc.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`No se pudo activar la pantalla completa. Revisa los permisos del navegador o de la página.`,"{count} relations":`{count} relaciones`,"Node notes":`Notas del nodo`,"Close details":`Cerrar detalles`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidencia`,"Start with a node":`Empieza por un nodo`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecciona un componente del diagrama o de la lista para ver su función, campos, métodos y evidencias.`,"Evidence facts":`Hechos documentados`,"Unlock the layout before arranging nodes":`Desbloquea la disposición antes de ajustar los espacios`,Local:`Selección`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope}: espaciado ajustado, {count} nodos movidos`,"Cannot arrange further within the current constraints":`No se puede ajustar más con estas restricciones`,"No spacing changes needed":`No es necesario ajustar el espaciado`,"Generating {format}…":`Generando {format}…`,"{format} downloaded":`{format} descargado`,"The browser could not generate the PNG":`El navegador no pudo generar el PNG`,"The browser could not read the exported SVG":`El navegador no pudo leer el SVG exportado`,"Zoom in":`Acercar`,"Zoom out":`Alejar`,Minimap:`Minimapa`,"Graph navigation":`Navegación del grafo`,"Show graph navigation":`Mostrar navegación`,"Hide graph navigation":`Ocultar navegación`,More:`Más`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Cerrar`,"View details":`Ver detalles`,Appearance:`Apariencia`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar la disposición y la vista originales, y borrar la búsqueda y la selección.`,"Reset: original positions and reading view restored":`Restablecido: posiciones y vista originales restauradas`,Details:`Detalles`,Name:`Nombre`,Description:`Descripción`,"Name is required":`El nombre es obligatorio`,Cancel:`Cancelar`,Save:`Guardar`,"Edit text":`Editar texto`,Evidence:`Evidencia`,"Save changes":`Guardar cambios`,"Graph JSON saved":`Graph JSON guardado`,"Saved into this page, its sibling graph.json and SVGs":`Guardado en esta página, en el graph.json contiguo y en los SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Guardado en esta página y en el graph.json contiguo; SVG sin actualizar: hay que ajustar el diseño`,"Choose the folder containing this page ({page}); edits remain in this page":`Elija la carpeta que contiene esta página ({page}); los cambios permanecen en esta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON descargado; conserva el archivo para guardar los cambios`,"Save cancelled; edits remain in this page":`Guardado cancelado; los cambios permanecen en esta página`,"Save failed; edits remain in this page":`Error al guardar; los cambios permanecen en esta página`,"Synchronous message":`Mensaje síncrono`,"Asynchronous message":`Mensaje asíncrono`,"Return message":`Mensaje de retorno`,"Branch conditions unspecified":`Condiciones de ramas sin especificar`,"Activation: execution interval; offset means nesting":`Activación: intervalo de ejecución; el desplazamiento indica anidación`,"C ID: paired call and return share a color":`ID C: llamada y retorno comparten color`,"par: concurrent branches; vertical position is not order":`par: ramas paralelas; la posición vertical no indica orden`,"Layout needs adjustment; JSON drafts can still be saved":`Ajusta el diseño; puedes guardar el borrador JSON`,"Card wash":`Tinte suave de tarjetas`,yes:`sí`,no:`no`,composition:`composición`,aggregation:`agregación`,inheritance:`herencia`,implementation:`implementación`,"Core state":`Estado principal`,"Ended state":`Estado finalizado`,"Failed state":`Estado fallido`,"In-progress state":`Estado en curso`,"In-progress state: warm to cool as it advances":`Estado en curso: de cálido a frío a medida que avanza`,Transition:`Transición`,"Self-transition: handled without leaving the state":`Autotransición: evento atendido sin salir del estado`,"Key points":`Puntos clave`,"Show key points":`Mostrar puntos clave`,"Hide key points":`Ocultar puntos clave`,"Component relations":`Relaciones entre componentes`,"Platform capabilities":`Capacidades de la plataforma`,"Engineering layers":`Capas del proyecto`,"Overview text":`Texto del resumen`,Badges:`Insignias`,"Badge type":`Tipo de insignia`,"Add badge":`Añadir insignia`,"Remove badge":`Eliminar insignia`,Status:`Estado`,Version:`Versión`,Requirement:`Requisito`,"Overview aligned":`Resumen alineado`,Section:`Sección`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitectura de componentes`,"Platform capability architecture":`Arquitectura de capacidades`,"Engineering layer architecture":`Arquitectura por capas`,"Layout suggestions":`Sugerencias de diseño`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organiza esta vista para mejorar la separación y el espacio de los conectores. Las posiciones actuales se conservan hasta entonces.`,"Shared dependencies":`Dependencias compartidas`,"Source changes":`Cambios en el código`,"Show source changes":`Mostrar cambios en el código`,"Hide source changes":`Ocultar cambios en el código`,"This update":`Esta actualización`,"Show this update":`Mostrar esta actualización`,"Hide this update":`Ocultar esta actualización`,Added:`Añadido`,Changed:`Modificado`,Removed:`Eliminado`,"View notes updated":`Descripción de la vista actualizada`},ru:JSON.parse(`{"Architecture":"Архитектура","Flowchart":"Блок-схема","Sequence":"Последовательность","ER diagram":"ER-диаграмма","Deployment":"Развёртывание","Class diagram":"Диаграмма классов","State diagram":"Диаграмма состояний","Use cases":"Варианты использования","Data flow":"Поток данных","Source code":"Исходный код","Code":"Код","Configuration":"Конфигурация","Schema":"Схема данных","Test":"Тест","Document":"Документ","Framework convention":"Правило фреймворка","Inference":"Предположение","External":"Внешний","Framework":"Фреймворк","Security":"Безопасность","Service":"Сервис","Business":"Бизнес-логика","Data":"Данные","Failure":"Сбой","System":"Система","Component":"Компонент","Database":"База данных","Start":"Начало","End":"Конец","Process":"Процесс","Decision":"Решение","Input":"Вход","Output":"Выход","Subprocess":"Подпроцесс","Actor":"Актор","Participant":"Участник","Entity":"Сущность","Device":"Устройство","Nodes":"Узлы","Container":"Контейнер","Artifact":"Артефакт","Class":"Класс","Interface":"Интерфейс","Abstract class":"Абстрактный класс","State":"Состояние","Initial":"Начальное","Choice":"Выбор","Use case":"Вариант использования","Data store":"Хранилище данных","Initial state":"Начальное состояние","Final state":"Конечное состояние","Core component":"Ключевой компонент","Data / storage":"Данные / хранение","Start / end":"Начало / конец","Components / actors":"Компоненты / акторы","Solid relation":"Сплошная связь","Dashed: notation / convention / inference":"Пунктир: нотация / правило / предположение","Reset":"Сбросить","Dark":"Тёмная","Light":"Светлая","Locked":"Блокировка","Draggable":"Можно перемещать","Unlock the layout first":"Сначала разблокируйте расположение","Space the selected node and its direct neighbors":"Настроить интервалы выбранного узла и его соседей","Space all nodes":"Настроить интервалы всех узлов","Arrange":"Интервалы","Hide details":"Скрыть сведения","Show details":"Показать сведения","Overview":"Обзор","Edges":"Связи","Groups":"Границы","Diagram types":"Типы диаграмм","Search nodes":"Найти узлы","Edge animation":"Анимация связей","On":"Вкл.","Off":"Выкл.","System reduced-motion preference is respected":"Учтена системная настройка уменьшения движения","Matches · {count}":"Найдено · {count}","Nodes · {count}":"Узлы · {count}","No matches. Try a name or responsibility.":"Совпадений нет. Попробуйте имя или назначение.","Legend":"Легенда","Interactive {type}":"Интерактивная диаграмма: {type}","Fit canvas":"Вписать в холст","Exit fullscreen":"Выйти из полноэкранного режима","Enter fullscreen":"На весь экран","Exit fullscreen (Esc)":"Выйти из полноэкранного режима (Esc)","Fullscreen is not available in this browser or page":"Полноэкранный режим недоступен в этом браузере или на этой странице","Could not exit fullscreen. Press Esc to try again.":"Не удалось выйти из полноэкранного режима. Нажмите Esc.","Could not enter fullscreen. Check browser or page permissions and try again.":"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера или страницы.","{count} relations":"Связей: {count}","Node notes":"Примечания к узлу","Close details":"Закрыть сведения","Fields":"Поля","Attributes":"Атрибуты","Methods":"Методы","Source":"Основание","Start with a node":"Начните с узла","Select a component or a list entry to explore its role, fields, methods and source.":"Выберите компонент или пункт списка, чтобы посмотреть назначение, поля, методы и источник.","Evidence facts":"Подтверждённые факты","Unlock the layout before arranging nodes":"Разблокируйте расположение перед настройкой интервалов","Local":"Локально","Full diagram":"Вся диаграмма","{scope} arranged: {count} nodes moved":"{scope}: интервалы настроены, перемещено узлов: {count}","Cannot arrange further within the current constraints":"Текущие ограничения не позволяют улучшить расположение","No spacing changes needed":"Интервалы не требуют изменений","Generating {format}…":"Создание {format}…","{format} downloaded":"{format} скачан","The browser could not generate the PNG":"Браузер не смог создать PNG","The browser could not read the exported SVG":"Браузер не смог прочитать экспортированный SVG","Zoom in":"Увеличить","Zoom out":"Уменьшить","Minimap":"Мини-карта","Graph navigation":"Навигация по графу","Show graph navigation":"Показать навигацию","Hide graph navigation":"Скрыть навигацию","More":"Ещё","Export SVG":"Экспорт SVG","Export PNG":"Экспорт PNG","Close":"Закрыть","View details":"Подробнее","Appearance":"Оформление","Follow system":"Как в системе","Restore the original layout and view, and clear search and selection.":"Восстановить исходное расположение и вид, очистить поиск и выделение.","Reset: original positions and reading view restored":"Сброс: исходное расположение и вид восстановлены","Details":"Сведения","Name":"Имя","Description":"Описание","Name is required":"Имя обязательно","Cancel":"Отмена","Save":"Сохранить","Edit text":"Изменить текст","Evidence":"Основание","Save changes":"Сохранить изменения","Graph JSON saved":"Graph JSON сохранён","Saved into this page, its sibling graph.json and SVGs":"Сохранено в эту страницу, соседний graph.json и SVG","Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":"Сохранено в эту страницу и соседний graph.json; SVG не обновлены: нужно исправить расположение","Choose the folder containing this page ({page}); edits remain in this page":"Выберите папку с этой страницей ({page}); изменения остаются на этой странице","Graph JSON downloaded; keep the file to preserve edits":"Graph JSON скачан; сохраните файл, чтобы не потерять изменения","Save cancelled; edits remain in this page":"Сохранение отменено; изменения остались на странице","Save failed; edits remain in this page":"Не удалось сохранить; изменения остались на странице","Synchronous message":"Синхронное сообщение","Asynchronous message":"Асинхронное сообщение","Return message":"Ответное сообщение","Branch conditions unspecified":"Условия ветвей не указаны","Activation: execution interval; offset means nesting":"Активация: интервал выполнения; смещение означает вложенность","C ID: paired call and return share a color":"Номер C: вызов и возврат одного цвета","par: concurrent branches; vertical position is not order":"par: параллельные ветви; положение по вертикали не задаёт порядок","Layout needs adjustment; JSON drafts can still be saved":"Исправьте расположение; черновик JSON можно сохранить","Card wash":"Лёгкая заливка карточек","yes":"да","no":"нет","composition":"композиция","aggregation":"агрегация","inheritance":"наследование","implementation":"реализация","Core state":"Ключевое состояние","Ended state":"Завершённое состояние","Failed state":"Состояние сбоя","In-progress state":"Состояние в процессе","In-progress state: warm to cool as it advances":"Состояние в процессе: от тёплого цвета к холодному по мере продвижения","Transition":"Переход","Self-transition: handled without leaving the state":"Петля: событие обрабатывается без выхода из состояния","Key points":"Ключевые выводы","Show key points":"Показать ключевые выводы","Hide key points":"Скрыть ключевые выводы","Component relations":"Связи компонентов","Platform capabilities":"Возможности платформы","Engineering layers":"Слои проекта","Overview text":"Текст обзора","Badges":"Метки","Badge type":"Тип метки","Add badge":"Добавить метку","Remove badge":"Удалить метку","Status":"Статус","Version":"Версия","Requirement":"Требование","Overview aligned":"Обзор выровнен","Section":"Раздел","Cancelled":"Отменено","Component relationship architecture":"Архитектура компонентов","Platform capability architecture":"Архитектура возможностей платформы","Engineering layer architecture":"Слоистая архитектура","Layout suggestions":"Рекомендации по размещению","Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":"Упорядочьте эту схему, чтобы улучшить зазоры и расстояния между связями. До этого текущие позиции сохраняются.","Shared dependencies":"Общие зависимости","Source changes":"Изменения в коде","Show source changes":"Показать изменения в коде","Hide source changes":"Скрыть изменения в коде","This update":"Это обновление","Show this update":"Показать это обновление","Hide this update":"Скрыть это обновление","Added":"Добавлено","Changed":"Изменено","Removed":"Удалено","View notes updated":"Описание представления обновлено"}`),pt:{Architecture:`Arquitetura`,Flowchart:`Fluxograma`,Sequence:`Sequência`,"ER diagram":`Diagrama ER`,Deployment:`Implantação`,"Class diagram":`Diagrama de classes`,"State diagram":`Diagrama de estados`,"Use cases":`Casos de uso`,"Data flow":`Fluxo de dados`,"Source code":`Código-fonte`,Code:`Código`,Configuration:`Configuração`,Schema:`Esquema`,Test:`Teste`,Document:`Documento`,"Framework convention":`Convenção do framework`,Inference:`Inferência`,External:`Externo`,Framework:`Framework`,Security:`Segurança`,Service:`Serviço`,Business:`Negócio`,Data:`Dados`,Failure:`Falha`,System:`Sistema`,Component:`Componente`,Database:`Banco de dados`,Start:`Início`,End:`Fim`,Process:`Processo`,Decision:`Decisão`,Input:`Entrada`,Output:`Saída`,Subprocess:`Subprocesso`,Actor:`Ator`,Participant:`Participante`,Entity:`Entidade`,Device:`Dispositivo`,Nodes:`Nós`,Container:`Contêiner`,Artifact:`Artefato`,Class:`Classe`,Interface:`Interface`,"Abstract class":`Classe abstrata`,State:`Estado`,Initial:`Inicial`,Choice:`Escolha`,"Use case":`Caso de uso`,"Data store":`Armazenamento de dados`,"Initial state":`Estado inicial`,"Final state":`Estado final`,"Core component":`Componente central`,"Data / storage":`Dados / armazenamento`,"Start / end":`Início / fim`,"Components / actors":`Componentes / atores`,"Solid relation":`Relação contínua`,"Dashed: notation / convention / inference":`Tracejado: notação / convenção / inferência`,Reset:`Redefinir`,Dark:`Escuro`,Light:`Claro`,Locked:`Bloqueado`,Draggable:`Arrastável`,"Unlock the layout first":`Desbloqueie o layout primeiro`,"Space the selected node and its direct neighbors":`Ajustar o espaçamento do nó selecionado e dos vizinhos diretos`,"Space all nodes":`Ajustar o espaçamento de todos os nós`,Arrange:`Organizar`,"Hide details":`Ocultar detalhes`,"Show details":`Mostrar detalhes`,Overview:`Visão geral`,Edges:`Relações`,Groups:`Limites`,"Diagram types":`Tipos de diagrama`,"Search nodes":`Buscar nós`,"Edge animation":`Animação das conexões`,On:`Ativada`,Off:`Desativada`,"System reduced-motion preference is respected":`A preferência do sistema por movimento reduzido é respeitada`,"Matches · {count}":`Resultados · {count}`,"Nodes · {count}":`Nós · {count}`,"No matches. Try a name or responsibility.":`Nenhum resultado. Tente um nome ou responsabilidade.`,Legend:`Legenda`,"Interactive {type}":`{type} interativo`,"Fit canvas":`Ajustar à tela`,"Exit fullscreen":`Sair da tela cheia`,"Enter fullscreen":`Entrar em tela cheia`,"Exit fullscreen (Esc)":`Sair da tela cheia (Esc)`,"Fullscreen is not available in this browser or page":`A tela cheia não está disponível neste navegador ou nesta página`,"Could not exit fullscreen. Press Esc to try again.":`Não foi possível sair da tela cheia. Pressione Esc para tentar novamente.`,"Could not enter fullscreen. Check browser or page permissions and try again.":`Não foi possível entrar em tela cheia. Verifique as permissões do navegador ou da página e tente novamente.`,"{count} relations":`{count} relações`,"Node notes":`Notas do nó`,"Close details":`Fechar detalhes`,Fields:`Campos`,Attributes:`Atributos`,Methods:`Métodos`,Source:`Evidência`,"Start with a node":`Comece por um nó`,"Select a component or a list entry to explore its role, fields, methods and source.":`Selecione um componente ou item da lista para explorar sua função, campos, métodos e fonte.`,"Evidence facts":`Fatos comprovados`,"Unlock the layout before arranging nodes":`Desbloqueie o layout antes de organizar os nós`,Local:`Local`,"Full diagram":`Diagrama completo`,"{scope} arranged: {count} nodes moved":`{scope} organizado: {count} nós movidos`,"Cannot arrange further within the current constraints":`Não é possível organizar mais com as restrições atuais`,"No spacing changes needed":`Nenhum ajuste de espaçamento necessário`,"Generating {format}…":`Gerando {format}…`,"{format} downloaded":`{format} baixado`,"The browser could not generate the PNG":`O navegador não conseguiu gerar o PNG`,"The browser could not read the exported SVG":`O navegador não conseguiu ler o SVG exportado`,"Zoom in":`Ampliar`,"Zoom out":`Reduzir`,Minimap:`Minimapa`,"Graph navigation":`Navegação do grafo`,"Show graph navigation":`Mostrar navegação do grafo`,"Hide graph navigation":`Ocultar navegação do grafo`,More:`Mais`,"Export SVG":`Exportar SVG`,"Export PNG":`Exportar PNG`,Close:`Fechar`,"View details":`Ver detalhes`,Appearance:`Aparência`,"Follow system":`Sistema`,"Restore the original layout and view, and clear search and selection.":`Restaurar o layout e a visualização originais e limpar a busca e a seleção.`,"Reset: original positions and reading view restored":`Redefinido: posições e visualização originais restauradas`,Details:`Detalhes`,Name:`Nome`,Description:`Descrição`,"Name is required":`O nome é obrigatório`,Cancel:`Cancelar`,Save:`Salvar`,"Edit text":`Editar texto`,Evidence:`Evidência`,"Save changes":`Salvar alterações`,"Graph JSON saved":`Graph JSON salvo`,"Saved into this page, its sibling graph.json and SVGs":`Salvo nesta página, no graph.json ao lado e nos SVG`,"Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment":`Salvo nesta página e no graph.json ao lado; SVG não atualizados: o layout precisa de ajuste`,"Choose the folder containing this page ({page}); edits remain in this page":`Escolha a pasta desta página ({page}); as alterações permanecem nesta página`,"Graph JSON downloaded; keep the file to preserve edits":`Graph JSON baixado; guarde o arquivo para preservar as alterações`,"Save cancelled; edits remain in this page":`Salvamento cancelado; as alterações permanecem nesta página`,"Save failed; edits remain in this page":`Falha ao salvar; as alterações permanecem nesta página`,"Synchronous message":`Mensagem síncrona`,"Asynchronous message":`Mensagem assíncrona`,"Return message":`Mensagem de retorno`,"Branch conditions unspecified":`Condições dos ramos não indicadas`,"Activation: execution interval; offset means nesting":`Ativação: intervalo de execução; deslocamento indica aninhamento`,"C ID: paired call and return share a color":`ID C: chamada e retorno têm a mesma cor`,"par: concurrent branches; vertical position is not order":`par: ramos paralelos; posição vertical não indica ordem`,"Layout needs adjustment; JSON drafts can still be saved":`Ajuste o layout; o rascunho JSON pode ser salvo`,"Card wash":`Tom suave dos cartões`,yes:`sim`,no:`não`,composition:`composição`,aggregation:`agregação`,inheritance:`herança`,implementation:`implementação`,"Core state":`Estado central`,"Ended state":`Estado encerrado`,"Failed state":`Estado com falha`,"In-progress state":`Estado em andamento`,"In-progress state: warm to cool as it advances":`Estado em andamento: do quente ao frio conforme avança`,Transition:`Transição`,"Self-transition: handled without leaving the state":`Autotransição: evento tratado sem sair do estado`,"Key points":`Pontos-chave`,"Show key points":`Mostrar pontos-chave`,"Hide key points":`Ocultar pontos-chave`,"Component relations":`Relações entre componentes`,"Platform capabilities":`Capacidades da plataforma`,"Engineering layers":`Camadas do projeto`,"Overview text":`Texto da visão geral`,Badges:`Emblemas`,"Badge type":`Tipo de emblema`,"Add badge":`Adicionar emblema`,"Remove badge":`Remover emblema`,Status:`Estado`,Version:`Versão`,Requirement:`Requisito`,"Overview aligned":`Visão geral alinhada`,Section:`Seção`,Cancelled:`Cancelado`,"Component relationship architecture":`Arquitetura de componentes`,"Platform capability architecture":`Arquitetura de capacidades`,"Engineering layer architecture":`Arquitetura em camadas`,"Layout suggestions":`Sugestões de disposição`,"Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.":`Organize esta vista para melhorar as folgas e os espaçamentos das ligações. As posições atuais são preservadas até lá.`,"Shared dependencies":`Dependências compartilhadas`,"Source changes":`Alterações no código`,"Show source changes":`Mostrar alterações no código`,"Hide source changes":`Ocultar alterações no código`,"This update":`Esta atualização`,"Show this update":`Mostrar esta atualização`,"Hide this update":`Ocultar esta atualização`,Added:`Adicionado`,Changed:`Alterado`,Removed:`Removido`,"View notes updated":`Descrição da visão atualizada`}};let he=[`en`,...Object.keys(me)];function ge(e,t,n={}){let r=e??`zh-CN`,i=Object.hasOwn(me,r)?me[r]:void 0;return(i&&Object.hasOwn(i,t)?i[t]:t).replace(/\\{(\\w+)\\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}let k=(e,t)=>[...e].reduce((e,n)=>e+t*(/[^\\u0000-\\u00ff]|[MWmw@%&]/.test(n)?1:/[A-Z]/.test(n)?.8:6.8/12),0),_e=`\\\\p{Script=Han}\\\\p{Script=Hiragana}\\\\p{Script=Katakana}\\\\u3000-\\\\u303f\\\\uff00-\\\\uffef`,ve=RegExp(`[${_e}]`,`u`),ye=RegExp(`[${_e}]|[^${_e}]+`,`gu`),be=/(?<=[_./\\\\\\-=,;:|&)>\\]}])|(?<=[a-z0-9])(?=[A-Z])/u,xe=new Set([...`,。、.;:!?)]}〕】》〉」』”’…`]),Se=new Set([...`([{〔【《〈「『“‘`]),Ce=(e,t)=>!Se.has([...e].at(-1))&&!xe.has([...t][0]);function we(e,t,n){let r=[];for(let i of e.match(ye))if(ve.test(i)||k(i,t)<=n)r.push(i);else for(let e of i.split(be))r.push(...k(e,t)<=n?[e]:e);return r}function A(e,t,n=O.body,r=n*1.5){let i=String(e??``);if(!i)return{lines:[],width:0,height:0,lineHeight:r};let a=Math.max(1,t),o=[];for(let e of i.split(/\\r?\\n/)){let t=``,r=0,i=[],s=()=>{o.push(t),t=``,r=0,i=[]};for(let c of e.match(/\\s+|\\S+/g)??[]){let e=k(c,n);if(t&&e<=a&&r+e>a&&s(),i.push(t.length),e<=a||/^\\s/.test(c)){for(let e of c){let i=k(e,n);t&&r+i>a&&s(),t+=e,r+=i}continue}for(let e of we(c,n,a)){let c=k(e,n);if(t&&r+c>a){if(Ce(t,e))s();else{let e=i.length-1;for(;e>=0&&!(i[e]>0&&Ce(t.slice(0,i[e]),t.slice(i[e])));)e--;if(e>=0){let a=i[e];o.push(t.slice(0,a)),t=t.slice(a),r=k(t,n),i=i.slice(e).map(e=>e-a)}}}i.push(t.length),t+=e,r+=c}}o.push(t)}return{lines:o,width:Math.ceil(Math.max(...o.map(e=>k(e,n)))),height:o.length*r,lineHeight:r}}let j=Object.freeze({pad:14,plate:24,textX:48,tagGap:8,tagPad:8,titleLine:26,subtitleLine:24,sourceLine:20,chipLine:24,chipGap:6,minHeight:64,maxWidth:360}),Te=e=>e.source?.file?`${e.source.file.split(`/`).at(-1)}:${e.source.lineStart}`:``;function Ee(e,t,n){let r=e.lastIndexOf(`:`),i=e.slice(0,r),a=e.slice(r);for(let r=i.length-1;k(e,n)>t&&r>4;r--)e=`${i.slice(0,Math.ceil(r/2))}…${i.slice(i.length-Math.floor(r/2))}${a}`;return e}let De=(e,t)=>{let n=ge(t,fe[e.kind]??e.kind);return{text:n,width:Math.ceil(k(n,O.small)+n.length*.6)+2*j.tagPad}};function Oe(e,t,n=!1,r=0){if(n){let t=A(e.label,e.size.width-30,O.title,26),n=A(e.subtitle??``,e.size.width-30,O.body,24);return{title:t,subtitle:n,minHeight:Math.max(100,65+t.height+n.height)}}let i=De(e,t),a=e.size.width-j.textX-j.pad,o=A(e.label,a-i.width-j.tagGap-r,O.title,j.titleLine),s=A(e.subtitle??``,a,O.body,j.subtitleLine),c=A(Ee(Te(e),a,O.small),a,O.small,j.sourceLine),l=ke(e,a),u=l.length?(l.at(-1).row+1)*j.chipLine:0,d=j.pad+o.height+(s.height?4+s.height:0)+(c.height?6+c.height:0)+(u?6+u:0)+j.pad;return{title:o,subtitle:s,source:c,tag:i,chips:l,contentHeight:d,minHeight:Math.max(j.minHeight,d)}}function ke(e,t){let n=[],r=0,i=0;for(let a of[...(e.badges??[]).map(e=>e.label),...e.dependencyTags??[]]){let e=Math.min(t,Math.ceil(k(a,O.small)+a.length*.6)+2*j.tagPad);r&&r+e>t&&(i++,r=0),n.push({text:a,x:r,row:i,width:e}),r+=e+j.chipGap}return n}function Ae(e,t=f.labelWidth){let n=A(e,t);return{...n,width:n.lines.length?Math.max(24,n.width+12):0,height:n.lines.length?n.height+6:0}}function je(e,t){let n=t.map(e=>e.text).join(` `),r=t.flatMap((e,n)=>[...n?[t[n-1].role]:[],...Array.from({length:e.text.length},()=>e.role)]),i=0,a=e.map(e=>{for(;n[i]===`\\r`||n[i]===`\n`;)i++;if(!n.startsWith(e,i))return null;let t=[];for(let n=0;n`,`>`).replaceAll(`"`,`"`)}function N(e,t){return{value:String(e??``),width:t}}function P(e,t,n,r,i=``){let a=n&&typeof n==`object`&&`width`in n,o=Number(i.match(/font-size:([\\d.]+)px/)?.[1])||{title:O.title,"shape-title":O.title,"participant-title":O.title,body:O.body,"field-name":O.body,"field-type":O.body,member:O.body,"entity-title":O.title}[r]||O.small;if(n&&typeof n==`object`&&`runs`in n)return`${n.runs.map(e=>{let t=n.colors[e.role];return t?`${Ne(e.text)}`:Ne(e.text)}).join(``)}`;let s=a?n.value:n;if(a&&A(s,1/0,o).width>n.width){let e=Math.max(0,n.width-A(`…`,1/0,o).width);s=e?(A(s,e,o).lines[0]??``)+`…`:`…`}return`${Ne(s)}`}function Pe(e,t,n,r,i=1/0,a=``){if(r<=0||i<=0)return``;let o=A(n,r,O.title,29),s=A(a,r,O.body,23.2),c=Math.min(o.lines.length,Math.max(1,Math.floor(i/o.lineHeight))),l=Math.min(s.lines.length,Math.max(0,Math.floor((i-c*o.lineHeight-5)/s.lineHeight))),u=c*o.lineHeight+(l?5+l*s.lineHeight:0),d=t-u/2,f=(t,n,r,i)=>t.lines.slice(0,n).map((a,o)=>P(e,r+o*t.lineHeight,a+(o===n-1&&n${p}`:p}function F(e,t={}){return e.map(([e,n])=>`<${e}${Object.entries({...n,...Object.keys(t).length?{class:`node-surface`}:{},...t,...n.fill===void 0?{}:{fill:n.fill}}).map(([e,t])=>` ${e}="${Ne(t)}"`).join(``)}/>`).join(``)}let I=(e,t,n,r=10,i=e.size.height)=>[[`rect`,{x:t,y:n,width:e.size.width,height:i,rx:r}]],Fe=(e,t,n)=>{let{width:r,height:i}=e.size,a=n+2+5,o=n+i-2-5;return[[`path`,{d:`M${t+12} ${a}Q${t+12} ${n+2} ${t+r/2} ${n+2}T${t+r-12} ${a}V${o}Q${t+r-12} ${n+i-2} ${t+r/2} ${n+i-2}T${t+12} ${o}Z`}],[`ellipse`,{cx:t+r/2,cy:a,rx:r/2-12,ry:5,fill:`none`}]]},Ie=[[.08,0],[.92,0],[1,.5],[.92,1],[.08,1],[0,.5]],Le=(e,t,n,r)=>[[`polygon`,{points:r.map(([r,i])=>`${t+r*e.size.width},${n+i*e.size.height}`).join(` `)}]],Re=(e,t,n)=>[[`polygon`,{points:`${t+e.size.width/2},${n} ${t+e.size.width},${n+e.size.height/2} ${t+e.size.width/2},${n+e.size.height} ${t},${n+e.size.height/2}`}]],ze=(e,t,n)=>{let r=t+e.size.width/2;return[[`circle`,{cx:r,cy:n+13,r:11}],[`path`,{d:`M${r} ${n+24}v29M${r-20} ${n+35}h40M${r} ${n+53}l-17 23M${r} ${n+53}l17 23`,fill:`none`}]]},Be=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2});function L(e,t,n=0,r=0){let i=Be(e),a=typeof r==`number`?{left:r,right:r,top:r,bottom:r}:{left:0,right:0,top:0,bottom:0,...r};return t===`left`||t===`right`?{x:e.position.x+(t===`left`?a.left:e.size.width-a.right),y:i.y+n}:{x:i.x+n,y:e.position.y+(t===`top`?a.top:e.size.height-a.bottom)}}function Ve(e,t,n=0,r=10){let{x:i,y:a}=e.position,{width:o,height:s}=e.size,c=Be(e),l=Math.max(0,Math.min(r,o/2,s/2));if(t===`left`||t===`right`){let r=c.y+n;if(ra+s)return L(e,t,n);let u=ra+s-l?a+s-l:r,d=Math.sqrt(Math.max(0,l*l-(r-u)**2));return{x:t===`left`?i+l-d:i+o-l+d,y:r}}let u=c.x+n;if(ui+o)return L(e,t,n);let d=ui+o-l?i+o-l:u,f=Math.sqrt(Math.max(0,l*l-(u-d)**2));return{x:u,y:t===`top`?a+l-f:a+s-l+f}}function He(e,t,n=0,r=0,i=0){let a=Be(e),o=Math.max(1,e.size.width/2-r),s=Math.max(1,e.size.height/2-i);if(t===`left`||t===`right`){let r=a.y+n;if(Math.abs(n)>s)return L(e,t,n);let i=o*Math.sqrt(Math.max(0,1-((r-a.y)/s)**2));return{x:a.x+(t===`left`?-i:i),y:r}}let c=a.x+n;if(Math.abs(n)>o)return L(e,t,n);let l=s*Math.sqrt(Math.max(0,1-((c-a.x)/o)**2));return{x:c,y:a.y+(t===`top`?-l:l)}}function Ue(e,t,n=0,r){let i=r.map(([t,n])=>({x:e.position.x+t*e.size.width,y:e.position.y+n*e.size.height})),a=Be(e),o=t===`left`||t===`right`,s=o?a.y+n:a.x+n,c=[];for(let e=0;eMath.max(r,a)||r===a)continue;let l=(s-r)/(a-r);c.push((o?t.x:t.y)+l*((o?n.x:n.y)-(o?t.x:t.y)))}if(!c.length)return L(e,t,n);let l=t===`left`||t===`top`?Math.min(...c):Math.max(...c);return o?{x:l,y:s}:{x:s,y:l}}function We(e,t,n=0,r=0){let i=e.position.x+e.size.width/2,a=e.position.y+r;return t===`left`?{x:i-20,y:a+35}:t===`right`?{x:i+20,y:a+35}:t===`top`?{x:i,y:a+2}:{x:i+Math.sign(n||1)*Math.min(17,Math.abs(n)),y:a+76}}let Ge=(e,t,n)=>e.kind===`actor`?ze(e,t,n):I(e,t,n,7,Ke(e));function Ke(e){let t=(e.size?.width??280)-28,n=A(e.label,t,20,26).lines.length,r=e.subtitle?A(e.subtitle,t,16,22).lines.length:0;return(e.kind===`actor`?O.sequenceActorHeader+(e.subtitle?22:0):O.sequenceHeader)+Math.max(0,n-1)*26+Math.max(0,r-1)*22}function qe(e,t,n,r,i,a,o){let s=t+e.size.width/2,c=e.kind===`actor`,l=Ke(e),u=F(Ge(e,t,n),{fill:r,stroke:i,"stroke-width":1.5}),d=A(e.label,e.size.width-28,20,26).lines,f=n+(c?98:e.subtitle?44:53),p=(c?``:P(s,n+20,ge(o,fe[e.kind]??e.kind),`stereotype`,` text-anchor="middle"`))+d.map((e,t)=>P(s,f+t*26,e,`participant-title`,` text-anchor="middle"`)).join(``),m=e.subtitle?A(e.subtitle,e.size.width-28,16,22).lines.map((e,t)=>P(s,f+(d.length-1)*26+(c?28:22)+t*22,e,`body`,` text-anchor="middle"`)).join(``):``,h=(e.executionRects??[]).map(e=>``).join(``);return`${Ne([e.label,e.subtitle].filter(Boolean).join(` · `))}${u}${p}${m}${h}`}var Je={dashedKinds:[`return`],markers:{async:{end:`arrow-open`},return:{end:`arrow-open`}},id:`sequence`,label:`Sequence`,nodeKinds:[`actor`,`participant`,`external`,`service`,`database`],groupKinds:[`alt`,`opt`,`loop`,`par`],edgeKinds:[`sync`,`async`,`return`],render:qe,outline:Ge,sequence:!0,selectionHeight:Ke,edgeLabel:e=>`${String(e.order).padStart(2,`0`)} · ${e.label??``}`,validateEdge(e,t,n,{requireString:r,sequenceOrders:i}){!Number.isInteger(e?.order)||e.order<1?n.push(`${t}.order must be a positive integer for sequence`):i.has(e.order)?n.push(`${t}.order duplicates ${e.order}`):i.add(e.order),r(e?.label,`${t}.label`,n)}};let Ye=e=>Math.max(0,(e.size.height-104-(e.subtitle?24:0))/2),Xe=e=>({width:e.size.width/Math.SQRT2-8,height:e.size.height/Math.SQRT2-8}),Ze=(e,t,n)=>e.kind===`actor`?ze(e,t,n+Ye(e)):[[`ellipse`,{cx:t+e.size.width/2,cy:n+e.size.height/2,rx:e.size.width/2,ry:e.size.height/2}]],Qe=(e,t,n)=>e.kind===`actor`?We(e,t,n,Ye(e)):He(e,t,n);function $e(e,t,n,r,i,a){let o=t+e.size.width/2;if(e.kind===`actor`)return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.5})}${P(o,n+Ye(e)+98,N(e.label,e.size.width-12),`shape-title`,` text-anchor="middle" style="fill:${a.ink}"`)}${e.subtitle?P(o,n+Ye(e)+122,N(e.subtitle,e.size.width-12),`body`,` text-anchor="middle"`):``}`;let s=Xe(e);return`${F(Ze(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,n+e.size.height/2,e.label,s.width,s.height,e.subtitle)}`}var et={dashedKinds:[`include`,`extend`],id:`usecase`,label:`Use cases`,nodeKinds:[`actor`,`usecase`],groupKinds:[`system`],edgeKinds:[`association`,`include`,`extend`],render:$e,outline:Ze,anchor:Qe,textArea:Xe,undirected:[`association`],markers:{include:{end:`arrow-open`},extend:{end:`arrow-open`}},edgeLabel:e=>{let t={include:`«include»`,extend:`«extend»`}[e.kind];return t?e.label&&e.label!==e.kind?`${t} · ${e.label}`:t:e.label??``}};let tt=e=>e.subtitle?14:e.size.width/2,nt=[`entry`,`do`,`exit`],R={side:16,pad:8,line:20,keyWidth:64};function rt(e){let t=e.kind===`state`?nt.filter(t=>typeof e[t]==`string`&&e[t].trim()).map(t=>({key:t,lines:A(e[t],e.size.width-2*R.side-R.keyWidth,O.small,R.line).lines})):[];return{rows:t,height:t.length?t.reduce((e,t)=>e+t.lines.length,0)*R.line+2*R.pad:0}}let it=2*R.side+R.keyWidth,at=e=>{let{height:t}=rt(e);return t?{x:R.side,y:e.size.height-t,width:e.size.width-2*R.side,height:t}:null},ot=(e,t,n)=>[`initial`,`final`].includes(e.kind)?[[`circle`,{cx:t+tt(e),cy:n+e.size.height/2,r:e.kind===`initial`?12:13}]]:e.kind===`choice`?Re(e,t,n):I(e,t,n,12),st=(e,t,n)=>{if([`initial`,`final`].includes(e.kind)){let r=e.kind===`initial`?12:13,i=tt(e)-e.size.width/2;return He({...e,position:{...e.position,x:e.position.x+i}},t,n-([`top`,`bottom`].includes(t)?i:0),e.size.width/2-r,e.size.height/2-r)}return e.kind===`choice`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):L(e,t,n)},ct=e=>{if([`initial`,`final`].includes(e.kind)&&e.subtitle)return{x:42,y:8,width:e.size.width-50,height:e.size.height-16};let t=rt(e).height,n={width:e.kind===`choice`?e.size.width/2-8:e.size.width-24,height:e.kind===`choice`?e.size.height/2-8:e.size.height-16-t};return t?{x:12,y:8,...n}:n};function lt(e,t,n,r,i){let{rows:a,height:o}=rt(e);if(!a.length)return``;let s=n+e.size.height-o,c=0;return`${a.map(e=>e.lines.map((n,r)=>{let a=s+R.pad+c++*R.line+15;return(r?``:P(t+R.side,a,`${e.key} /`,`field-key`))+P(t+R.side+R.keyWidth,a,n,`entity-meta`,` style="fill:${i.ink}"`)}).join(``)).join(``)}`}function ut(e,t,n,r,i,a){let o=t+e.size.width/2,s=n+e.size.height/2;if([`initial`,`final`].includes(e.kind)){let r=ct(e),o=e.kind===`final`;return`${F(ot(e,t,n),{fill:o?a.surface:i,stroke:i,"stroke-width":1})}${o?``:``}${e.subtitle?Pe(t+r.x+r.width/2,s,e.label,r.width,r.height,e.subtitle):``}`}let c=ct(e),l=n+(e.size.height-rt(e).height)/2;return`${F(ot(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(o,l,e.label,c.width,c.height,e.subtitle)}${lt(e,t,n,i,a)}`}let dt=e=>[{text:e.label,role:`trigger`},...e.guard?[{text:`[${e.guard}]`,role:`guard`}]:[],...e.action?[{text:`/ ${e.action}`,role:`effect`}]:[]].filter(e=>e.text);var ft={id:`state`,label:`State diagram`,nodeKinds:[`initial`,`state`,`final`,`choice`],groupKinds:[],edgeKinds:[`transition`],render:ut,outline:ot,anchor:st,textArea:ct,activityArea:at,curvedSelfLoops:!0,markers:{transition:{end:`arrow-open`}},edgeLabel:e=>dt(e).map(e=>e.text).join(` `),edgeLabelParts:dt,labelRoleColors:{trigger:`ink`,guard:`guard`},legend:{neutral:`State`,core:`Core state`,goal:`Core state`,ended:`Ended state`,failed:`Failed state`,flight:`In-progress state: warm to cool as it advances`,solid:`Transition`},validateNode(e,t,n){for(let r of nt)e?.[r]!==void 0&&(typeof e[r]!=`string`||!e[r].trim()?n.push(`${t}.${r} must be a non-empty string`):e.kind!==`state`&&n.push(`${t}.${r} is only supported on state nodes`))},validateEdge(e,t,n){for(let r of[`guard`,`action`])e?.[r]!==void 0&&typeof e[r]!=`string`&&n.push(`${t}.${r} must be a string`)}};let pt=(e,t,n=0)=>e.xt.x-n&&e.yt.y-n,mt=e=>e.points.slice(1).map((t,n)=>{let r=e.points[n];return{x:Math.min(r.x,t.x)-6,y:Math.min(r.y,t.y)-6,width:Math.abs(t.x-r.x)+12,height:Math.abs(t.y-r.y)+12}}),z=(e,t)=>e?.id??String(t);function ht(e){let t=new Map((e.groups??[]).map(e=>[e.id,e])),n=new Map,r=(e,n=new Set)=>{if(!e.parentId||n.has(e.id))return``;n.add(e.id);let i=t.get(e.parentId);return i?r(i,n)+`${encodeURIComponent(i.id)}:${encodeURIComponent(e.parentOperandId)}/`:``};for(let e of t.values())if(Array.isArray(e.operands))for(let[t,i]of e.operands.entries())for(let a of Array.isArray(i?.edgeIds)?i.edgeIds:[])n.set(a,r(e)+`${encodeURIComponent(e.id)}:${encodeURIComponent(z(i,t))}`);return n}function gt(e,t,n,r,i=new Set){if(i.has(e.id))return[];let a=new Set(i).add(e.id),o=r.filter(r=>r.parentId===e.id&&r.parentOperandId===z(t,n));return[...t.edgeIds??[],...o.flatMap(e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,r,a)))]}function _t(e){let t=[],n=new Map(e.edges.map(e=>[e.id,e])),r=e.groups??[],i=new Map;for(let a of r){let o=`group ${a.id}.operands`;if(e.meta.diagramType!==`sequence`){(a.operands!==void 0||a.parentOperandId!==void 0||a.loop!==void 0)&&t.push(`${o} is only supported for sequence`);continue}if(a.parentId!==void 0||a.parentOperandId!==void 0){let e=r.find(e=>e.id===a.parentId);(!e||!Array.isArray(e.operands)||!e.operands.some((e,t)=>z(e,t)===a.parentOperandId))&&t.push(`group ${a.id} unknown parent operand ${a.parentId}/${a.parentOperandId}`)}let s=new Set([a.id]),c=r.find(e=>e.id===a.parentId);for(;c;){if(s.has(c.id)){t.push(`group ${a.id} parent cycle at ${c.id}`);break}s.add(c.id),c=r.find(e=>e.id===c.parentId)}if(a.operands===void 0&&a.kind!==`par`&&a.loop===void 0&&a.parentId===void 0)continue;let l=[`alt`,`par`].includes(a.kind);if(!Array.isArray(a.operands)||(l?a.operands.length<2:a.operands.length!==1)){t.push(`${o} needs ${l?`at least two branches`:`exactly one branch`}`);continue}a.kind===`loop`?(!Number.isInteger(a.loop?.min)||a.loop.min<0||!(a.loop?.max===`*`||Number.isInteger(a.loop?.max)&&a.loop.max>=a.loop.min))&&t.push(`group ${a.id}.loop needs a non-negative min and max >= min (or *)`):a.loop!==void 0&&t.push(`group ${a.id}.loop is only supported for loop`);let u=new Set;for(let[e,s]of a.operands.entries()){let c=`${o}[${e}] (${String(s?.id??e)})`;if(!s||typeof s!=`object`||Array.isArray(s)){t.push(`${c} must be an object`);continue}s.id!==void 0&&(typeof s.id!=`string`||!s.id.trim())&&t.push(`${c}.id must be a non-empty string`),a.kind!==`alt`&&s.id===void 0&&t.push(`${c}.id is required`);let l=z(s,e);u.has(l)&&t.push(`${c} duplicate operand id`),u.add(l);let d=a.kind===`par`?`label`:`guard`;(typeof s[d]!=`string`||!s[d].trim())&&t.push(`${c}.${d} must be a non-empty string`),a.kind===`alt`&&s.guard?.trim?.()===`else`&&e!==a.operands.length-1&&t.push(`${c} else must be last and unique`),s.body!==void 0&&(typeof s.body!=`string`||!s.body.trim())&&t.push(`${c}.body must be a non-empty string`);let f=r.filter(e=>e.parentId===a.id&&e.parentOperandId===l);if(!Array.isArray(s.edgeIds)||!s.edgeIds.length&&!s.body?.trim?.()&&!f.length){t.push(`${c}.edgeIds must be an array with messages, body or a child fragment`);continue}for(let e of s.edgeIds)(typeof e!=`string`||!n.has(e))&&t.push(`${c} unknown edge ${String(e)}`),i.has(e)&&t.push(`${c} duplicate edge ${e}, already in ${i.get(e)}`),i.set(e,`${a.id}/${l}`)}}if(t.length)return t;for(let e of r){let i=-1/0;for(let[a,o]of(e.operands??[]).entries()){let s=gt(e,o,a,r).map(e=>n.get(e)?.order).filter(Number.isFinite);s.length&&Math.min(...s)<=i&&t.push(`group ${e.id}.operands order ranges must be ordered and non-interleaving`),s.length&&(i=Math.max(...s))}}return t}function vt(e,t){let n=0,r=t.find(t=>t.id===e.parentId),i=new Set([e.id]);for(;r&&!i.has(r.id);)i.add(r.id),n++,r=t.find(e=>e.id===r.parentId);return n}let yt=e=>A(e.label,Math.min(f.headingWidth,Math.max(1,(e.size?.width??1/0)-88)),15.12,22);function bt(e,t){let n={...e.position,...e.size},r=yt(e),i={width:Math.min(r.width+16,n.width-88),height:Math.max(24,r.height+8),lines:r.lines};return[n.x+16,...t.map(e=>e.x+e.width+12)].map(e=>({x:e,y:n.y+6,...i})).find(e=>e.x>=n.x+16&&e.x+e.width<=n.x+n.width-64&&!t.some(t=>pt(e,t,4)))}function xt(e,t,n,r,i){let a={...e.position,...e.size},o=a.y+a.height,s=[...t.entries()],c=e=>e.points.some(e=>e.x>=a.x&&e.x<=a.x+a.width&&e.y>a.y&&e.yc(e)).map(([,e])=>e),u=[`group ${e.id}: alt branch conditions are unspecified (operands missing)`],d=[...i?[i]:[],{x:a.x+a.width-52,y:a.y,width:52,height:36},...s.flatMap(([,e])=>[e.labelBox,...mt(e)]),...r],f=A(ge(n,`Branch conditions unspecified`),Math.max(1,a.width-32),14,20),p={width:f.width+8,height:f.height+4},m=[a.x+16,...d.map(e=>e.x+e.width+8),a.x+a.width-p.width-16],h=Math.min(...l.map(e=>Math.min(e.labelBox.y,...e.points.map(e=>e.y)))),g=[a.y+6,h,...l.map(e=>e.points[0].y-p.height-6)].flatMap(e=>m.map(t=>({x:t,y:e,...p}))).find(e=>e.x>=a.x+8&&e.x+e.width<=a.x+a.width-8&&e.y>=a.y+6&&e.y+e.height<=o-6&&!d.some(t=>pt(e,t,2)));return g||u.push(`layout: group ${e.id} has no room for guard 1; shorten the guard or adjust the frame/participant spacing`),{warnings:u,guards:[{...g??{x:a.x+16,y:a.y+38,...p},lines:f.lines,operandId:z(null,0)}]}}function St(e,t,n,r=[],i=[]){let a=[],o=[],s=[],c=[],l=[],u={...e.position,...e.size},d=u.y+u.height,p=r.find(t=>t.id===e.parentId);p&&!(u.x>=p.position.x+8&&u.x+u.width<=p.position.x+p.size.width-8&&u.y>=p.position.y+36&&d<=p.position.y+p.size.height-8)&&a.push(`layout: group ${e.id} exceeds parent ${p.id}`);let m=new Set,h=p;for(;h&&!m.has(h.id);)m.add(h.id),h=r.find(e=>e.id===h.parentId);for(let t of r)if(t.id!==e.id&&!m.has(t.id)){let n=t,i=new Set;for(;n?.parentId&&!i.has(n.id)&&(i.add(n.id),n.parentId!==e.id);)n=r.find(e=>e.id===n.parentId);if(n?.parentId===e.id)continue;pt(u,{...t.position,...t.size})&&a.push(`layout: groups ${e.id} and ${t.id} cross without nesting`)}if(e.kind!==`alt`&&!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let g=bt(e,i);g||a.push(`layout: group ${e.id} has no room for heading; adjust its frame`);let _=r.filter(t=>t.parentId===e.id);if(e.kind===`alt`&&e.operands===void 0&&!e.parentId&&!_.length){let r=xt(e,t,n,i,g);return{errors:a,warnings:r.warnings,guards:r.guards,separators:[],heading:g}}if(!e.operands)return{errors:a,warnings:o,guards:s,bodies:c,separators:l};let v=Math.max(u.y+36,g?g.y+g.height+6:0),y=e.operands.map((n,i)=>{let a=_.filter(e=>e.parentOperandId===z(n,i)).map(e=>({...e.position,...e.size,id:e.id})),o=gt(e,n,i,r).map(e=>t.get(e)).filter(Boolean),s=[...a,...o.flatMap(e=>[e.labelBox,...mt(e)])],c=e.kind===`par`?n.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${n.guard}]`,l=Math.min(f.labelWidth,Math.max(1,u.width-40));return{operand:n,selected:o,childFrames:a,boxes:s,textHeight:A(c,l,14,20).height+16+(n.body?A(n.body,l,16,24).height+12:0),top:Math.min(...s.map(e=>e.y)),bottom:Math.max(...s.map(e=>e.y+e.height))}});for(let e=1;ee+t.textHeight,0)+(r?.textHeight??0);n&&(l[e-1]=i+(a-i)*o/s);for(let n=e;n<=t;n++)o+=y[n].textHeight,n+1gt(e,t,n,r)));for(let[n,r]of t)r.points.some(e=>e.x>=u.x&&e.x<=u.x+u.width&&e.y>u.y&&e.y[e.labelBox,...mt(e)]);return x.push(...i),y.forEach(({operand:t,selected:n,childFrames:r,top:i},o)=>{let p=o?l[o-1]:v,m=l[o]??d;for(let i of[...r,...n.flatMap(e=>[e.labelBox,...mt(e)])])(i.xu.x+u.width-4||i.ym-2)&&a.push(`layout: group ${e.id} cannot contain operand ${z(t,o)}${i.id?` child ${i.id}`:``}; enlarge or reposition its frame`);let h=e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,g=[...x,...r,...s,...c],_=(n,r,l)=>{let d=r===`body`?16:14,p=r===`body`?24:20,h=A(n,Math.min(f.labelWidth,Math.max(1,u.width-40)),d,p),_={width:h.width+8,height:h.height+4},v=[u.x+16,...g.map(e=>e.x+e.width+8),u.x+u.width-_.width-16],y=[l,...g.map(e=>e.y+e.height+8),i-_.height-8].filter(Number.isFinite).sort((e,t)=>e-t).flatMap(e=>v.map(t=>({x:t,y:e,..._}))).find(e=>e.x>=u.x+8&&e.x+e.width<=u.x+u.width-8&&e.y>=l&&e.y+e.height<=m-6&&!g.some(t=>pt(e,t,2)));return y?(y.lines=h.lines,y.fontSize=d,y.lineHeight=p,y.operandId=z(t,o),g.push(y),(r===`guard`?s:c).push(y)):a.push(`layout: group ${e.id} has no room for ${r} ${z(t,o)}; adjust frame/message spacing`),y},y=_(h,`guard`,p+6);t.body&&_(t.body,`body`,y?y.y+y.height+8:p+38)}),{errors:a,warnings:o,guards:s,bodies:c,separators:l,heading:g}}function Ct(e){if(e.meta.diagramType!==`sequence`)return new Map;let t=new Map(e.edges.map(e=>[e.id,e.order])),n=[...new Set(e.edges.map(e=>e.replyTo).filter(Boolean))].sort((e,n)=>(t.get(e)??1/0)-(t.get(n)??1/0)||(en))),r=new Map(n.map((e,t)=>[e,t]));return new Map(e.edges.filter(e=>r.has(e.replyTo??e.id)).map(e=>{let t=e.replyTo??e.id,n=r.get(t);return[e.id,{callId:t,index:n,label:`${e.replyTo?`↩ `:``}C${n+1}`}]}))}function wt(e,t,n=Ct(e),r=ht(e)){let i=n.get(t.id),a=(e.groups??[]).some(e=>e.kind===`par`&&(r.get(t.id)??``).split(`/`).some(t=>t.startsWith(encodeURIComponent(e.id)+`:`)));return i?`${i.label} · ${t.label??``}`:a?t.label??``:`${String(t.order).padStart(2,`0`)} · ${t.label??``}`}function Tt(e,t){let n=e=>t.findIndex(t=>t.id===e),r=[...e.edges].sort((e,t)=>Math.abs(n(e.source)-n(e.target))-Math.abs(n(t.source)-n(t.target))||e.order-t.order),i=new Map;for(let a of r){let r=Math.min(n(a.source),n(a.target)),o=Math.max(n(a.source),n(a.target)),s=Ae(wt(e,a)).width+64;if(r===o){let e=i.get(a.source)??0;if(i.set(a.source,e+1),o++,s+=48+e*24,o===t.length)continue}let c=e=>e.position.x+e.size.width/2,l=Math.max(0,s-(c(t[o])-c(t[r])));for(let e=o;e(e.route?.messageY??140+e.order*54)+(t===`receive`&&e.source===e.target?30:0);function Dt(e,{inputOnly:t=!1}={}){let n=[],r=new Map(e.edges.map(e=>[e.id,e]));if(e.meta.diagramType!==`sequence`)return(e.executions!==void 0||e.edges.some(e=>e.replyTo!==void 0))&&n.push(`executions and replyTo are only supported for sequence`),n;if(!t){let t=[...e.edges].sort((e,t)=>e.order-t.order);for(let e=1;e=t.order&&n.push(`${o} must precede its return`),(e.source!==t.target||e.target!==t.source)&&n.push(`${o} endpoints must be reversed`),i.get(e.id)!==i.get(t.id)&&n.push(`${o} must stay in the same operand scope`)),a.has(t.replyTo)&&n.push(`${o} has a duplicate return`),a.add(t.replyTo)}if(e.executions===void 0)return n;if(!Array.isArray(e.executions))return[...n,`executions must be an array`];let o=new Map,s=new Map,c=new Map;for(let a of e.executions){if(!a||typeof a!=`object`||Array.isArray(a)){n.push(`execution must be an object`);continue}let l=`execution ${String(a.id)}`;(typeof a.id!=`string`||!a.id.trim())&&n.push(`${l} needs a non-empty id`),o.has(a.id)&&n.push(`${l} duplicate id`),o.set(a.id,a),e.nodes.some(e=>e.id===a.participantId)||n.push(`${l} unknown participant ${String(a.participantId)}`);let u=[];for(let e of[`start`,`end`]){let i=a[e],o=r.get(i?.edgeId);if(!o||![`send`,`receive`].includes(i?.at)){n.push(`${l}.${e} invalid endpoint ${String(i?.edgeId)}`);continue}o[i.at===`send`?`source`:`target`]!==a.participantId&&n.push(`${l}.${e} endpoint ${o.id} does not belong to participant ${a.participantId}`),u.push(t?o.order*2+Number(i.at===`receive`&&o.source===o.target):Et(o,i.at));let s=`${o.id}:${i.at}`;c.has(s)&&n.push(`${l}.${e} ambiguous endpoint ${s} with execution ${c.get(s)}`),c.set(s,a.id)}u.length===2&&(u[0]>=u[1]&&n.push(`${l} start must precede end`),i.get(a.start.edgeId)!==i.get(a.end.edgeId)&&n.push(`${l} endpoints must stay in the same operand scope`),s.set(a.id,u))}for(let e of o.values()){if(e.parentId!==void 0){let t=o.get(e.parentId);if(!t)n.push(`execution ${e.id} unknown parent ${String(e.parentId)}`);else{t.participantId!==e.participantId&&n.push(`execution ${e.id} parent ${t.id} belongs to another participant`);let r=s.get(t.id),a=s.get(e.id);r&&a&&(a[0]r[1])&&n.push(`execution ${e.id} exceeds parent ${t.id}`);let o=i.get(t.start?.edgeId)??``,c=i.get(e.start?.edgeId)??``;o&&c!==o&&!c.startsWith(o+`/`)&&n.push(`execution ${e.id} is outside parent ${t.id} operand scope`)}}let t=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(t.has(r.id)){n.push(`execution ${e.id} parent cycle at ${r.id}`);break}t.add(r.id),r=o.get(r.parentId)}}let l=[...o.values()],u=(e,t)=>{let n=new Set,r=o.get(t.parentId);for(;r&&!n.has(r.id);){if(r.id===e.id)return!0;n.add(r.id),r=o.get(r.parentId)}return!1};for(let e=0;e[e.id,e])),r=ht(e);return t.map(i=>{let a=0,o=t.find(e=>e.id===i.parentId),s=new Set([i.id]);for(;o&&!s.has(o.id);)s.add(o.id),a++,o=t.find(e=>e.id===o.parentId);let c=e.nodes.find(e=>e.id===i.participantId),l=Et(n.get(i.start.edgeId),i.start.at);return{...i,depth:a,scope:r.get(i.start.edgeId)??``,x:c.position.x+c.size.width/2-8+a*8,y:l,width:16,height:Et(n.get(i.end.edgeId),i.end.at)-l}})}function kt(e,t,n,r,i,a=``){let o=e.filter(e=>e.participantId===t);return o.find(e=>[e.start,e.end].some(e=>e.edgeId===n.id&&e.at===r))||o.filter(e=>i>=e.y&&i<=e.y+e.height&&(!e.scope||a===e.scope||a.startsWith(e.scope+`/`))).sort((e,t)=>t.depth-e.depth)[0]}let B=e=>({x:e.position.x+e.size.width/2,y:e.position.y+e.size.height/2}),At=(e,t,n)=>X(t)?.edgeLabel?.(e,n)??e.label??``;function jt(e,t,n){let r=Math.hypot(n.x-t.x,n.y-t.y);if(!r)return{path:``};let i=(n.x-t.x)/r,a=(n.y-t.y)/r,o=(e,n=0)=>({x:t.x+i*e-a*n,y:t.y+a*e+i*n}),s=e=>[o(e,-6),o(e,6)],c=String(e).trim(),l=/[*n]/i.test(c),u=c.startsWith(`0`)||c===`*`,d=l?[[o(0,-6),o(12)],[o(0,6),o(12)],[t,o(12)]]:[s(8)];u||d.push(s(l?21:14));let f=d.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),p=o(23),m=u?{cx:p.x,cy:p.y,r:4}:void 0,h=d.flat();m&&h.push({x:p.x-4,y:p.y-4},{x:p.x+4,y:p.y+4});let g=Math.min(...h.map(e=>e.x)),_=Math.min(...h.map(e=>e.y)),v={x:g,y:_,width:Math.max(...h.map(e=>e.x))-g,height:Math.max(...h.map(e=>e.y))-_};return{path:f,...m?{circle:m}:{},bounds:v}}function Mt(e,t=H(e)){e=T(e);let n=[...J(e),...e.groups??[],...e.nodes,...Ot(e).map(e=>({position:{x:e.x,y:e.y},size:{width:e.width,height:e.height}}))],r=[...t.values()].flatMap(e=>[...e.points,{x:e.labelBox.x,y:e.labelBox.y},{x:e.labelBox.x+e.labelBox.width,y:e.labelBox.y+e.labelBox.height}]);for(let e of t.values())for(let t of e.endpointLabels??[])r.push({x:t.labelBox.x,y:t.labelBox.y},{x:t.labelBox.x+t.labelBox.width,y:t.labelBox.y+t.labelBox.height});if(X(e.meta?.diagramType).cardinalities)for(let n of e.edges){let e=t.get(n.id);for(let t of[jt(n.sourceCardinality,e.points[0],e.points[1]),jt(n.targetCardinality,e.points.at(-1),e.points.at(-2))])t.bounds&&r.push({x:t.bounds.x,y:t.bounds.y},{x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height})}let i=Math.min(...n.map(e=>e.position.x),...r.map(e=>e.x)),a=Math.min(...n.map(e=>e.position.y),...r.map(e=>e.y)),o=Math.max(...n.map(e=>e.position.x+e.size.width),...r.map(e=>e.x)),s=Math.max(...n.map(e=>e.position.y+e.size.height),...r.map(e=>e.y));return{x:i,y:a,width:o-i,height:s-a}}function V(e,t,n=0,r=`architecture`){let i=X(r)?.anchor;if(i)return i(e,t,n);let a=B(e);return t===`left`?{x:e.position.x,y:a.y+n}:t===`right`?{x:e.position.x+e.size.width,y:a.y+n}:t===`top`?{x:a.x+n,y:e.position.y}:{x:a.x+n,y:e.position.y+e.size.height}}function Nt(e,t,n=d.endpoint){return t===`left`?{x:e.x-n,y:e.y}:t===`right`?{x:e.x+n,y:e.y}:t===`top`?{x:e.x,y:e.y-n}:{x:e.x,y:e.y+n}}function Pt(e){let t=[];for(let n of e){let e=t.at(-1);(!e||e.x!==n.x||e.y!==n.y)&&t.push(n)}for(let e=1;e=0,o=n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0;a||o?t.splice(e,1):e+=1}return t}function Ft(e,t){let n=e.at(-1);n.x!==t.x&&n.y!==t.y&&e.push({x:t.x,y:n.y}),e.push(t)}function It(e){let t={length:-1,point:e[0]};for(let n=1;nt.length&&(t={length:a,point:{x:(r.x+i.x)/2,y:(r.y+i.y)/2}})}return t.point}function Lt(e,t,n,r){let i={clearance:-1,length:-1,point:It(e)};for(let a=1;ai.clearance||u===i.clearance&&d>i.length)&&(i={clearance:u,length:d,point:c})}return i.point}function Rt(e,t){let n=B(e),r=B(t),i=r.x-n.x,a=r.y-n.y;return Math.abs(a)>Math.abs(i)?{orientation:`vertical`,sourceSide:a>=0?`bottom`:`top`,targetSide:a>=0?`top`:`bottom`}:{orientation:`horizontal`,sourceSide:i>=0?`right`:`left`,targetSide:i>=0?`left`:`right`}}function zt(e,t,n,r){let{x:i,y:a,width:o,height:s}=r===`usecase`&&e.kind===`actor`?Yt(e,r):{...e.position,...e.size},c=Math.max(i-t.x,0,t.x-i-o),l=Math.max(a-t.y,0,t.y-a-s),u=c===0&&l===0?n:c>l?t.x0&&i.every((r,a)=>r[f]===e[f]&&(r[u]-(a?i[a-1][u]:e[u]))*l[n]>=0&&(t[u]-r[u])*l[n]>=0))return[e,t];let p=[e,Nt(e,n,a)];[`left`,`right`].includes(n)&&i.length&&p[1].y!==i[0].y&&p.push({x:p[1].x,y:i[0].y});for(let e of i)Ft(p,e);return Ft(p,Nt(t,r,a)),p.push(t),Pt(p)}function Vt(e,t,n,r,i,a=d.endpoint,o=`architecture`){let s=V(e,n.sourceSide,r,o),c=V(t,n.targetSide,i,o),l=Nt(s,n.sourceSide,a),u=Nt(c,n.targetSide,a),f=r||i;if(n.orientation===`horizontal`){let e=(l.x+u.x)/2+f;return Pt([s,l,{x:e,y:l.y},{x:e,y:u.y},u,c])}let p=(l.y+u.y)/2+f;return Pt([s,l,{x:l.x,y:p},{x:u.x,y:p},u,c])}function Ht(e,t=0,n=0){if(!e.length)return``;let r=e.map(e=>({x:e.x+t,y:e.y+n}));return r.slice(1).reduce((e,t,n)=>{let i=r[n];return i.y===t.y?`${e} H ${t.x}`:i.x===t.x?`${e} V ${t.y}`:`${e} L ${t.x} ${t.y}`},`M ${r[0].x} ${r[0].y}`)}function Ut(e,t,n){if(e.sourceSide!==e.targetSide)return null;let[r,...i]=e.points.map(e=>({x:e.x+t,y:e.y+n})),a=i.at(-1),[o,s]={right:[1,0],left:[-1,0],top:[0,-1],bottom:[0,1]}[e.sourceSide]??[1,0],[c,l]=[-s,o],u=Math.max(...i.map(e=>(e.x-r.x)*o+(e.y-r.y)*s))*4/3,d=(a.x-r.x)*c+(a.y-r.y)*l,f=Math.abs(d)*.35,p=Math.sign(d);if(!(u>0)||Math.abs(d)<1)return null;let m={x:r.x+o*u-c*p*f,y:r.y+s*u-l*p*f},h={x:a.x+o*u+c*p*f,y:a.y+s*u+l*p*f};return`M ${r.x} ${r.y} C ${m.x} ${m.y} ${h.x} ${h.y} ${a.x} ${a.y}`}let Wt=(e,t=0,n=0)=>e.curved&&Ut(e,t,n)||Ht(e.points,t,n);function Gt(e,t,n,r,i){let{graph:a,executions:o,scopes:s,pairs:c}=i,l=Et(e,`send`),u=Et(e,`receive`),p=kt(o,t.id,e,`send`,l,s.get(e.id)),m=kt(o,n.id,e,`receive`,u,s.get(e.id)),h=t.id===n.id||B(t).x<=B(n).x,g=p?p.x+(h?p.width:0):B(t).x,_=m?m.x+(t.id===n.id||!h?m.width:0):B(n).x,v=wt(a,e,c,s),y=Math.abs(_-g),b=Ae(v,t.id===n.id?f.labelWidth:Math.min(f.labelWidth,Math.max(1,y-32-12))),x=t.id===n.id?null:Ae(v,Math.max(1,y-64)),S=x&&(e.route?.labelAt??{x:(g+_)/2,y:l-6-x.height/2}),C=x&&x.lines.lengthpt({x:S.x-x.width/2,y:S.y-x.height/2,width:x.width,height:x.height},e,2))?x:b,w={width:C.width,height:C.height};if(t.id===n.id){let t=48+r*d.parallelGap,n={x:g,y:l},i={x:_,y:u},a=e.route?.via?.length?Bt(n,i,`right`,`right`,e.route.via):[n,{x:g+t,y:l},{x:g+t,y:l+30},i];return{points:a,label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:Math.max(...a.map(e=>e.x))+8+w.width/2,y:l+15},sourceSide:`right`,targetSide:`right`}}return{points:e.route?.via?.length?Bt({x:g,y:l},{x:_,y:l},g<=_?`right`:`left`,g<=_?`left`:`right`,e.route.via):[{x:g,y:l},{x:_,y:l}],label:v,labelLines:C.lines,labelSize:w,labelPoint:e.route?.labelAt??{x:(g+_)/2,y:l-6-w.height/2},sourceSide:g<=_?`right`:`left`,targetSide:g<=_?`left`:`right`}}function H(e){e=T(e);let t=Y(e),r=X(t).endpointStub??d.endpoint,i=new Map(e.nodes.map(e=>[e.id,e])),a=e.edges.map(e=>{let t=i.get(e.source),n=i.get(e.target);return{edge:e,source:t,target:n,self:t.id===n.id,...Rt(t,n)}}),o=t===`sequence`?{graph:e,executions:Ot(e),scopes:ht(e),pairs:Ct(e)}:null,s=new Map;for(let e of a.filter(e=>!X(t).sequence&&!e.self&&!e.edge.route?.via?.length))for(let[t,n,r,i]of[[`source`,e.source,e.sourceSide,e.target],[`target`,e.target,e.targetSide,e.source]]){let a=`${n.id}:${r}`,o=e.orientation===`horizontal`?B(i).y:B(i).x;s.has(a)||s.set(a,[]),s.get(a).push({id:e.edge.id,role:t,coordinate:o})}let c=new Map;for(let e of s.values())e.sort((e,t)=>e.coordinate-t.coordinate||e.id.localeCompare(t.id)||e.role.localeCompare(t.role)),e.forEach((t,n)=>c.set(`${t.id}:${t.role}`,(n-(e.length-1)/2)*d.parallelGap));let l=new Map,u=new Map;for(let e of a.filter(e=>e.self).sort((e,t)=>(e.edge.order??0)-(t.edge.order??0)||(e.edge.idt.x-n&&e.yt.y-n}function U(e,t){return X(t).sequence?{...e.position,width:e.size.width,height:Math.min(e.size.height,Ke(e))}:{...e.position,...e.size}}function qt(e,t){let n=Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),r=Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0);return Math.hypot(n,r)}function Jt(e,t,n,r){let i=Yt(t,r);if((n===`left`||n===`right`)&&(e.yi.y+i.height)||(n===`top`||n===`bottom`)&&(e.xi.x+i.width))return!1;let a=B(t),o=V(t,n,n===`left`||n===`right`?e.y-a.y:e.x-a.x,r);return Math.hypot(e.x-o.x,e.y-o.y)<1e-7}function W(e,t,n){return e.y===t.y?e.y>n.y&&e.yn.x&&e.x0&&W(e,t,{x:a-s/2,y:r+106,width:s,height:24})}let a=B(n);if(e.y===t.y){if(e.y<=i.y||e.y>=i.y+i.height)return!1;let o=e.y-a.y,s=V(n,`left`,o,r).x,c=V(n,`right`,o,r).x;return Math.max(Math.min(e.x,t.x),s)=i.x+i.width)return!1;let o=e.x-a.x,s=V(n,`top`,o,r).y,c=V(n,`bottom`,o,r).y;return Math.max(Math.min(e.y,t.y),s)[{id:e.source,point:t[0]},{id:e.target,point:t.at(-1)}],o=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y)<.001;for(let s=1;s1||y<0||y>1)continue;let b={x:+(l.x+v*p).toFixed(3),y:+(l.y+v*m).toFixed(3)};a(e,t).some(e=>a(n,r).some(t=>e.id===t.id&&o(e.point,b)&&o(t.point,b)))||i.set(`${b.x},${b.y}`,b)}return[...i.values()].sort((e,t)=>e.x-t.x||e.y-t.y)}function tn(e){e=T(e);let t=Y(e),n=[],r=H(e),i=[],a=[],o=[],s=new Map([...e.nodes,...e.groups??[],...Ot(e)].map(e=>[e.id,e])),c=(e,n,a)=>{i.push(a);let c=n.flatMap(e=>{let t=s.get(e);if(t)return[t.position?{...t.position,...t.size}:{x:t.x,y:t.y,width:t.width,height:t.height}];let n=r.get(e);return n?n.points.map(e=>({...e,width:0,height:0})):[]});o.push({ruleId:e,severity:`error`,diagramType:t,elementIds:n,bounds:c,measured:a,required:`clear full-size geometry`,remediation:a.includes(`;`)?a.split(`;`).slice(1).join(`;`).trim():`Adjust the identified elements while preserving the complete model.`})};if(t===`sequence`){for(let t of e.nodes)t.size.heightpt(i.labelBox,e))&&c(`sequence.message-clearance`,[n.id,t.id],`layout: sequence edge ${n.id} label needs 6px clearance from message ${t.id}; shorten the label or adjust participant spacing/route hints`);i.points.some(t=>t.y>Math.min(...[n.source,n.target].map(t=>{let n=e.nodes.find(e=>e.id===t);return n.position.y+n.size.height})))&&c(`sequence.lifeline`,[n.id,n.source,n.target],`layout: sequence edge ${n.id} exceeds its participant lifeline`)}}let l=X(t).cardLayout&&!zr(e);if(X(t).cardLayout)for(let n of e.nodes){if(n.size.height<(l?100:j.minHeight))continue;let{minHeight:r}=t===`architecture`&&Vn(n)?Un(n):Oe(n,e.meta.locale,l);n.size.heightr.get(e.id).label);for(let e=0;ed.endpoint&&c(`route.shared-segment`,[o.id,s.id],`layout: edges ${o.id} and ${s.id} share a route segment longer than ${d.endpoint}px`);let p=en(o,l,s,u);p.length&&n.push({ruleId:`route.point-crossing`,severity:`info`,diagramType:t,elementIds:[o.id,s.id].sort(),measured:p.length,required:null,bounds:p.map(e=>({...e,width:0,height:0})),repeated:Math.max(0,p.length-1),remediation:`Keep each relation traceable; prefer fewer repeated crossings without overlapping channels.`})}for(let n of e.edges){let i=r.get(n.id),a=e.nodes.find(e=>e.id===n.source),o=e.nodes.find(e=>e.id===n.target);if(!X(t).sequence&&(!Jt(i.points[0],a,i.sourceSide,t)||!Jt(i.points.at(-1),o,i.targetSide,t))&&c(`route.anchor`,[n.id,n.source,n.target],`layout: edge ${n.id} exceeds an endpoint side; enlarge the node or add route hints`),X(t).cardinalities){let r=X(t).endpointStub;for(let[t,a,o,s,l,u]of[[`source`,i.points[0],i.points[1],i.sourceSide,n.sourceCardinality,n.route?.via?.[0]],[`target`,i.points.at(-1),i.points.at(-2),i.targetSide,n.targetCardinality,n.route?.via?.at(-1)]]){let i=Nt(a,s,1),d=e=>(e.x-a.x)*(i.x-a.x)+(e.y-a.y)*(i.y-a.y);(d(o){let n=i.points[t],r=i.points[t+2];return n.x===e.x&&e.x===r.x&&(e.y-n.y)*(r.y-e.y)<0||n.y===e.y&&e.y===r.y&&(e.x-n.x)*(r.x-e.x)<0})&&c(`route.er-reversal`,[n.id],`layout: ER edge ${n.id} reverses within its route; reserve ${r}px endpoint segments or move the route hints`)}if(X(t).sequence&&n.source!==n.target){let e=Math.abs(B(a).x-B(o).x),t=Math.max(160,i.labelBox.width+32);eKt(i.labelBox,e))&&c(`label.group-heading`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} heading`),Zt(t).some(([e,t])=>W(e,t,i.labelBox))&&c(`label.group-boundary`,[n.id,t.id],`layout: edge ${n.id} label overlaps group ${t.id} boundary`);for(let r of e.nodes)Kt(i.labelBox,Yt(r,t))&&c(`label.node`,[n.id,r.id],`layout: edge ${n.id} label overlaps node ${r.id}`)}}for(let t of e.edges){let n=r.get(t.id);for(let r of e.groups??[]){let e=Zt(r);for(let i=1;iW(a,o,e))&&c(`route.group-heading`,[t.id,r.id],`layout: edge ${t.id} crosses group ${r.id} heading`),e.some(([e,t])=>$t(a,o,e,t)>d.endpoint)&&c(`route.group-boundary`,[t.id,r.id],`layout: edge ${t.id} overlaps group ${r.id} boundary`)}}}return{errors:[...new Set(i)],warnings:[...new Set(a)],routes:r,crossings:n,diagnostics:o}}let nn=e=>({node:c(e)?6:12,preferred:c(e)?8:24,boundary:6}),rn=(e,t,n)=>Math.max(t,Math.min(n,e)),an=(e,t,n)=>{let r=n.x-t.x,i=n.y-t.y,a=rn(((e.x-t.x)*r+(e.y-t.y)*i)/(r*r+i*i||1),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)};function on(e,t,n,r){let i=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x);return i(e,t,n)*i(e,t,r)<=0&&i(n,r,e)*i(n,r,t)<=0&&Math.max(Math.min(e.x,t.x),Math.min(n.x,r.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,r.x))&&Math.max(Math.min(e.y,t.y),Math.min(n.y,r.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,r.y))?0:Math.min(an(e,n,r),an(t,n,r),an(n,e,t),an(r,e,t))}function sn(e,t,n){return Math.hypot(Math.max(n.x-Math.max(e.x,t.x),Math.min(e.x,t.x)-n.x-n.width,0),Math.max(n.y-Math.max(e.y,t.y),Math.min(e.y,t.y)-n.y-n.height,0))}function cn(e,t,n){let r=e=>{let t=Math.abs(e.x-n.cx),r=Math.abs(e.y-n.cy);if((t/n.rx)**2+(r/n.ry)**2<=1+1e-12)return 0;if(t===0)return Math.max(0,r-n.ry);if(r===0)return Math.max(0,t-n.rx);let i=e=>Math.hypot(t-n.rx*Math.cos(e),r-n.ry*Math.sin(e)),a=0,o=Math.PI/2;for(let e=0;e<32;e++){let e=a+(o-a)/3,t=o-(o-a)/3;i(e)=c-e)return 0}if(l<=c&&u>=c)return Math.max(0,Math.abs(a)-o);let d=r(e);return d===0?0:Math.min(d,r(t))}function ln(e,t,n){let r=n.position.x+12,i=n.position.x+n.size.width-12,a=n.position.y+2,o=n.position.y+n.size.height-2,s=(i-r)/2,c=(r+i)/2,l=e=>{if(e.xi)return!1;let t=5*(1-Math.sqrt(Math.min(e.x-r,i-e.x)/s))**2;return e.y>=a+t&&e.y<=o-t};if(l(e)||l(t)||l({x:rn(c,Math.min(e.x,t.x),Math.max(e.x,t.x)),y:rn((a+o)/2,Math.min(e.y,t.y),Math.max(e.y,t.y))}))return 0;let u=(n,r,i,a)=>{let o=o=>an({x:n+i*s*o*o,y:r+a*5*(1-o)**2},e,t),c=0,l=1;for(let e=0;e<32;e++){let e=c+(l-c)/3,t=l-(l-c)/3;o(e){let t=!1;for(let r=0,i=n.length-1;re.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(t=!t)}return t};return r(e)||r(t)?0:Math.min(...n.map((r,i)=>on(e,t,r,n[(i+1)%n.length])))}let dn=new WeakMap;function fn(e,t){let n=JSON.stringify([t,e.position,e.size,e.kind,e.label,e.subtitle,e.overviewText,e.badges,e.overviewTone]),r=dn.get(e);if(r?.signature===n)return r.probe;let i=X(t),{x:a,y:o}=e.position,[s,c]=(i.outline?.(e,a,o)??[])[0]??[],l;if(t===`usecase`&&e.kind===`actor`){let t=o+Ye(e),n=a+e.size.width/2,r=[[{x:n,y:t+24},{x:n,y:t+53}],[{x:n-20,y:t+35},{x:n+20,y:t+35}],[{x:n,y:t+53},{x:n-17,y:t+76}],[{x:n,y:t+53},{x:n+17,y:t+76}]],i=[[e.label,20,t+78,26],...e.subtitle?[[e.subtitle,16,t+106,24]]:[]].map(([t,r,i,a])=>{let o=Math.min(e.size.width,A(t,1/0,r).width*1.15);return{x:n-o/2,y:i,width:o,height:a}});l=(e,a)=>Math.min(Math.max(0,an({x:n,y:t+13},e,a)-11),...r.map(([t,n])=>on(e,a,t,n)),...i.map(t=>sn(e,a,t)))}else if(s===`path`&&[`architecture`,`deployment`].includes(t)&&e.kind===`database`)l=(t,n)=>ln(t,n,e);else if(s===`polygon`){let e=c.points.split(/\\s+/).map(e=>{let[t,n]=e.split(`,`).map(Number);return{x:t,y:n}});l=(t,n)=>un(t,n,e)}else if(s===`circle`)l=(e,t)=>Math.max(0,an({x:c.cx,y:c.cy},e,t)-c.r);else if(s===`ellipse`)l=(e,t)=>cn(e,t,c);else{let n=s===`rect`?c:Yt(e,t),r=s===`rect`?Math.min(c.rx??0,n.width/2,n.height/2):0,i={x:n.x+r,y:n.y+r,width:n.width-2*r,height:n.height-2*r};l=(e,t)=>Math.max(0,sn(e,t,i)-r)}if(t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle){let t=l,n=i.textArea(e),r={...n,x:a+n.x,y:o+n.y};l=(e,n)=>Math.min(t(e,n),sn(e,n,r))}let u=l,d=new Map;return l=(e,t)=>{if(e.x!==t.x||e.y!==t.y)return u(e,t);let n=e.x+`,`+e.y;if(d.has(n))return d.get(n);let r=u(e,t);return d.size<1024&&d.set(n,r),r},dn.set(e,{signature:n,probe:l}),l}function pn(e,t,n){let r=e.y===t.y,i=r?`x`:`y`,a=r?`y`:`x`;return Zt(n).filter(([e,t])=>r===(e.y===t.y)).map(([n,r])=>({distance:Math.abs(e[a]-n[a]),length:Math.max(0,Math.min(Math.max(e[i],t[i]),Math.max(n[i],r[i]))-Math.max(Math.min(e[i],t[i]),Math.min(n[i],r[i])))})).filter(e=>e.length>.001).sort((e,t)=>e.distance-t.distance)[0]??{distance:1/0,length:0}}function mn(e,t,n,r=[],i=[]){let a=Y(e),o=nn(e),s=e.nodes.map(e=>({node:e,probe:fn(e,a),bounds:Yt(e,a),terminals:[...e.id===t?r:[],...e.id===n?i:[]]}));return(t,n)=>s.some(({node:e,probe:r,bounds:i,terminals:s})=>{if(sn(t,n,i)>=o.node&&(a!==`usecase`||e.kind!==`actor`)&&!(a===`state`&&e.subtitle))return!1;let c=e=>s.some(t=>Math.abs(t.x-e.x)<.001&&Math.abs(t.y-e.y)<.001);return c(t)&&r(n,n)+.001>=o.node||c(n)&&r(t,t)+.001>=o.node?!1:r(t,n)+.001pn(t,n,e).distance+.001JSON.stringify(t)!==JSON.stringify(e.nodes.find(e=>e.id===t.id))),s=new Set(o.map(e=>e.id)),c=o.map(e=>{let t=U(e,i);return{x:t.x-a,y:t.y-a,width:t.width+2*a,height:t.height+2*a}}),l=(t.groups??[]).filter(t=>JSON.stringify(t)!==JSON.stringify(e.groups?.find(e=>e.id===t.id))),u=H(e),d=h(X(i)).labelGap,f=[...o.map(e=>U(e,i)),...l.flatMap(Qt)],p=(e,t)=>Math.hypot(Math.max(e.x-t.x-t.width,t.x-e.x-e.width,0),Math.max(e.y-t.y-t.height,t.y-e.y-e.height,0));for(let n of t.edges){let i=e.edges.find(e=>e.id===n.id),a=u.get(n.id);(s.has(n.source)||s.has(n.target)||JSON.stringify(n)!==JSON.stringify(i)||a&&[...a.label?[a.labelBox]:[],...(a.endpointLabels??[]).map(e=>e.labelBox)].some(e=>f.some(t=>p(e,t){let r=a.points[n];return c.some(t=>W(r,e,t))||l.some(n=>pn(r,e,n).distanceW(r,e,t)))}))&&r.add(n.id)}return r}let gn=[`top`,`right`,`bottom`,`left`],G={top:[0,-1],right:[1,0],bottom:[0,1],left:[-1,0]},K=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),_n=e=>({...e.position,...e.size}),vn=(e,t)=>({x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}),yn=(e,t)=>e.xe.slice(1).map((t,n)=>[e[n],t]),bn=e=>e.x+`,`+e.y,xn=(e,t)=>e.idt.id);var Sn=class{items=[];less(e,t){return e.priority>1;if(!this.less(t[n],t[e]))break;[t[n],t[e]]=[t[e],t[n]],n=e}}pop(){let e=this.items,t=e[0],n=e.pop();if(e.length){e[0]=n;let t=0;for(;;){let n=t,r=t*2+1;for(let t of[r,r+1])t=0||n.y===r.y&&r.y===i.y&&(r.x-n.x)*(i.x-r.x)>=0?t.splice(e,1):e++}return t}function wn(e,t,n=32){let r=Cn(e),i=t(r),a=0,o=!0;for(;o&&ae+1;s--){let c=r[e],l=r[s];for(let u of[[{x:l.x,y:c.y}],[{x:c.x,y:l.y}]]){if(a++>=n)break search;let c=Cn([...r.slice(0,e+1),...u,...r.slice(s)]),l=t(c);if(l{let r=U(n,Y(e));return t+r.width*r.height},0)/Math.max(1,e.nodes.length)),r=i.crossings*n,a=i.bends*n;return c(e)?{...t,labelGap:6,parallelGap:8,nodeGap:14,crossingCost:r,bendCost:a}:{...t,crossingCost:r,bendCost:a}}function En(e,t,n,r,i,a,o){let s=n===`top`||n===`bottom`,c=s?`x`:`y`,l=s?`width`:`height`,u=Yt(e,r),d=e.position[c]+e.size[l]/2,f=u[c]+u[l]/2,p=Math.max(0,u[l]/2-20),m=t.position[s?`x`:`y`]+t.size[s?`width`:`height`]/2-f,h=a.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>({edge:t,target:a.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))})).filter(t=>t.target.id!==e.id);h.sort((e,t)=>e.target.position[c]+e.target.size[l]/2-t.target.position[c]-t.target.size[l]/2||xn(e.edge,t.edge));let g=h.findIndex(e=>e.edge.id===o?.id),_=g<0?0:(g-(h.length-1)/2)*i.parallelGap,v=[`decision`,`choice`].includes(e.kind)?[0]:[_,Math.max(-p,Math.min(p,m)),0,-i.parallelGap,i.parallelGap,-p*.6,p*.6];return[...new Set(v.map(e=>Math.max(-p,Math.min(p,e))))].map(t=>Dn(e,n,t+f-d,r,i))}function Dn(e,t,n,r,i){let a=V(e,t,n,r),[o,s]=G[t],c=_n(e),l=r===`usecase`&&e.kind===`actor`?i.endpoint:Math.max(X(r).endpointStub??i.endpoint,t===`left`?a.x-c.x+1:t===`right`?c.x+c.width-a.x+1:t===`top`?a.y-c.y+1:c.y+c.height-a.y+1);return{point:a,side:t,stub:{x:a.x+o*l,y:a.y+s*l}}}function On(e,t,n,r=null,i=null){let a=Y(n),o=Tn(n),s=[];for(let c of r?[r]:gn)for(let r of gn){let l=En(e,t,c,a,o,n,i),u=En(t,e,r,a,o,n,i);if((c===`left`||c===`right`)==(r===`left`||r===`right`)){let n=c===`left`||c===`right`?`y`:`x`,i=n===`x`?`width`:`height`,s=(e,t,r,s)=>{let c=Yt(e,a),l=e.position[n]+e.size[i]/2;for(let u of s.slice(0,3)){let s=u.point[n];if(sc[n]+c[i]-20)continue;let d=Dn(e,t,s-l,a,o);r.some(e=>K(e.point,d.point)<.001)||r.push(d)}},d=[...l];s(e,c,l,u),s(t,r,u,d)}let d=Math.min(...l.flatMap(e=>u.map(t=>K(e.point,t.point)))),f=(c===`left`||c===`right`)==(r===`left`||r===`right`),p=f&&c!==r&&l.some(e=>u.some(t=>(e.point.x===t.point.x||e.point.y===t.point.y)&&(t.point.x-e.point.x)*G[c][0]+(t.point.y-e.point.y)*G[c][1]>0))?0:f?2:1;s.push({sourceSide:c,targetSide:r,starts:l,ends:u,nearest:d,minimumBends:p,sourceId:e.id,targetId:t.id})}return s.sort((e,t)=>e.nearest+e.minimumBends*o.bendCost-t.nearest-t.minimumBends*o.bendCost||e.nearest-t.nearest||gn.indexOf(e.sourceSide)-gn.indexOf(t.sourceSide)||gn.indexOf(e.targetSide)-gn.indexOf(t.targetSide))}function kn(e,t,n,r,i){let a=e.y===t.y;if(a===(n.y===r.y)){let o=a?`x`:`y`,s=a?`y`:`x`;return Math.abs(e[s]-n[s])+.001.001?1/0:0}let[o,s,c,l]=a?[e,t,n,r]:[n,r,e,t];return+(c.x>=Math.min(o.x,s.x)&&c.x<=Math.max(o.x,s.x)&&o.y>=Math.min(c.y,l.y)&&o.y<=Math.max(c.y,l.y))}function An(e,t){let n=e=>({source:bn(e[0]),target:bn(e.at(-1))});return en(n(e),e,n(t),t).length}function jn(e,t){let n=e.nodes.map(e=>({node:e,r:Yt(e,t),always:t===`usecase`&&e.kind===`actor`||t===`state`&&[`initial`,`final`].includes(e.kind)&&e.subtitle}));return(e,r)=>n.some(({node:n,r:i,always:a})=>!a&&(e.y===r.y?e.y<=i.y||e.y>=i.y+i.height:e.x===r.x&&(e.x<=i.x||e.x>=i.x+i.width))?!1:Xt(e,r,n,t))}function Mn(e,t){let n=t.parallelGap,r=e.flatMap((e,t)=>q(e).map(([e,r])=>({index:t,c:e,d:r,l:Math.min(e.x,r.x)-n,r:Math.max(e.x,r.x)+n,t:Math.min(e.y,r.y)-n,b:Math.max(e.y,r.y)+n})));return(i,a,o,s=!0)=>{let c=Math.min(i.x,a.x),l=Math.max(i.x,a.x),u=Math.min(i.y,a.y),d=Math.max(i.y,a.y),f=new Map;for(let{index:o,c:p,d:m,l:h,r:g,t:_,b:v}of r){if(lg||d<_||u>v)continue;let r=kn(i,a,p,m,n);if(r===1/0){let n=$t(i,a,p,m),r=e.some(e=>[e[0],e.at(-1)].some(e=>(e.x===i.x&&e.y===i.y||e.x===a.x&&e.y===a.y)&&(e.x===p.x&&e.y===p.y||e.x===m.x&&e.y===m.y)));if(n>0&&n<=t.endpoint+.001&&r)continue;return 1/0}if(s&&r){let t=i.y===a.y?{x:p.x,y:i.y}:{x:i.x,y:p.y},n=K(t,i)<.001||K(t,a)<.001;if(n&&[e[o][0],e[o].at(-1)].some(e=>K(e,t)<.001))continue;f.set(o+`:`+bn(t),n?.5:1)}}return o+[...f.values()].reduce((e,t)=>e+t,0)*t.crossingCost}}function Nn(e,t,n,r,i,a,o,s=1/0){let c=e.starts,l=e.ends,u=Y(t),d=M(o),f=t.nodes.map(e=>U(e,u)),p=r.flatMap(q),m=(t.groups??[]).flatMap(Zt),h=jn(t,u),g=Mn(r,i),_=mn(t,e.sourceId,e.targetId,c.map(e=>e.point),l.map(e=>e.point)),v=(e,t)=>_(e,t)||m.some(([n,r])=>$t(e,t,n,r)>i.endpoint),y=(t,a=1/0)=>{if(t.length<2)return 1/0;let s=t[0],c=t[1],l=t.at(-1),u=t.at(-2),m=(e,t,n)=>(t.x-e.x)*G[n][0]+(t.y-e.y)*G[n][1]>0;if(!m(s,c,e.sourceSide)||!m(l,u,e.targetSide)||t.length>2&&(K(s,c)e+K(t,n),0)+Math.max(0,t.length-2)*i.bendCost;if(_>=a)return 1/0;for(let[e,r]of q(t))if(h(e,r)||n.some(t=>W(e,r,t))||v(e,r)||(_=g(e,r,_,!1),_===1/0))return 1/0;return _+=r.reduce((e,n)=>e+An(t,n),0)*i.crossingCost,o&&!Pn(t,d,f,n,p,i).length?1/0:_},b=[...t.nodes.map(e=>U(e,u)),...n,...r.flat().map(e=>({...e,width:0,height:0}))],x=Math.max(i.preferredClearance,d.width/2+i.labelGap+4),S=Math.max(i.preferredClearance,d.height/2+i.labelGap+4),C=Math.min(...b.map(e=>e.x))-x,w=Math.max(...b.map(e=>e.x+e.width))+x,T=Math.min(...b.map(e=>e.y))-S,ee=Math.max(...b.map(e=>e.y+e.height))+S,E;for(let e of c)for(let t of l){let n=e.stub,r=t.stub,a=[[n,{x:r.x,y:n.y},r],[n,{x:n.x,y:r.y},r],[n,{x:(n.x+r.x)/2,y:n.y},{x:(n.x+r.x)/2,y:r.y},r],[n,{x:n.x,y:(n.y+r.y)/2},{x:r.x,y:(n.y+r.y)/2},r],...[C,w].map(e=>[n,{x:e,y:n.y},{x:e,y:r.y},r]),...[T,ee].map(e=>[n,{x:n.x,y:e},{x:r.x,y:e},r])];if((e.point.x===t.point.x||e.point.y===t.point.y)&&K(e.point,t.point)>=(X(u).endpointStub??i.endpoint)){let n={x:(e.point.x+t.point.x)/2,y:(e.point.y+t.point.y)/2};G[e.side][0]*(t.point.x-e.point.x)+G[e.side][1]*(t.point.y-e.point.y)>0&&G[t.side][0]*(e.point.x-t.point.x)+G[t.side][1]*(e.point.y-t.point.y)>0&&a.push([n])}for(let n of a){let r=Cn([e.point,...n,t.point]),i=y(r,Math.min(s,E?.cost??1/0));Number.isFinite(i)&&(!E||iU(e,u)),ne=new Set([...c,...l].map(e=>e.stub.x)),re=new Set([...c,...l].map(e=>e.stub.y));for(let e of[...te,...n,...r.flatMap(e=>q(e).map(([e,t])=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)})))])ne.add(e.x-i.preferredClearance),ne.add(e.x+e.width+i.preferredClearance),re.add(e.y-i.preferredClearance),re.add(e.y+e.height+i.preferredClearance);let D=[...ne].sort((e,t)=>e-t),ie=[...re].sort((e,t)=>e-t),ae=D.length,oe=e=>({x:D[e%ae],y:ie[Math.floor(e/ae)]}),se=e=>ie.indexOf(e.y)*ae+D.indexOf(e.x),ce=new Map,le=(e,t)=>{let r=bn(e),i=bn(t),a=rW(e,t,n))&&!v(e,t)&&(o=g(e,t,K(e,t))),ce.set(a,o),o},ue=e=>Math.min(...l.map(t=>K(e,t.stub))),O=new Sn,de=new Map,fe=new Map,pe=0;for(let e of l){let t=se(e.stub);fe.has(t)||fe.set(t,[]),fe.get(t).push(e)}for(let e of c){if(n.some(t=>W(e.point,e.stub,t))||!Number.isFinite(le(e.point,e.stub)))continue;let t=se(e.stub),r=+![`left`,`right`].includes(e.side),i=K(e.point,e.stub),a={id:t,direction:r,cost:i,priority:i+ue(e.stub),start:e,serial:pe++},o=t*2+r;(!de.has(o)||de.get(o).cost>a.cost)&&(de.set(o,a),O.push(a))}let me=0;for(;O.items.length&&a.remaining>0&&me++<4e3;){a.remaining--;let e=O.pop();if(de.get(e.id*2+e.direction)!==e)continue;if(e.priority>=Math.min(s,E?.cost??1/0))break;let t=oe(e.id);for(let t of fe.get(e.id)??[]){if(!Number.isFinite(le(t.stub,t.point)))continue;let r=[];for(let t=e;t;t=t.before)r.push(oe(t.id));r.reverse();let a=wn([e.start.point,...r,t.point],y);if(o&&!Pn(a,d,f,n,p,i).length)continue;let s=y(a);if(Number.isFinite(s))return E&&E.cost<=s?E:{points:a,via:a.length>2?a.slice(1,-1):[e.start.stub,t.stub],sourceSide:e.start.side,targetSide:t.side,cost:s}}let r=e.id%ae,c=Math.floor(e.id/ae);for(let[n,a]of[[r-1,c],[r+1,c],[r,c-1],[r,c+1]]){if(n<0||a<0||n>=ae||a>=ie.length)continue;let o=a*ae+n,s=oe(o),c=le(t,s);if(!Number.isFinite(c))continue;let l=+(r===n),u=e.cost+c+(l===e.direction?0:i.bendCost),d=o*2+l;if(de.has(d)&&de.get(d).cost<=u)continue;let f={id:o,direction:l,cost:u,priority:u+ue(s),before:e,start:e.start,serial:pe++};de.set(d,f),O.push(f)}}return E??null}function Pn(e,t,n,r,i,a){let o=[];for(let[s,[c,l]]of q(e).entries()){let u=c.y===l.y,d=u?`x`:`y`,f=u?`width`:`height`,p=t[f]/2,m=Math.min(c[d],l[d])+p+4,h=Math.max(c[d],l[d])-p-4;if(m>h)continue;let g=(c[d]+l[d])/2,_=[...new Set([g,m,h,...[...n,...r].flatMap(e=>[e[d]-p-a.labelGap-.01,e[d]+e[f]+p+a.labelGap+.01]),...i.flatMap(([e,t])=>[Math.min(e[d],t[d])-p-a.labelEdgeGap-.01,Math.max(e[d],t[d])+p+a.labelEdgeGap+.01])])].filter(e=>e>=m&&e<=h);for(let l of _){let u={...c,[d]:l};if(u.x<0||u.y<0)continue;let f={x:u.x-t.width/2,y:u.y-t.height/2,...t};[...n,...r].some(e=>yn(f,vn(e,a.labelGap)))||i.some(([e,t])=>W(e,t,vn(f,a.labelEdgeGap)))||[e[0],e.at(-1)].some(e=>yn(f,{x:e.x-12,y:e.y-12,width:24,height:24}))||o.push({point:u,r:f,score:Math.abs(l-g)+s*.001})}}return o.sort((e,t)=>e.score-t.score)}function Fn(e,t=null){let n=Y(e),r=Tn(e),i=H(e),a=t?[...i].filter(([e])=>!t.has(e)).flatMap(([,e])=>e.label?[e.labelBox]:[]):[],o=[...(e.groups??[]).flatMap(e=>{let t=_n(e);return[{x:t.x,y:t.y,width:t.width,height:1},{x:t.x,y:t.y+t.height,width:t.width,height:1},{x:t.x,y:t.y,width:1,height:t.height},{x:t.x+t.width,y:t.y,width:1,height:t.height}]}),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)],s=e.nodes.map(e=>U(e,n));for(let n of[...e.edges].filter(e=>!t||t.has(e.id)).sort(xn)){let e=i.get(n.id);if(!e.label)continue;let t=[...i].filter(([e])=>e!==n.id).flatMap(([,e])=>q(e.points)),c=Pn(e.points,M(e.label),s,[...o,...a],t,r)[0];if(!c)throw Object.assign(Error(`No clear label position for `+n.id),{elementIds:[n.id,n.source,n.target],routingReason:`label-space`});n.route={...n.route,labelAt:c.point},a.push(c.r)}return e}function In(e,t,n,r,i,a,o,s=0){let c=Y(t),l=M(At(o,c,t.meta.locale));for(let[o,u]of[`right`,`bottom`,`left`,`top`].entries()){if(ob(a,o)||t.nodes.some(t=>t.id!==e.id&&Xt(a,o,t,c))||n.some(e=>W(a,o,e))||r.flatMap(q).some(([e,t])=>kn(a,o,e,t,i.parallelGap)===1/0)))return{via:y.slice(1,-1),sideIndex:o}}return null}function Ln(e){let t=Tn(e),n=[...H(e).values()],r=n.reduce((e,t)=>e+q(t.points).reduce((e,[t,n])=>e+K(t,n),0),0),i=0;for(let e=0;ee+Math.max(0,n.points.length-2)*t.bendCost,0)+i*t.crossingCost}function Rn(e,{passes:t=3,accept:n=null,edgeIds:r=null,searchBudget:a=null}={}){let o=Y(e);if(X(o).sequence){let t=structuredClone(e),r=H(t),i=t.nodes.map(e=>U(e,o)),a=Math.min(1/0,...[...r.values()].filter(e=>e.label).map(e=>e.labelBox.y)),s=Math.max(0,Math.max(...i.map(e=>e.y+e.height))+h(X(o)).labelGap-a);if(s){for(let e of t.edges)e.route={...e.route,messageY:r.get(e.id).points[0].y+s},e.route.via&&(e.route.via=e.route.via.map(e=>({...e,y:e.y+s}))),e.route.labelAt&&(e.route.labelAt={...e.route.labelAt,y:e.route.labelAt.y+s});for(let e of t.groups??[])e.position.y+=s;for(let e of t.nodes)e.size.height+=s}return n&&n(t),{graph:t,report:{strategy:`sequence-span-constraints`,evaluations:1,headerClearanceShift:s,termination:`notation-specific`}}}let s=Tn(e),c=H(e),l=r?[...c].filter(([e])=>!r.has(e)).map(([,e])=>e):[],u=[...l.filter(e=>e.label).map(e=>vn(e.labelBox,s.labelEdgeGap)),...(e.groups??[]).flatMap(Qt),...J(e).flatMap(Kn)].map(e=>vn(e,8)),d=e.layout?.primaryPath??[],f=t=>{let n=e.nodes.find(e=>e.id===t.source),r=e.nodes.find(e=>e.id===t.target);return Math.abs(n.position.x+n.size.width/2-r.position.x-r.size.width/2)+Math.abs(n.position.y+n.size.height/2-r.position.y-r.size.height/2)},p=[...e.edges].filter(e=>!r||r.has(e.id)).sort((t,n)=>{let r=e=>d.some((t,n)=>t===e.source&&d[n+1]===e.target),i=t=>[`decision`,`choice`].includes(e.nodes.find(e=>e.id===t.source)?.kind);return Number(r(n))-Number(r(t))||Number(i(n))-Number(i(t))||f(t)-f(n)||xn(t,n)}),m,g,_=[],v=6e4*Math.min(4,Math.max(1,Math.ceil(p.length/16)));if(n)try{n(e,{strictEdgeIds:new Set(p.map(e=>e.id))}),m={graph:structuredClone(e),cost:Ln(e),pass:`preserved`}}catch{}for(let d=0;d{let n=e.get(t.id);return[...e].filter(([e])=>e!==t.id).reduce((e,[,t])=>e+An(n.points,t.points),0)*i.crossings+Math.max(0,n.points.length-2)*i.bends},r=[...p].sort((e,n)=>t(n)-t(e)||xn(e,n));for(let[e,t]of r.entries()){if(h.remaining<=0)break;let i=Math.ceil(h.remaining/(r.length-e)),a={remaining:i};try{let e=Rn(m.graph,{passes:1,accept:n,edgeIds:new Set([t.id]),searchBudget:a}),r=Ln(e.graph);_.push({pass:d,edgeId:t.id,cost:r,visited:i-a.remaining}),re.points),b=[],x=new Map,S=[],C=new Set(r?[...c.keys()].filter(e=>!r.has(e)):[]),w=e=>{C.add(e.id),Fn({...a,edges:a.edges.filter(e=>C.has(e.id))},new Set([e.id]));let t=H(a).get(e.id);t.label&&S.push(vn(t.labelBox,s.labelEdgeGap)),p.push(t.points)};try{for(let e of y){let t=a.edges.find(t=>t.id===e.id),n=a.nodes.find(e=>e.id===t.source),r=a.nodes.find(e=>e.id===t.target);if(n===r){let e=[...a.edges].filter(e=>e.source===n.id&&e.target===n.id).sort(xn).findIndex(e=>e.id===t.id),r=In(n,a,[...u,...S],p,s,e,t,f.get(t.id)??0);if(!r)throw Object.assign(Error(`No clear self corridor for `+t.id),{elementIds:[t.id],routingReason:`corridor-space`});x.set(t.id,r.sideIndex),t.route={via:r.via},w(t);continue}let i=On(n,r,a,[`decision`,`choice`].includes(n.kind)&&a.edges.filter(e=>e.source===n.id&&e.target!==n.id).length>=2?c.get(t.id).sourceSide:null,t),l,d;for(let e=f.get(t.id)??0;e=l.cost-.001)continue;let n=Nn(i[e],a,[...u,...S],p,s,h,At(t,o,a.meta.locale),l?.cost);if(n){let t=e=>e.cost;if((!l||t(n)e.id))});let e=Ln(a);if(_.push({pass:d,cost:e,fallbacks:b,visited:v-h.remaining}),(!m||e0){let t=e.elementIds[0],n=y.findIndex(e=>e.id===t);if(n>0){y=[y[n],...y.slice(0,n),...y.slice(n+1)];continue}}if(e.routingReason===`label-space`){let t=e.elementIds[0];if(f.set(t,(x.get(t)??f.get(t)??0)+1),h.remaining>0)continue}}break}}if(!m)throw Object.assign(g??Error(`No routing candidate`),{routingReport:{attempts:_,termination:`no-valid-candidate`,provenImpossible:!1}});return{graph:m.graph,report:{strategy:`nearest-outline-orthogonal`,budget:v,evaluations:_.length,selected:m.pass,attempts:_,termination:`bounded-search`,provenImpossible:!1}}}let J=e=>{let t=(e,n=0)=>(Array.isArray(e)&&n<=16?e:[]).filter(e=>e&&typeof e==`object`).flatMap(e=>[e,...t((Array.isArray(e.items)?e.items:[]).filter(e=>e?.mode),n+1)]);return t(e.layout?.sections)},zn=e=>e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim()),Vn=e=>e.overviewText!==void 0||e.overviewTone!==void 0;function Hn(e,{inputOnly:t=!0,validateAnchor:n,evidenceKinds:r}={}){let i=[],a=c(e),o=(e,t)=>{e!==void 0&&!ie.includes(e)&&i.push(`${t} is unsupported`)},s=(e,t)=>{zn(e)?(n?.(e,t,i),e.kind!==void 0&&!r?.has(e.kind)&&i.push(`${t}.kind is unsupported`)):i.push(`${t} must be an object`)};for(let t of e.nodes??[])if(o(t.overviewTone,`node ${t.id}.overviewTone`),t.overviewAccent!==void 0&&typeof t.overviewAccent!=`boolean`&&i.push(`node ${t.id}.overviewAccent must be boolean`),t.overviewText!==void 0&&!Bn(t.overviewText)&&i.push(`node ${t.id}.overviewText must contain non-empty strings`),t.badges!==void 0){if(!Array.isArray(t.badges))i.push(`node ${t.id}.badges must be an array`);else for(let[e,n]of t.badges.entries()){let a=`node ${t.id}.badges[${e}]`;(!zn(n)||typeof n.label!=`string`||!n.label.trim()||![`status`,`version`,`requirement`].includes(n.role)||!r?.has(n.evidence))&&i.push(`${a} needs label, role (status/version/requirement) and evidence`),n?.source!==void 0&&s(n.source,`${a}.source`)}}if(!a)return e.layout?.sections!==void 0&&i.push(`layout.sections requires an architecture overview`),i;if(!Array.isArray(e.layout?.sections)||!e.layout.sections.length)return[...i,`architecture overview requires non-empty layout.sections`];let l=new Map(e.nodes.map(e=>[e.id,e])),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=new Set,f=new Set,p=new Set,m=e=>{l.has(e)?d.has(e)?i.push(`section repeats node ${e}`):d.add(e):i.push(`section nodeId does not name a node: ${e}`)},h=(t,n=new Set)=>{if(!u.has(t)){i.push(`section groupId does not name a group: ${t}`);return}if(n.has(t)||p.has(t)){i.push(`section repeats or cycles group ${t}`);return}p.add(t);let r=new Set([...n,t]);e.nodes.filter(e=>e.groupId===t).forEach(e=>m(e.id)),[...u.values()].filter(e=>e.parentId===t).forEach(e=>h(e.id,r))},g=(e,n=0)=>{if(!zn(e)||n>16){i.push(`invalid section or nesting exceeds 16 levels`);return}(typeof e.id!=`string`||!e.id.trim()||f.has(e.id)||l.has(e.id)||u.has(e.id))&&i.push(`section.id must be unique: ${e.id}`),f.add(e.id),[`stack`,`grid`,`row`,`note`].includes(e.mode)||i.push(`section ${e.id}.mode is unsupported`),(typeof e.title!=`string`||!e.title.trim())&&i.push(`section ${e.id}.title is required`),o(e.tone,`section ${e.id}.tone`),e.frame!==void 0&&![`solid`,`dashed`,`none`].includes(e.frame)&&i.push(`section ${e.id}.frame is unsupported`),e.columns!==void 0&&(!Number.isInteger(e.columns)||e.columns<1||e.columns>16||e.mode!==`grid`)&&i.push(`section ${e.id}.columns requires a grid and an integer from 1 to 16`),e.weights!==void 0&&(e.mode!==`row`||!Array.isArray(e.weights)||e.weights.length!==e.items?.length||e.weights.some(e=>!Number.isFinite(e)||e<=0))&&i.push(`section ${e.id}.weights requires a row and one positive finite weight per item`),e.text!==void 0&&!Bn(e.text)&&i.push(`section ${e.id}.text must contain non-empty strings`),e.source!==void 0&&s(e.source,`section ${e.id}.source`),e.detailOf!==void 0&&!l.has(e.detailOf)&&i.push(`section ${e.id}.detailOf does not name a node`),!t&&(!zn(e.position)||!zn(e.size)||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y)||e.position.x<0||e.position.y<0||!Number.isFinite(e.size.width)||!Number.isFinite(e.size.height)||e.size.width<=0||e.size.height<=0)&&i.push(`section ${e.id} requires finite geometry`),e.mode===`note`?(!Bn(e.text)||!e.text.length||(e.items?.length??0))&&i.push(`note ${e.id} requires text and no items`):(!Array.isArray(e.items)||!e.items.length)&&i.push(`section ${e.id}.items must be non-empty`);for(let t of Array.isArray(e.items)?e.items:[]){if(!zn(t)){i.push(`section ${e.id} item must be an object`);continue}[`nodeId`,`groupId`,`mode`].filter(e=>Object.hasOwn(t,e)).length===1?t.nodeId===void 0?t.groupId===void 0?g(t,n+1):h(t.groupId):m(t.nodeId):i.push(`section ${e.id} item needs exactly one nodeId, groupId or nested section`)}};e.layout.sections.forEach(e=>g(e));for(let e of l.keys())d.has(e)||i.push(`overview node ${e} is missing from sections`);return i}function Un(e,t=e.size.width){let n=e.overviewTone===`plain`?0:D.cardPadding,r=t-n*2,i=[],a=e.badges?.length?Math.min(r*.45,Math.max(...e.badges.map(e=>A(e.label,r*.45-16,D.badge,D.badgeLine).width+16))):0,o=n;for(let r of e.badges??[]){let e=A(r.label,a-16,D.badge,D.badgeLine),s=Math.max(48,e.width+16),c=e.height+6;i.push({...r,x:t-n-s,y:o,width:s,height:c,lines:e.lines}),o+=c+6}let s=A(e.label,r-(a?a+10:0),D.title,D.titleLine),c=s.lines.map((e,t)=>({text:e,x:n,y:n+D.title+t*D.titleLine,role:`title`})),l=e.subtitle&&s.lines.length===1&&A(e.subtitle,1/0,D.body,D.bodyLine).width+s.width+12<=r-(a?a+10:0);l&&c.push({text:e.subtitle,x:n+s.width+12,y:n+D.title,role:`body`});let u=Math.max(n+s.height,i.length?o-6:0),d=t>1e3?[(e.overviewText??[]).join(` `)]:e.overviewText??[];for(let t of[l?``:e.subtitle,...d].filter(Boolean)){u+=6;let e=A(t,r,D.body,D.bodyLine);c.push(...e.lines.map((e,t)=>({text:e,x:n,y:u+D.body+t*D.bodyLine,role:`body`}))),u+=e.height}return{lines:c,badges:i,minHeight:u+n}}let Wn=e=>e.frame===`none`?0:D.padding,Gn=(e,t)=>{let n=t-Wn(e)*2;return Wn(e)+A(e.title,n,D.sectionTitle,D.sectionLine).height+(e.text??[]).reduce((e,t)=>e+8+A(t,n,D.body,D.bodyLine).height,0)};function Kn(e){if(e.mode===`note`)return[{...e.position,...e.size}];let t=Wn(e),n=e.position.x+t,r=e.size.width-t*2,i=A(e.title,r,D.sectionTitle,D.sectionLine),a=i.lines.map((r,i)=>({x:n,y:e.position.y+t+i*D.sectionLine,width:A(r,1/0,D.sectionTitle,D.sectionLine).width,height:D.sectionLine})),o=e.position.y+t+i.height;for(let t of e.text??[]){o+=8;let e=A(t,r,D.body,D.bodyLine);a.push(...e.lines.map((e,t)=>({x:n,y:o+t*D.bodyLine,width:A(e,1/0,D.body,D.bodyLine).width,height:D.bodyLine}))),o+=e.height}return a}function qn(t,{width:n=D.width,gap:r=D.cardGap,gaps:i={},bandGaps:a={}}={}){let o=structuredClone(t),s=new Map(o.nodes.map(e=>[e.id,e])),c=new Map((o.groups??[]).map(e=>[e.id,e])),l=(e,t)=>Un(e,t).minHeight,u=e=>({id:e,title:c.get(e).label,mode:`grid`,group:!0,items:[...(o.groups??[]).filter(t=>t.parentId===e).map(e=>({groupId:e.id})),...o.nodes.filter(t=>t.groupId===e).map(e=>({nodeId:e.id}))]}),d=e=>e.nodeId?[e.nodeId]:(e.groupId?u(e.groupId):e).items?.flatMap(d)??[],f=(e,t)=>{if(e.nodeId)return{item:e,width:t,height:l(s.get(e.nodeId),t)};let n=e.groupId?u(e.groupId):e,a=Wn(n),c=i[n.id]??r,p=Gn(n,t)+(n.mode===`note`?0:24);if(n.mode===`note`)return{item:n,width:t,height:p+a};let m=n.mode===`row`?n.items.length:n.mode===`grid`?Math.min(n.items.length,n.columns??Math.max(1,Math.floor((t-a*2+c)/(300+c)))):1,h=[];for(let e=0;e1),o=i.reduce((e,t)=>e+t,0),s=t-a*2-c*(r.length-1),l=r.map((e,t)=>f(e,s*i[t]/o)),u=Math.max(...l.map(e=>e.height));for(let e of l)(n.mode===`grid`&&e.item.nodeId||n.mode===`row`)&&(e.height=u);h.push(l)}let g=new Set(d(n)),_=o.edges.some(e=>g.has(e.source)&&g.has(e.target))?Math.max(c,D.connectedGap):c;return{item:n,width:t,height:p+h.reduce((e,t)=>e+Math.max(...t.map(e=>e.height)),0)+_*Math.max(0,h.length-1)+a,top:p,rows:h,rowGap:_,gap:c,padding:a}},p=(e,t,n)=>{if(e.item.nodeId){let r=s.get(e.item.nodeId);r.position={x:t,y:n},r.size={width:e.width,height:e.height};return}let r=e.item;r.position={x:t,y:n},r.size={width:e.width,height:e.height},r.group&&Object.assign(c.get(r.id),{position:r.position,size:r.size});let i=n+e.top;for(let n of e.rows??[]){let r=t+e.padding;for(let t of n)p(t,r,i),r+=t.width+e.gap;i+=Math.max(...n.map(e=>e.height))+e.rowGap}},m=e=>{if(e.nodeId)return 300;let t=e.groupId?u(e.groupId):e,n=Wn(t);if(i[t.id],t.mode===`note`)return 300+n*2;let a=t.items.map(m);if(t.mode===`row`){let e=t.weights??a.map(()=>1);return n*2+Math.max(...a.map((t,n)=>t/e[n]))*e.reduce((e,t)=>e+t,0)+r*(a.length-1)}return t.columns?n*2+Math.min(t.columns,t.items.length)*176+r*(Math.min(t.columns,t.items.length)-1):n*2+Math.max(...a)};n=Math.max(n,...o.layout.sections.map(m));let h=D.margin;for(let e of o.layout.sections){let t=f(e,n);p(t,D.margin,h),h+=t.height+Math.max(a[e.id]??r,D.bandGap)}let g=e=>{let t=[...o.nodes.filter(t=>t.groupId===e.id),...(o.groups??[]).filter(t=>t.parentId===e.id).map(e=>(g(e),e))];if(!t.length)throw Error(`Empty ownership group ${e.id}`);let r=Math.min(...t.map(e=>e.position.x))-D.padding,i=Math.min(...t.map(e=>e.position.y))-A(e.label,n,20,26).height-D.padding,a=Math.max(...t.map(e=>e.position.x+e.size.width))+D.padding,s=Math.max(...t.map(e=>e.position.y+e.size.height))+D.padding;e.position={x:Math.max(0,r),y:Math.max(0,i)},e.size={width:a-e.position.x,height:s-e.position.y}};for(let e of o.groups??[])!e.parentId&&!J(o).some(t=>t.items?.some(t=>t.groupId===e.id))&&g(e);o.layout.version=e,o.layout.direction=`down`,o.layout.strategy=`architecture-overview-v2`;for(let e of o.edges)delete e.route;return tr(o)}function Jn(e,t,n){let r=structuredClone(e);for(let e of r.nodes){let n=t.nodes.find(t=>t.id===e.id);JSON.stringify(e)!==JSON.stringify(n)&&(e.size.height=Math.max(e.size.height,Un(e).minHeight))}let i=(e,n)=>{if(e.join(`\\0`)===n.join(`\\0`))return;let i=e.map(e=>t.nodes.find(t=>t.id===e));n.forEach((e,t)=>{let n=r.nodes.find(t=>t.id===e);n.position={...i[t].position}})};for(let e of J(r)){let n=J(t).find(t=>t.id===e.id);n&&i((n.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId),(e.items??[]).filter(e=>e.nodeId).map(e=>e.nodeId))}for(let e of r.groups??[])i(t.nodes.filter(t=>t.groupId===e.id).map(e=>e.id),r.nodes.filter(t=>t.groupId===e.id).map(e=>e.id));let a=hn(t,r);return r.edges=ee(r,Rn(T(r),{edgeIds:a,passes:2,accept:n}).graph),n(r,{strictEdgeIds:a}),r}let Yn=new WeakMap;function Xn(e,t){let n={},r={},i=[],a;for(let o=0;o<60;o++)try{let a=qn(e,{gaps:n,bandGaps:r});return t(a),Yn.set(a,{evaluations:o+1,budget:60,gaps:{...n},bandGaps:{...r},attempts:i,termination:`valid-local-spacing`,provenImpossible:!1}),a}catch(t){a=t;let o=new Set([...t.elementIds??[],...(t.diagnostics??[]).flatMap(e=>e.elementIds)]);for(let t of e.edges)o.has(t.id)&&(o.add(t.source),o.add(t.target));let s=J(e),c=t=>(t.items??[]).flatMap(t=>t.nodeId?[t.nodeId]:t.groupId?e.nodes.filter(e=>e.groupId===t.groupId).map(e=>e.id):c(t)),l=s.filter(e=>c(e).some(e=>o.has(e))),u=l.filter(e=>!l.some(t=>t!==e&&(e.items??[]).includes(t)));if(!u.length)throw t;let d=!1;for(let e of u){let t=n[e.id]??D.cardGap;t>=200||(n[e.id]=t+16,d=!0)}for(let t of e.layout.sections)if(c(t).some(e=>o.has(e))){let e=r[t.id]??D.bandGap;e<200&&(r[t.id]=e+16,d=!0)}if(i.push({elementIds:[...o],reason:t.routingReason??`quality`,gaps:{...n},bandGaps:{...r}}),!d)break}throw Object.assign(a,{routingReport:{attempts:i,termination:`local-spacing-budget`,provenImpossible:!1}})}let Zn=e=>String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Qn=(e,t,n,r,i=``)=>`${Zn(n)}`;function $n(e,t,n,r){let i=se(r),a=i[e.overviewTone??`subtle`]??i.subtle,o=Un(e),s=e.overviewTone===`plain`,c=`overview-card-${[...e.id].map(e=>e.codePointAt(0).toString(16)).join(`-`)}`,l=!s&&a.band&&e.size.width>1e3?``:``,u=``,d=e.overviewAccent&&a.accent?``:``,f=o.lines.map(e=>Qn(t+e.x,n+e.y,e.text,e.role,`fill:${e.role===`title`?i.ink:i.body};font-size:${e.role===`title`?D.title:D.body}px;font-weight:${e.role===`title`?700:400}`)).join(``);return l+u+d+f+o.badges.map(e=>{let r=/^(已实现|已完成|完成|implemented|ready|done|complete)$/i.test(e.label),o=e.role===`version`?{fill:a.accent??i.blue.accent,ink:i.paper}:e.role===`status`&&r||e.role===`requirement`&&/^(必选|required|mandatory)$/i.test(e.label)?i.success:i.badge;return`${e.lines.map((r,i)=>Qn(t+e.x+8,n+e.y+3+D.badge+i*D.badgeLine,r,`meta`,`fill:${o.ink};font-size:${D.badge}px;font-weight:600`)).join(``)}`}).join(``)}function er(e,t=new Map){if(!c(e))return[];let n=[],r=J(e);for(let t of r){let r=Gn(t,t.size.width)+Wn(t);t.size.heighte.id===r.nodeId):r.groupId?e.groups.find(e=>e.id===r.groupId):r;i&&(i.position.xt.position.x+t.size.width-Wn(t)+.01||i.position.y+i.size.height>t.position.y+t.size.height-Wn(t)+.01)&&n.push(`section ${t.id} does not contain ${i.id}`)}}let i=e=>({...e.position,...e.size}),a=(e,t)=>e.xt.x&&e.yt.y,o=t=>{let r=t.map(t=>t.nodeId?e.nodes.find(e=>e.id===t.nodeId):t.groupId?(e.groups??[]).find(e=>e.id===t.groupId):t).filter(Boolean);for(let e=0;e{let r=0,i=1;for(let[a,o]of[[`x`,`width`],[`y`,`height`]]){let s=t[a]-e[a];if(!s){if(e[a]<=n[a]||e[a]>=n[a]+n[o])return!1;continue}let c=(n[a]-e[a])/s,l=(n[a]+n[o]-e[a])/s;if(r=Math.max(r,Math.min(c,l)),i=Math.min(i,Math.max(c,l)),r>=i)return!1}return i>0&&r<1};for(let e of r)for(let r of Kn(e))for(let[i,o]of t)o.points.slice(1).some((e,t)=>s(o.points[t],e,r))&&n.push(`overview route ${i} crosses section ${e.id} text`),o.label&&a(o.labelBox,r)&&n.push(`overview label ${i} overlaps section ${e.id} text`);return n}function tr(e){return e.edges=ee(e,Rn(T(e),{passes:3}).graph),e}function nr(e,t,n,r,i,a,o,s,c=0,l=0){if(e.classicCard)return or(e,t,n,r,i,a,o,s,c);let{title:u,subtitle:d,source:f,tag:p,chips:m,contentHeight:h}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!1,l),g=t+c,_=n+Math.max(0,(e.size.height-h)/2)+j.pad,v=g+j.textX,y=_+u.height+(d.height?4:0),b=y+d.height+(f.height?6:0),x=b+f.height+(m.length?6:0),S=m.map(e=>{let t=x+e.row*j.chipLine;return`${P(v+e.x+e.width/2,t+15,e.text,`stereotype`,` text-anchor="middle"`)}`}).join(``),C=u.lines.map((e,t)=>P(v,_+20+t*u.lineHeight,e,`title`)).join(``),w=d.lines.map((e,t)=>P(v,y+17+t*d.lineHeight,e,`body`)).join(``),T=f.lines.map((e,t)=>P(v,b+14+t*f.lineHeight,e,`meta`)).join(``),ee={x:g+j.pad,y:_+(j.titleLine-j.plate)/2},E=t+e.size.width-c-j.pad-p.width-l;return`${rr(e,t,n,r,i,s)}${ir(e,ee.x,ee.y,j.plate,a)}${P(E+p.width/2,_+18,p.text,`stereotype`,` text-anchor="middle"`)}${C}${w}${T}${S}`}let rr=(e,t,n,r,i,a)=>F(a(e,t,n),{fill:r,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1});function ir(e,t,n,r,i){let a=e.appearance?.chip,o=a?`#ffffff`:de(e)?i.accent:ue.has(e.kind)?i.data:e.kind===`failure`?i.warn:i.ink2,s=(r-15)/2;return`${ar(e)}`}let ar=e=>ue.has(e.kind)?``:[`external`,`actor`].includes(e.kind)?``:[`security`,`config`].includes(e.kind)?``:``;function or(e,t,n,r,i,a,o,s,c){let{title:l,subtitle:u}=Oe({...e,size:{...e.size,width:e.size.width-c*2}},o,!0),d=l.lines.map((e,r)=>P(t+15+c,n+68+r*l.lineHeight,e,`title`)).join(``),f=u.lines.map((e,r)=>P(t+15+c,n+68+l.height+r*u.lineHeight,e,`body`)).join(``);return`${rr(e,t,n,r,i,s)}${ir(e,t+15+c,n+13,25,a)}${P(t+47+c,n+29,De(e,o).text,`stereotype`)}${d}${f}`}let sr=[[.06,0],[.94,0],[1,.16],[1,.84],[.94,1],[.06,1],[0,.84],[0,.16]],cr=[[.08,0],[1,0],[.92,1],[0,1]];function lr(e,t,n){let{width:r,height:i}=e.size;if(Vn(e))return I(e,t,n,16);if(e.kind===`external`)return Le(e,t,n,Ie);if(e.kind===`security`)return I(e,t,n,22);if(e.kind===`failure`)return Le(e,t,n,sr);if(e.kind===`config`)return Le(e,t,n,cr);if(e.kind===`business`)return I(e,t,n,Math.min(28,i/2));let a=I(e,t,n,[`service`,`component`].includes(e.kind)?16:10);return e.kind===`data`?[...a,[`path`,{d:`M${t+10} ${n}V${n+i}M${t+r-10} ${n}V${n+i}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`framework`?[...a,[`path`,{d:`M${t+16} ${n+6}H${t+r-16}M${t+16} ${n+i-6}H${t+r-16}`,fill:`none`,"stroke-dasharray":`7 5`}]]:a}let ur=(e,t,n)=>Vn(e)?Ve(e,t,n,16):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`security`?Ve(e,t,n,22):e.kind===`failure`?Ue(e,t,n,sr):e.kind===`config`?Ue(e,t,n,cr):e.kind===`business`?Ve(e,t,n,Math.min(28,e.size.height/2)):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):L(e,t,n),dr=e=>[`external`,`config`,`failure`].includes(e.kind)?Math.min(28,e.size.width*.08):e.kind===`database`?12:0;var fr={dashedKinds:[`framework`,`optional`],id:`architecture`,label:`Architecture`,nodeKinds:[`external`,`config`,`framework`,`security`,`service`,`business`,`data`,`failure`,`system`,`component`,`database`],groupKinds:[`runtime`,`security`,`ownership`,`external`],edgeKinds:[`request`,`call`,`data`,`success`,`failure`,`framework`,`optional`,`depends`,`aggregates`,`inherits`,`provides`],render:(e,t,n,r,i,a,o)=>Vn(e)?$n(e,t,n,a,r,i):nr(e,t,n,r,i,a,o,lr,dr(e)),outline:lr,anchor:ur,cardLayout:!0,contentInset:dr};let pr=.12,mr=(e,t,n)=>e.kind===`decision`?Re(e,t,n):[`input`,`output`].includes(e.kind)?[[`polygon`,{points:`${t+e.size.width*pr},${n} ${t+e.size.width},${n} ${t+e.size.width*.88},${n+e.size.height} ${t},${n+e.size.height}`}]]:I(e,t,n,[`start`,`end`].includes(e.kind)?e.size.height/2:10),hr=(e,t,n)=>e.kind===`decision`?Ue(e,t,n,[[.5,0],[1,.5],[.5,1],[0,.5]]):[`input`,`output`].includes(e.kind)?Ue(e,t,n,[[pr,0],[1,0],[.88,1],[0,1]]):[`start`,`end`].includes(e.kind)?Ve(e,t,n,e.size.height/2):L(e,t,n),gr=e=>{let{width:t,height:n}=e.size,r=[`input`,`output`].includes(e.kind)?t*pr+12:[`start`,`end`].includes(e.kind)?Math.min(n/2,t/4):18;return{width:e.kind===`decision`?t/2-8:t-r*2,height:e.kind===`decision`?n/2-8:n-12}};function _r(e,t,n,r,i){let{width:a,height:o}=e.size,s=gr(e),c=Pe(t+a/2,n+o/2,e.label,s.width,s.height,e.subtitle),l=e.kind===`subprocess`?``:``;return`${F(mr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${l}${c}`}var vr={id:`flowchart`,label:`Flowchart`,nodeKinds:[`start`,`end`,`process`,`decision`,`input`,`output`,`subprocess`],groupKinds:[],edgeKinds:[`flow`,`yes`,`no`,`success`,`failure`],render:_r,outline:mr,anchor:hr,textArea:gr,edgeLabel:(e,t)=>e.label??([`yes`,`no`].includes(e.kind)?ge(t,e.kind):``)};let yr=(e,t,n)=>I(e,t,n,9);function br(e,t,n,r,i,a,o){let{erHeaderHeight:s,erRowHeight:c,erFontSize:l}=pe(e),u=N(e.subtitle??ge(o,`Entity`),e.size.width-60),d=e.subtitle?O.body:O.small,f=e.fields.map((r,i)=>{let o=n+s+i*c,u=o+c/2+l*.35,d=Math.min(e.size.width*.55,A(r.type,1/0,l).width);return`${r.key===`FK`?``:``}${i?``:``}${r.key?P(t+10,u-1,r.key,`field-key`,` style="fill:${r.key===`FK`?a.accent:a.data}"`):``}${P(t+45,u,N(r.name,Math.max(1,e.size.width-62-d)),`field-name`,` style="font-size:${l}px"`)}${P(t+e.size.width-10,u-1,N(r.type,d),`field-type`,` text-anchor="end" style="font-size:${l}px"`)}`}).join(``);return`${F(yr(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${P(t+13,n+s*.43,N(e.label,e.size.width-26),`entity-title`,` style="font-size:${Math.min(O.title,s*.38)}px;fill:${a.ink}"`)}${P(t+13,n+s*.78,u,`entity-meta`,` style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${P(t+e.size.width-13,n+s*.78,String(e.fields.length).padStart(2,`0`),`entity-meta`,` text-anchor="end" style="font-size:${Math.min(d,s*.23)}px;fill:${a.ink2}"`)}${f}`}var xr={id:`er`,label:`ER diagram`,nodeKinds:[`entity`],groupKinds:[],edgeKinds:[`relationship`],render:br,outline:yr,compartments:!0,cardinalities:!0,endpointStub:28,undirected:[`relationship`],validateNode(e,t,n){(!Array.isArray(e?.fields)||e.fields.length===0)&&n.push(`${t}.fields must be a non-empty array for er`)},validateEdge(e,t,n){for(let r of[`sourceCardinality`,`targetCardinality`])[`1`,`0..1`,`*`,`1..*`,`0..*`].includes(e?.[r])||n.push(`${t}.${r} is unsupported`)}};let Sr=[[0,.1],[.06,0],[1,0],[1,.9],[.94,1],[0,1]];function Cr(e,t,n){let{width:r,height:i}=e.size;return e.kind===`device`?[[`rect`,{x:t+16,y:n,width:r-32,height:i,rx:10}],[`path`,{d:`M${t+r/2} ${n+i-10}V${n+i-5}M${t+r/2-30} ${n+i-5}H${t+r/2+30}`,fill:`none`}]]:e.kind===`node`?[...Le(e,t,n,Sr),[`path`,{d:`M${t} ${n+i*.1}L${t+r*.94} ${n+i*.1}L${t+r} ${n}M${t+r*.94} ${n+i*.1}V${n+i}`,fill:`none`}]]:e.kind===`container`?[...I(e,t,n,10),[`rect`,{x:t+r-30,y:n+13,width:16,height:11,rx:2,fill:`none`}],[`rect`,{x:t+r-34,y:n+17,width:16,height:11,rx:2,fill:`none`}]]:e.kind===`artifact`?[[`path`,{d:`M${t} ${n}H${t+r-28}L${t+r} ${n+28}V${n+i}H${t}Z`}],[`path`,{d:`M${t+r-28} ${n}V${n+28}H${t+r}`,fill:`none`}]]:e.kind===`database`?Fe(e,t,n):e.kind===`external`?Le(e,t,n,Ie):e.kind===`service`?I(e,t,n,16):I(e,t,n,10)}let wr=(e,t,n)=>e.kind===`device`?L(e,t,n,{left:16,right:16,top:0,bottom:0}):e.kind===`node`?Ue(e,t,n,Sr):e.kind===`database`?L(e,t,n,{left:12,right:12,top:2,bottom:2}):e.kind===`external`?Ue(e,t,n,Ie):e.kind===`service`?Ve(e,t,n,16):L(e,t,n),Tr=e=>({container:24,artifact:18,node:20})[e.kind]??0,Er=e=>e.kind===`external`?Math.min(28,e.size.width*.08):[`device`,`database`].includes(e.kind)?12:0;var Dr={id:`deployment`,label:`Deployment`,nodeKinds:[`device`,`node`,`container`,`artifact`,`service`,`database`,`external`],groupKinds:[`host`,`network`,`cluster`,`namespace`],edgeKinds:[`deploy`,`network`,`depends`],render:(e,...t)=>nr(e,...t,Cr,Er(e),Tr(e)),outline:Cr,anchor:wr,cardLayout:!0,contentInset:Er,cardCorner:Tr};let Or=(e,t,n)=>I(e,t,n,9);function kr(e,t,n,r,i,a){let o=e.attributes??[],s=e.methods??[],{classHeaderHeight:c,classRowHeight:l}=pe(e),u=o.length?o.length*l+13:30,d=n+c,f=d+u,p=e.kind===`interface`?`«interface»`:e.kind===`abstract`?`«abstract»`:``,m=e.size.width-26,h=o.map((e,n)=>P(t+13,d+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``),g=s.map((e,n)=>P(t+13,f+6+l/2+O.body*.35+n*l,N(e,m),`member`)).join(``);return`${F(Or(e,t,n),{fill:a.surface2,stroke:i,"stroke-width":e.appearance?.moduleColor||e.appearance?.ring?1.5:1})}${p?P(t+13,n+24,p,`stereotype`):``}${P(t+13,n+(p?50:O.classHeader/2+7),N(e.label,m),`shape-title`)}${e.subtitle?P(t+13,n+c-10,N(e.subtitle,m),`body`):``}${h}${g}`}var Ar={dashedKinds:[`implementation`,`dependency`],id:`class`,label:`Class diagram`,nodeKinds:[`class`,`interface`,`abstract`],groupKinds:[],edgeKinds:[`association`,`inheritance`,`implementation`,`composition`,`aggregation`,`dependency`],render:kr,outline:Or,compartments:!0,undirected:[`association`,`composition`,`aggregation`],markers:{inheritance:{end:`triangle`},implementation:{end:`triangle`},composition:{start:`diamond-filled`},aggregation:{start:`diamond-open`},dependency:{end:`arrow-open`}},edgeLabel:(e,t)=>e.label??([`composition`,`aggregation`,`inheritance`,`implementation`].includes(e.kind)?ge(t,e.kind):``),validateEdge(e,t,n){for(let r of[`source`,`target`]){let i=e[`${r}Multiplicity`];if(i===void 0)continue;let a=typeof i==`string`&&/^(\\d+)(?:\\.\\.(\\d+|\\*))?$/.exec(i);i!==`*`&&(!a||a[2]&&a[2]!==`*`&&Number(a[2]){let r=e[`${n}Multiplicity`];if(r===void 0)return[];let i=n===`source`?t[0]:t.at(-1),a=n===`source`?t[1]:t.at(-2),o=M(r,1/0),s=i.y===a.y,c=Math.sign(s?a.x-i.x:a.y-i.y),l=s?{x:i.x+c*(24+o.width/2),y:i.y-6-o.height/2}:{x:i.x+6+o.width/2,y:i.y+c*(24+o.height/2)};return[{role:n,label:r,labelPoint:l,labelBox:{x:l.x-o.width/2,y:l.y-o.height/2,...o}}]})}};let jr=(e,t,n)=>e.kind===`dataStore`?[[`path`,{d:`M${t+e.size.width} ${n}H${t}V${n+e.size.height}H${t+e.size.width}M${t+12} ${n}V${n+e.size.height}`}]]:I(e,t,n,e.kind===`process`?24:10),Mr=e=>({width:e.size.width-32,height:e.size.height-20});function Nr(e,t,n,r,i){let a=Mr(e);return`${F(jr(e,t,n),{fill:r,stroke:i,"stroke-width":1.2})}${Pe(t+e.size.width/2,n+e.size.height/2,e.label,a.width,a.height,e.subtitle)}`}let Pr=[fr,vr,Je,xr,Dr,Ar,ft,et,{id:`dataflow`,label:`Data flow`,nodeKinds:[`external`,`process`,`dataStore`],groupKinds:[`ownership`,`external`],edgeKinds:[`data`],render:Nr,outline:jr,textArea:Mr,anchor:(e,t,n)=>e.kind===`process`?Ve(e,t,n,24):L(e,t,n)}],Fr=Pr.map(e=>e.id);Object.fromEntries(Pr.map(e=>[e.id,e.label]));let Ir=new Map(Pr.map(e=>[e.id,e]));if(Ir.size!==Pr.length)throw Error(`Duplicate diagram type`);let Y=e=>e?.meta?.diagramType??`architecture`,X=(e=`architecture`)=>Ir.get(e),Lr=e=>X(e).sequence?null:[`flowchart`,`state`].includes(e)?{width:1600,height:2400}:{width:2400,height:1600},Rr=(e,t,n,r=!1)=>t===`architecture`&&Vn(e)?Un(e):Oe({...e,size:{...e.size,width:e.size.width-2*(X(t).contentInset?.(e)??0)}},n,r,X(t).cardCorner?.(e)),zr=e=>{let t=Y(e);return!X(t).cardLayout||e.nodes.every(n=>!n.size||n.size.height>=Rr(n,t,e.meta?.locale).minHeight)},Br=(e,t)=>Math.ceil(A(String(e??``).replace(/\\r?\\n/g,` `),1/0,t).width*1.15),Vr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function Hr(e,t,n=`en`){if(t===`architecture`&&Vn(e))return{width:300,height:Un(e,e.size?.width??300).minHeight};let r=X(t),i=Br(e.label,O.title),a=Br(e.subtitle,O.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return Vr({width:t+50,height:Math.max(80,A(e.label,t,O.title,29).height+5+A(e.subtitle,t,O.body,23.2).height+16)})}if(t===`state`&&nt.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...nt.filter(t=>e[t]).map(t=>Br(e[t],O.small)+it)))),n=A(e.label,t-24,O.title,29),r=A(e.subtitle,t-24,O.body,23.2);return Vr({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+rt({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:Ke({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?Ke(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=Br(e.name,O.body),n=Br(e.type,O.body);return Math.max(t+n+74,n/.55)});return Vr({width:Math.max(240,i+26,a+60,...t),height:Math.max(O.erHeader/.4,O.erHeader+e.fields.length*O.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return Vr({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>Br(e,O.body)+26)),height:O.classHeader+(e.subtitle?24:0)+(t.length?t.length*O.classRow+13:30)+(n.length?n.length*O.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+De(e,n).width+j.tagGap+t,a,Br(Te(e),O.small))+j.textX+j.pad,s=r.contentInset?.({...e,size:{width:Math.min(j.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(j.maxWidth,o+2*s)),height:0};return c.height=Oe({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,Vr(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=A(e.label,t.width,O.title,29),r=A(e.subtitle,t.width,O.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return Vr(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}let Z=(e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),Ur=e=>e.members.map(e=>e.kind),Wr=(e,t)=>Ur(e).some(e=>t.includes(e)),Gr=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function Kr(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(Z))}function qr(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function Jr(e,t){let n=Kr(e,t.edges);return n.length===1&&e.length>5?qr(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||Z(e,t)))}function Yr(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(Z);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(Z).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Xr(e,t){let n=t.layout?.primaryPath??[],r=Kr(e,Yr(t));return r.length===1&&e.length>5?qr(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||Z(e,t)}))}function Zr(e,t){let n=[...e].sort((e,n)=>Gr(n,t.edges)-Gr(e,t.edges)||Z(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return qr(r)}function Qr(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>Kr(e,t.edges))}function $r(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=Kr(r,n),o=Kr(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>Wr(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function ei(e,t){let n=e.filter(e=>Wr(e,[`initial`])),r=e.filter(e=>Wr(e,[`final`]));return[n,...Kr(e.filter(e=>!n.includes(e)&&!r.includes(e)),Yr(t)),r].filter(e=>e.length)}function ti(e,t,n=0){let r=e.filter(e=>Wr(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(Z),i.sort(Z)].filter(e=>e.length):n>=2?i.sort(Z).map(e=>[e]):Zr(i,t)}function ni(e,t){let n=e.filter(e=>Wr(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=Kr(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(Z)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}let ri=Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:Jr},flowchart:{structure:`workflow-spine`,arrange:Xr},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:Zr},deployment:{structure:`runtime-tiers`,arrange:Qr},class:{structure:`contract-hierarchy`,arrange:$r},state:{structure:`lifecycle-branches`,arrange:ei},usecase:{structure:`actor-system`,arrange:ti},dataflow:{structure:`process-store`,arrange:ni}}),ii=e=>ri[u(e)];function ai(e,t,n=Y(t)){let r=Hr(e,n,t.meta?.locale),i=t.edges.filter(t=>t.source===e.id&&t.target===e.id),a=Math.max(0,...i.map(e=>M(At(e,n,t.meta?.locale)).height+32));return a>r.height?{...r,height:Math.ceil(a)}:r}function oi(e,t=0){let n=ii(e);if(!n?.arrange||u(e)!==`deployment`&&e.layout?.direction&&!e.layout?.version&&!e.layout?.strategy?.startsWith(`template-`)||e.edges.length===e.nodes.length-1&&e.nodes.every(t=>e.edges.filter(e=>e.source===t.id).length<=1&&e.edges.filter(e=>e.target===t.id).length<=1)&&![`flowchart`,`class`,`state`,`deployment`,`dataflow`,`usecase`].includes(u(e)))return null;let r=structuredClone(e),i=Y(r),a=X(i),o=h(a),s=g(a);r.nodes.forEach(e=>{e.size=ai(e,r,i)}),r.edges.forEach(e=>{delete e.route});let c=r.groups??[];function l(a){let u=c.filter(e=>e.parentId===a).sort(Z).map(e=>{let t=l(e.id),n=Me({...e,size:void 0}),r=n.height+o.groupHeadingGap,i=o.groupInset;return e.size={width:Math.max(n.width+2*i,t.width+2*i),height:r+t.height+i},{...e,members:t.members,ids:new Set(t.members.map(e=>e.id)),children:t.items,inset:{x:i,y:r},original:e}}),d=r.nodes.filter(e=>e.groupId===a).sort(Z).map(e=>({...e,members:[e],ids:new Set([e.id]),original:e})),f=[...u,...d].sort(Z),p=f.length>0&&f.every(e=>e.members.length&&e.members.every(t=>t.layout?.rank!==void 0&&t.layout.rank===e.members[0].layout.rank)),m=n.arrange(f,r,t);if(p){let e=new Map;for(let t of f){let n=t.members[0].layout.rank;e.set(n,[...e.get(n)??[],t])}m=[...e].sort(([e],[t])=>e-t).map(([,e])=>e.sort(Z))}if(t>=2){let e=new Map(f.flatMap(e=>[...e.ids].map(t=>[t,e])));for(let t=0;t<4;t++){let n=new Map(m.flatMap(e=>e.map((t,n)=>[t.id,(n+.5)/e.length])));for(let i of t%2?[...m].reverse():m){if(i.some(e=>e.layout?.order!==void 0))continue;let t=t=>{let a=r.edges.flatMap(n=>{let r=e.get(n.source),a=e.get(n.target);return r===t&&a&&!i.includes(a)?[a]:a===t&&r&&!i.includes(r)?[r]:[]});return a.length?a.reduce((e,t)=>e+n.get(t.id),0)/a.length:n.get(t.id)};i.sort((e,n)=>t(e)-t(n)||Z(e,n))}}}let h=i===`architecture`&&(e.layout?.direction??v(i)[0])===`right`||i===`dataflow`||i===`usecase`&&f.some(e=>Wr(e,[`actor`]))||p&&(e.layout?.direction??v(i)[0])===`right`,g=h?`x`:`y`,_=h?`y`:`x`,y=h?`width`:`height`,b=h?`height`:`width`,x=Array.from({length:Math.max(0,...m.map(e=>e.length))},(e,t)=>Math.max(0,...m.map(e=>e[t]?.size[b]??0))),S=r.edges.filter(e=>e.source===e.target?m.some(t=>t.length>1&&t.some(t=>t.ids.has(e.source))):m.some(t=>t.some(t=>t.ids.has(e.source))&&t.some(t=>t.ids.has(e.target))&&!t.some(t=>t.ids.has(e.source)&&t.ids.has(e.target)))),C=e=>M(At(e,i,r.meta.locale))[b],w=Math.max(0,...S.filter(e=>e.source!==e.target).map(C)),T=Math.max(0,...S.filter(e=>e.source===e.target).map(e=>C(e)+2*o.labelGap+8)),ee=Math.max(s.nodeGap,Math.min(w+2*o.labelGap,240),T)+t*24,E=x.map((e,t)=>x.slice(0,t).reduce((e,t)=>e+t+ee,0)),te=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*ee,ne=0;for(let e of m){let n=new Set(e.flatMap(e=>[...e.ids])),a=r.edges.filter(e=>n.has(e.source)||n.has(e.target)).map(e=>M(At(e,i,r.meta.locale))),c=i===`class`&&r.edges.some(e=>(n.has(e.source)||n.has(e.target))&&(e.sourceMultiplicity!==void 0||e.targetMultiplicity!==void 0)),l=Math.max(i===`flowchart`?64:s.layerGap,c?176:i===`usecase`&&h?Math.max(160,r.edges.length*24):0,...a.map(e=>e[y]+2*o.labelGap))+t*24,u=Math.max(0,...e.map(e=>e.size[y])),d=[`flowchart`,`state`,`usecase`,`dataflow`].includes(i);e.forEach((t,n)=>{t.position={[g]:ne+(d?(u-t.size[y])/2:0),[_]:(i===`architecture`?e.slice(0,n).reduce((e,t)=>e+t.size[b]+ee,0):E[n])+(d?(x[n]-t.size[b])/2:0)}}),e.length===1&&[`flowchart`,`class`,`state`].includes(i)&&(e[0].position[_]=(te-e[0].size[b])/2),ne+=u+l}if(i===`flowchart`&&r.layout?.primaryPath?.length){let e=new Set(r.layout.primaryPath),t=f.filter(t=>t.members.some(t=>e.has(t.id))),n=Math.max(0,...t.map(e=>e.size.width));for(let e of m){let r=n+s.nodeGap;for(let i of e)t.includes(i)?i.position.x=(n-i.size.width)/2:(i.position.x=r,r+=i.size.width+s.nodeGap)}}return{width:Math.max(0,...f.map(e=>e.position.x+e.size.width)),height:Math.max(0,...f.map(e=>e.position.y+e.size.height)),items:f,members:f.flatMap(e=>e.members)}}function d(e,t){for(let n of e){let e={x:t.x+n.position.x,y:t.y+n.position.y};n.original.position=e,n.children&&d(n.children,{x:e.x+n.inset.x,y:e.y+n.inset.y})}}let f=l(void 0),p=Math.max(64,...r.edges.map(e=>M(At(e,i,r.meta.locale)).width+64));if(d(f.items,{x:p,y:p}),i===`architecture`&&t>=2){let e=r.layout?.direction===`right`?`y`:`x`,t=e===`x`?`y`:`x`,n=e===`x`?`width`:`height`,i=new Map;for(let e of[...r.nodes].sort(Z)){let r=`${e.groupId}:${e.position[t]}:${e.size[n]}`;i.set(r,[...i.get(r)??[],e])}for(let t=0;t<2;t++){let t=new Map(r.nodes.map(t=>[t.id,t.position[e]+t.size[n]/2]));for(let[,n]of[...i].sort(([e],[t])=>e.localeCompare(t))){if(n.length<2||n.some(e=>e.layout?.order!==void 0))continue;let i=n.map(t=>t.position[e]).sort((e,t)=>e-t),a=e=>{let n=r.edges.filter(t=>t.source===e.id||t.target===e.id).map(t=>r.nodes.find(n=>n.id===(t.source===e.id?t.target:t.source))).filter(t=>t.groupId!==e.groupId);return n.length?n.reduce((e,n)=>e+t.get(n.id),0)/n.length:t.get(e.id)},o=new Map(n.map(e=>[e.id,a(e)]));n.sort((e,t)=>o.get(e.id)-o.get(t.id)||Z(e,t)),n.forEach((t,n)=>{t.position[e]=i[n]})}}}if(i===`usecase`){let e=r.nodes.filter(e=>e.kind===`actor`);for(let t of e){let e=r.edges.filter(e=>e.source===t.id||e.target===t.id).map(e=>r.nodes.find(n=>n.id===(e.source===t.id?e.target:e.source))).filter(e=>e.kind===`usecase`);e.length&&(t.position.y=e.reduce((e,t)=>e+t.position.y+t.size.height/2,0)/e.length-t.size.height/2)}e.sort((e,t)=>e.position.y-t.position.y||Z(e,t));for(let t=1;t[`decision`,`choice`].includes(e.kind))){let t=e=>{let t=r.nodes.find(t=>t.id===e.target);return t.position.x+t.size.width/2};r.edges.filter(t=>t.source===e.id&&t.target!==e.id).sort((e,n)=>t(e)-t(n)||Z(e,n)).forEach((t,n)=>{t.route={via:[{x:e.position.x+(n%2?e.size.width+12:-12),y:e.position.y+e.size.height/2}]}})}return r}function si(e,t){if(Y(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=u(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}function ci(e,t,{keepColumns:n=!1}={}){let r=structuredClone(e),i=r.groups??[],a=new Map(r.edges.map(e=>[e.id,e])),o=new Map,s=r.nodes.every(e=>e.position);for(let e of[...r.edges].sort((e,t)=>e.order-t.order))for(let t of[e.source,e.target])o.has(t)||o.set(t,o.size);let c=e=>s?e.position.x:o.get(e.id)??1/0,l=(r.layout?.participantOrder??[...r.nodes].sort((e,t)=>(e.layout?.order??0)-(t.layout?.order??0)||c(e)-c(t)||(e.ide.id)).map(e=>r.nodes.find(t=>t.id===e)),u=d.nodeGap+t*8,p=12+t*4,m=(e,t)=>e.kind===`par`?t.label:`${e.kind===`loop`?`${e.loop.min}..${e.loop.max} `:``}[${t.guard}]`,h=(e,t)=>A(m(e,t),f.labelWidth,14,20),g=e=>A(e.body,f.labelWidth,16,24),_=32;for(let e of l){let t=n&&s?e.position.x:_;e.size=Hr(e,`sequence`,r.meta.locale),e.position={x:Math.max(_,t),y:48},_=e.position.x+e.size.width+u}Tt(r,l);for(let e of r.edges)e.route={messageY:200+e.order*100};let v=H(r),y=Ot(r),b=new Set(i.flatMap(e=>(e.operands??[]).flatMap(e=>e.edgeIds))),x=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).order),S=e=>e.edge?e.edge.order:Math.min(1/0,...x(e.group)),C=e=>e.sort((e,t)=>S(e)-S(t)||((e.edge??e.group).id<(t.edge??t.group).id?-1:1)),w=e=>(e.operands??[]).flatMap((t,n)=>gt(e,t,n,i)).map(e=>v.get(e)).flatMap(e=>[...e.points,{x:e.labelBox.x},{x:e.labelBox.x+e.labelBox.width}]),T=e=>{let t=new Set;for(let n=e;n&&!t.has(n.id);n=i.find(e=>e.id===n.parentId)){t.add(n.id);let e=w(n);if(e.length)return e}return[...v.values()].flatMap(e=>e.points)};for(let e of[...i].sort((e,t)=>vt(t,i)-vt(e,i)||e.id.localeCompare(t.id))){if(!e.operands)throw Error(`Sequence group ${e.id} needs explicit operands before automatic layout`);let t=T(e),n=i.filter(t=>t.parentId===e.id),r=Math.max(yt({...e,size:void 0}).width+16,...e.operands.flatMap(t=>[h(e,t).width,g(t).width])),o=e.operands.flatMap((t,n)=>gt(e,t,n,i)).map(e=>a.get(e).route.messageY),s=Math.min(...o),c=Math.max(...o),u=y.filter(e=>!o.length||e.y<=c&&e.y+e.height>=s).sort((e,t)=>e.x-t.x),d=t.length?Math.min(...t.map(e=>e.x)):l[0].position.x,f=Math.min(d,...u.filter(e=>e.x=d-8).map(e=>e.x))-r-40,p=Math.min(f,...n.map(e=>e.position.x-32)),m=Math.max(p+r+120,...t.map(e=>e.x+32),...n.map(e=>e.position.x+e.size.width+32));for(let e of u)e.xm-56-16&&(m=Math.max(m,e.x+e.width+56));e.position={x:p,y:0},e.size={width:Math.ceil(m-p),height:0}}function ee(e,t){let n=v.get(e.id).labelBox,r=e.source===e.target,i=Math.ceil(t+(r?Math.max(16,n.height/2-15):n.height+6));return e.route={messageY:i},i+(r?Math.max(36,15+n.height/2):6)+p}function E(e,t){for(let n of C(e))t=n.edge?ee(n.edge,t):te(n.group,t);return t}function te(e,t){e.position.y=t;let n=t+Math.max(36,yt(e).height+20)+p;for(let[t,r]of e.operands.entries()){n+=h(e,r).height+16,r.body&&(n+=g(r).height+16);let o=i.filter(n=>n.parentId===e.id&&n.parentOperandId===z(r,t));n=E([...r.edgeIds.map(e=>({edge:a.get(e)})),...o.map(e=>({group:e}))],n),n+=p}return e.size.height=n-t+16,t+e.size.height+p}let ne=E([...r.edges.filter(e=>!b.has(e.id)).map(e=>({edge:e})),...i.filter(e=>!e.parentId).map(e=>({group:e}))],48+Math.max(...l.map(Ke))+d.labelGap),re=[...r.edges].sort((e,t)=>e.order-t.order);for(let e=1;ee.position.x),...l.map(e=>e.position.x)));for(let e of[...l,...i])e.position.x+=D;for(let e of r.nodes)e.size.height=ne+32-e.position.y;return r}function li(e){let t=e.groups??[],n=h(X(Y(e))),r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=t.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...o,...e.nodes.filter(e=>e.groupId===a.id)];if(!s.length)return;let c=Me(a),l=c.height+n.groupHeadingGap,u=Math.max(0,Math.min(...s.map(e=>e.position.x))-n.groupInset),d=Math.max(0,Math.min(...s.map(e=>e.position.y))-l),f=Math.max(...s.map(e=>e.position.x+e.size.width))+n.groupInset,p=Math.max(...s.map(e=>e.position.y+e.size.height))+n.groupInset;a.position={x:u,y:d},a.size={width:Math.max(f-u,c.width+2*n.groupInset),height:p-d}};return t.forEach(i),e}function*ui(e){let t=Y(e);if(t===`sequence`)return;let n=X(t),r=h(n),i=g(n);if(yield*di(e,t,r,i),[`architecture`,`deployment`,`er`,`dataflow`].includes(t)){let n=e.groups??[],a=e=>{let t=new Set([e]);for(let e=0;e!==t.size;){e=t.size;for(let e of n)t.has(e.parentId)&&t.add(e.id)}return t};if(t===`architecture`&&!e.layout?.primaryPath?.length){let t=n.filter(e=>!e.parentId).map(t=>{let r=a(t.id);return{item:t,groups:n.filter(e=>r.has(e.id)),nodes:e.nodes.filter(e=>r.has(e.groupId))}}),o=new Map(t.flatMap(e=>e.nodes.map(t=>[t.id,e]))),s=[],c=e=>{let t=[...e.nodes,...e.groups??[]],n=new Map(e.nodes.map(e=>[e.id,e])),r=(Math.max(...t.map(e=>e.position.x+e.size.width))-Math.min(...t.map(e=>e.position.x)))*(Math.max(...t.map(e=>e.position.y+e.size.height))-Math.min(...t.map(e=>e.position.y))),i=e.nodes.reduce((e,t)=>e+t.size.width*t.size.height,0),a=Math.sqrt(i/e.nodes.length),o=e.edges.reduce((e,t)=>{let r=n.get(t.source),i=n.get(t.target);return e+Math.abs(r.position.x+r.size.width/2-i.position.x-i.size.width/2)+Math.abs(r.position.y+r.size.height/2-i.position.y-i.size.height/2)},0);return r/i+o/(Math.max(1,e.edges.length)*a)};for(let a of t){if(a.nodes.some(e=>e.layout?.order!==void 0||e.layout?.rank!==void 0))continue;let l=new Set(e.edges.flatMap(e=>o.get(e.source)===a?[o.get(e.target)]:o.get(e.target)===a?[o.get(e.source)]:[]).filter(e=>e&&e!==a));for(let o of l)for(let l of[`x`,`y`])for(let u of[!1,!0]){let d=l===`x`?`width`:`height`,f=i.nodeGap,p={...o.item.position,[l]:u?o.item.position[l]+o.item.size[d]+f:o.item.position[l]-a.item.size[d]-f};if(p.x<0||p.y<0)continue;let m={...p,...a.item.size};if(t.some(e=>e!==a&&m.xe.id)),g=p.x-a.item.position.x,_=p.y-a.item.position.y,v=e=>e.map(e=>({id:e.id,size:e.size,position:h.has(e.id)?{x:e.position.x+g,y:e.position.y+_}:e.position})),y=c({...e,nodes:v(e.nodes),groups:v(n)});ye.score-t.score||e.id.localeCompare(t.id));for(let t of s.slice(0,12)){let n=structuredClone(e);for(let e of[...n.nodes,...n.groups])t.ids.has(e.id)&&(e.position.x+=t.dx,e.position.y+=t.dy);yield n}}let o=new Map;for(let t of[...n,...e.nodes].sort((e,t)=>e.id.localeCompare(t.id))){let r=n.includes(t),i=`${(r?t.parentId:t.groupId)??``}:${t.position.y}`,s=r?a(t.id):new Set,c=r?e.nodes.filter(e=>s.has(e.groupId)):[t],l={item:t,groups:r?n.filter(e=>s.has(e.id)):[],nodes:c};o.set(i,[...o.get(i)??[],l])}for(let[,t]of[...o].sort(([e],[t])=>e.localeCompare(t))){if(t.length<2||t.some(e=>e.nodes.some(e=>e.layout?.order!==void 0)))continue;let n=t.sort((e,t)=>e.item.position.x-t.item.position.x||e.item.id.localeCompare(t.item.id));for(let t=0;t[e.id,e])),s=[...n];[s[t],s[r]]=[s[r],s[t]];let c=n[0].item.position.x;for(let e=0;eU(e,t)),...(e.groups??[]).flatMap(Qt)],o=[];for(let[i,s]of[[`x`,`width`],[`y`,`height`]]){let c=Math.max(0,...e.edges.map(n=>M(At(n,t,e.meta.locale))[s])),l=i===`y`&&[`class`,`state`,`flowchart`].includes(t)?r.layerGap:r.nodeGap,u=Math.max(l,c+2*n.labelGap),d=a.map(e=>[e[i],e[i]+e[s]]).sort((e,t)=>e[0]-t[0]),f=d[0]?.[1]??0;for(let[e,t]of d)e-f>u+1&&o.push({axis:i,extent:s,cut:e,remove:e-f-u}),f=Math.max(f,t)}o.sort((e,t)=>t.remove-e.remove||e.axis.localeCompare(t.axis)||e.cut-t.cut);for(let t of o)for(let n of[1,.5]){let r=structuredClone(e),i=t.remove*n,a=e=>e>=t.cut?e-i:e>t.cut-i?t.cut-i:e;for(let e of r.nodes)e.position[t.axis]>=t.cut&&(e.position[t.axis]-=i);for(let e of r.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,[t.axis]:a(e[t.axis])}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,[t.axis]:a(e.route.labelAt[t.axis])});for(let e of r.groups??[])e.position[t.axis]>=t.cut?e.position[t.axis]-=i:e.position[t.axis]+e.size[t.extent]>=t.cut&&(e.size[t.extent]-=i);yield r}}let fi=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function pi(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function mi(e,t,n){$(e.file,`${t}.file`,n),pi(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function vi(e,t){_i(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function yi(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!Q(e))return[`graph must be an object`];Q(e.meta)||r.push(`meta must be an object`),$(e.meta?.title,`meta.title`,r),$(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&$(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])pi(e.meta?.[t],`meta.${t}`,r);vi(e.meta?.notes,r),e.meta?.locale!==void 0&&!he.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=Y(e);Fr.includes(i)||r.push(`meta.diagramType is unsupported`);let a=X(i)??X(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!Q(c)){r.push(`${e} must be an object`);continue}$(c?.id,`${e}.id`,r),$(c?.label,`${e}.label`,r),pi(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&$(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!Q(c.source)?r.push(`${e}.source must be an object`):c.source&&(mi(c.source,`${e}.source`,r),c.source.kind!==void 0&&!fi.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])_i(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!Q(n)){r.push(`${i} must be an object`);continue}$(n.name,`${i}.name`,r),$(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:$,validateStringArray:_i})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!Q(s)){r.push(`${e} must be an object`);continue}$(s?.id,`${e}.id`,r),$(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),hi(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!Q(o)){r.push(`${e} must be an object`);continue}$(o?.id,`${e}.id`,r),pi(o.label,`${e}.label`,r),o.module!==void 0&&$(o.module,`${e}.module`,r),$(o?.source,`${e}.source`,r),$(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),fi.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!Q(o.site)?r.push(`${e}.site must be an object`):o.site&&mi(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>gi(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&gi(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:$,sequenceOrders:l})}return r.length===0&&r.push(...Hn(e,{inputOnly:t,validateAnchor:mi,evidenceKinds:fi})),r.length===0&&r.push(...bi(e)),r.length===0&&r.push(..._t(e)),r.length===0&&r.push(...Dt(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...tn(e).errors),r}function bi(e){let t=[],n=Y(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),o=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!o.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(Q(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!a.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${a.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),Q(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of o.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!o.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=o.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=o.get(r.parentId)}}if(e.layout!==void 0&&!Q(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!v(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${v(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!c(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||c(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(Q(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}let xi=e=>({...e.position,...e.size}),Si=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,Ci=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function Ti(e,t,n,r=[]){return r.length||(r=(String(n).includes(`\n- `)?String(n).split(`\n- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\\\w.-])${String(e.id).replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}($|[^\\\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...J(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:Y(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function Ei(e,t={}){let n=yi(e,{inputOnly:!0}),r=n.length?[]:yi(e,{audit:!1}),i=n.length||r.length?null:Di(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw Ti(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\\n- ${a.join(`\n- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function Di(e,{strictEdgeIds:i=null}={}){e=T(e);let a=tn(e),s=Y(e),l=X(s),u=c(e)?{...h(l),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:h(l),d=[...a.diagnostics,...a.crossings],f=(e,t,n,r,i,a)=>d.push({ruleId:e,severity:`error`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),p=new Map(e.nodes.map(e=>[e.id,U(e,s)])),m=new Map(e.nodes.map(e=>[e.id,e]));if(!l.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),n=e.layout?.primaryPath??[];if(s===`flowchart`&&!n.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),r=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(r.length===1&&[...t.values()].every(e=>e.length<=1)){let i=[],a=new Set;for(let e=r[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)i.push(e),a.add(e);i.length===e.nodes.length&&(n=i)}}let i=[`flowchart`,`state`].includes(s)?n.slice(1).map((e,t)=>[m.get(n[t]),m.get(e)]):[],c=[`flowchart`,`state`].includes(s)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let n=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:n,sides:new Set(n.map(e=>a.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],l=y(s,e.layout),d=l?`y`:`x`,h=l?`height`:`width`,g=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=u.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&f(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...p.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),s===`deployment`&&(r(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o(t)>=o(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=m.get(t.source),n=m.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||f(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[p.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let g=!zr(e);for(let t=0;t{let t=a.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;t<_.length;t++){let n=_[t];for(let[e,t]of p){let r=qt(n.box,t);r+.001W(t,n,e))&&f(`spacing.label-edge`,[n.id,t.id],`<6`,r,[n.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&f(`label.on-route`,[r.id],t,0,[i.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!l.sequence)for(let[e,t,n]of[[i.points[0],i.points[1],r.route?.via?.[0]],[i.points.at(-1),i.points.at(-2),r.route?.via?.at(-1)]]){let a=Math.hypot(e.x-t.x,e.y-t.y),o=l.endpointStub??u.endpoint,s=n&&a?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/a:a,c=i.points.length===2&&s>=0?a:Math.min(a,s);c+.001=u.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=u.endpoint&&h(r,i).some(t=>h(n,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===a||t.point===s)&&(e.point===o||e.point===c)))||t.push({x:Math.min(a.x,s.x,o.x,c.x),y:Math.min(a.y,s.y,o.y,c.y),width:Math.max(a.x,s.x,o.x,c.x)-Math.min(a.x,s.x,o.x,c.x),height:Math.max(a.y,s.y,o.y,c.y)-Math.min(a.y,s.y,o.y,c.y),separation:m,shared:p})}t.length&&f(`route.parallel-channels`,[r.id,n.id],Math.min(...t.map(e=>e.separation)),u.parallelGap,t,`Separate parallel channels; only the initial ${u.endpoint}px at one common port may overlap.`)}}if(!l.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of l)Si(c,xi(e))||f(`group.member-inset`,[i.id,e.id],xi(e),c,[a,xi(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&Ci(a,p.get(t.id))&&f(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[a,p.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&qt(a,xi(e))+.001({node:e,probe:fn(e,s)}));for(let o of e.edges){let c=a.routes.get(o.id),l=wi(c),u=t(e)||i?.has(o.id),f=(e,t,n,r,i,a,o=!0)=>d.push({ruleId:e,severity:o&&u?`error`:`warning`,diagramType:s,elementIds:t,measured:n,required:r,bounds:i,remediation:a}),m=1/0,h=0;for(let{node:e,probe:t}of r){let r=l.flatMap(([n,r],i)=>e.id===o.source&&i===0||e.id===o.target&&i===l.length-1?[]:[t(n,r)]),i=Math.min(...r);m=Math.min(m,i),i+.001pn(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&f(`route.boundary-clearance`,[o.id,t.id],Math.min(...e.map(e=>e.distance)),n.boundary,[xi(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=l.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=c.points[0],y=c.points.at(-1),b=Math.abs(_.x-y.x)+Math.abs(_.y-y.y),x=Math.max(0,c.points.length-2),S=b?g/b:null,C=l.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||C||o.source!==o.target&&S>1.8)&&f(`route.complexity`,[o.id],{bends:x,shortSegments:C,detour:S},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...c.points.map(e=>e.x)),y:Math.min(...c.points.map(e=>e.y)),width:Math.max(...c.points.map(e=>e.x))-Math.min(...c.points.map(e=>e.x)),height:Math.max(...c.points.map(e=>e.y))-Math.min(...c.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of er(e,a.routes)){let n=J(e).filter(e=>t.includes(e.id));f(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(xi),`Expand and re-layout the identified section without removing facts.`)}let b=[...d.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...a,errors:b,diagnostics:d,routeMetrics:v,bounds:Mt(e,a.routes)}}let Oi=(e,t)=>e.idt.id);function ki(e,t=Di(e)){let n=[...t.routes.values()],r=Mt(e,t.routes),a=Math.max(1,n.length),o=e.nodes.reduce((t,n)=>{let r=U(n,Y(e));return t+r.width*r.height},0),s=Math.sqrt(o/Math.max(1,e.nodes.length)),c=n.reduce((e,t)=>e+t.points.slice(1).reduce((e,n,r)=>e+Math.abs(n.x-t.points[r].x)+Math.abs(n.y-t.points[r].y),0),0),l=n.reduce((e,t)=>e+Math.max(0,t.points.length-2),0),u=t.crossings.reduce((e,t)=>e+t.measured,0),d=Lr(Y(e)),f=r.width/Math.max(1,r.height),p=d?Math.abs(f-d.width/d.height):0;return{errors:t.errors.length,aspectRatio:f,aspectPenalty:p,area:r.width*r.height,length:c,bends:l,crossings:u,cost:r.width*r.height/o+c/(a*s)+i.bends*l/a+i.crossings*u/a}}let Ai=(e,t)=>e.errorse.source===t||e.target===t).flatMap(e=>[e.source,e.target])]):new Set(e.nodes.map(e=>e.id))}function Mi(e,t){if(!si(e,t))return!1;let n=X(Y(e)).sequence,r=n?`x`:e.layout?.direction===`right`?`y`:`x`;for(let n of e.nodes)for(let i of e.nodes){if(n.id>=i.id||n.groupId!==i.groupId||n.layout?.order===void 0||i.layout?.order===void 0)continue;let e=t.nodes.find(e=>e.id===n.id),a=t.nodes.find(e=>e.id===i.id);if((n.position[r]-i.position[r])*(e.position[r]-a.position[r])<0)return!1}if([`flowchart`,`state`].includes(Y(e)))for(let n of e.edges){let r=e.nodes.find(e=>e.id===n.source),i=e.nodes.find(e=>e.id===n.target);if(r.id===i.id)continue;let a=t.nodes.find(e=>e.id===r.id),o=t.nodes.find(e=>e.id===i.id);if(r.position.x===i.position.x&&i.position.y>r.position.y&&o.position.y<=a.position.y||i.position.x>r.position.x&&i.position.y=a.position.y))return!1}if(n){let n=[...e.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t));for(let e=1;et.id===n[e].id).position.x<=t.nodes.find(t=>t.id===n[e-1].id).position.x)return!1}return!0}function Ni(e){let t=structuredClone(e),n=h(X(`sequence`)),r=[...t.nodes].sort((e,t)=>e.position.x-t.position.x||Oi(e,t)),i=r.map(e=>e.position.x);for(let e=1;e0)for(let n=e;ne.position.x-i[t]);if(a.some(e=>e>156))return null;let o=e=>e+(a[i.findLastIndex(t=>t<=e)]??0);for(let e of t.groups??[]){let t=o(e.position.x+e.size.width);e.position.x=o(e.position.x),e.size.width=t-e.position.x}for(let e of t.edges)e.route?.via&&(e.route.via=e.route.via.map(e=>({...e,x:o(e.x)}))),e.route?.labelAt&&(e.route.labelAt={...e.route.labelAt,x:o(e.route.labelAt.x)});return t}function Pi(e,t,n){let r=structuredClone(e),i=Y(r),a=X(i),o=h(a);if(a.sequence)return Ni(e);let s=new Set([t]),c=new Set([t]);for(let e=0;e!==c.size;){e=c.size;for(let e of r.edges)(c.has(e.source)||c.has(e.target))&&(c.add(e.source),c.add(e.target))}for(let t=0;t=l.id||!s.has(a.id)&&!s.has(l.id))continue;let u=Math.max(a.position.x,l.position.x)-Math.min(a.position.x+a.size.width,l.position.x+l.size.width),d=Math.max(a.position.y,l.position.y)-Math.min(a.position.y+a.size.height,l.position.y+l.size.height);if(Math.hypot(Math.max(0,u),Math.max(0,d))>=o.nodeGap)continue;let f=n===`x`||[`flowchart`,`state`,`class`].includes(i)?`y`:n===`y`?`x`:u<=0?`y`:`x`,p=f===`x`?`width`:`height`,m=a.position[f]<=l.position[f]?a:l,h=m===a?l:a,g=h.position[f],_=m.position[f]+m.size[p]+o.nodeGap-g;for(let t of r.nodes.filter(e=>e.groupId===h.groupId&&(c.has(e.id)||Math.abs(e.position[f]-g)<.001)&&e.position[f]>=g)){t.position[f]+=_;let n=e.nodes.find(e=>e.id===t.id).position;if(Math.abs(t.position[f]-n[f])>156)return null;s.add(t.id)}t=!0}if(!t)break}let l=r.groups??[],u=new Map(l.map(e=>[e.id,e])),d=(e,t)=>{for(let n=u.get(e),r=0;n&&rs.has(e.id)))for(let n of l){if(d(t.groupId,n.id))continue;let i=Math.min(t.position.x+t.size.width,n.position.x+n.size.width)-Math.max(t.position.x,n.position.x),a=Math.min(t.position.y+t.size.height,n.position.y+n.size.height)-Math.max(t.position.y,n.position.y);if(i<=0||a<=0)continue;let c=[`x`,`y`].map(e=>{let r=e===`x`?`width`:`height`;return{axis:e,delta:n.position[e]+n.size[r]/2>=t.position[e]+t.size[r]/2?t.position[e]+t.size[r]+o.nodeGap-n.position[e]:t.position[e]-o.nodeGap-n.position[e]-n.size[r]}}).sort((e,t)=>Math.abs(e.delta)-Math.abs(t.delta)),u=[...l.filter(e=>d(e.id,n.id)),...r.nodes.filter(e=>d(e.groupId,n.id))],f=c.find(({axis:t,delta:n})=>u.every(r=>{let i=[...e.nodes,...e.groups??[]].find(e=>e.id===r.id);return r.position[t]+n>=0&&Math.abs(r.position[t]+n-i.position[t])<=156}));if(!f)return null;for(let e of u)e.position[f.axis]+=f.delta,r.nodes.includes(e)&&s.add(e.id)}return Fi(r),r}function Fi(e){let t=h(X(Y(e))),n=e.groups??[],r=new Set,i=a=>{if(r.has(a.id))return;r.add(a.id);let o=n.filter(e=>e.parentId===a.id);o.forEach(i);let s=[...e.nodes.filter(e=>e.groupId===a.id),...o];if(!s.length)return;let c=Me(a).height+t.groupHeadingGap,l=t.groupInset,u=Math.max(0,Math.min(a.position.x,...s.map(e=>e.position.x-l))),d=Math.max(0,Math.min(a.position.y,...s.map(e=>e.position.y-c))),f=Math.max(a.position.x+a.size.width,...s.map(e=>e.position.x+e.size.width+l)),p=Math.max(a.position.y+a.size.height,...s.map(e=>e.position.y+e.size.height+l));a.position={x:u,y:d},a.size={width:f-u,height:p-d}};return n.forEach(i),e}function Ii(e,{focusId:t=null,move:n=!0,evaluations:r=60,passes:i=3,laneAxis:a=null,growBoundaries:o=!1,global:s=!1,edgeIds:l=null}={}){a??=/fold\\d+c$/.test(e.layout?.strategy??``)?`x`:/fold\\d+r?$/.test(e.layout?.strategy??``)?`y`:null;let u=structuredClone(e),d=ji(u,t),f=[],p=structuredClone(e);o&&Fi(p),o&&l&&(l=hn(u,p,l));let m=l?new Set(l):t?new Set(p.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):new Set(p.edges.map(e=>e.id)),h=ki(p,Di(p,{strictEdgeIds:m})),_,v=0,y=(e,n=null,r=!1)=>{let a=!r&&l?new Set(l):!r&&t?new Set(e.edges.filter(e=>d.has(e.source)||d.has(e.target)).map(e=>e.id)):null;!s&&!r&&(a=hn(p,e,a??m)),v++;try{if(s){let t=Di(e),n=ki(e,t);if(!n.errors&&Ai(n,h))return f.push({errors:0,cost:n.cost,routing:{termination:`preserved-clear-paths`}}),p=e,h=n,!0;if(!n.errors&&v>1&&(a=hn(p,e),!a.size))return!1;if(n.errors){let n=new Set(t.diagnostics.filter(e=>e.severity===`error`).flatMap(e=>e.elementIds));a=new Set(e.edges.filter(e=>n.has(e.id)).map(e=>e.id))}}let t=Rn(e,{passes:n||s&&v>1?1:i,edgeIds:a,accept:Ei}),r=t.graph,o=ki(r,Di(r,{strictEdgeIds:a??m}));if(f.push({errors:o.errors,cost:o.cost,routing:t.report}),Ai(o,h)){for(let e of a??[])m.add(e);return p=r,h=o,_=t.report,!0}}catch(e){f.push({reason:e.routingReason??`quality`,elementIds:e.elementIds??[],routing:e.routingReport})}return!1};if(r>0&&y(p),n&&t&&h.errors&&v=r)break;if(!(n.nodes.some(e=>e.position.x<0||e.position.y<0)||![`architecture`,`er`].includes(Y(e))&&!Mi(u,n))&&!Di(n).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(n,null,!0)){t=!0;break}}}}if(n&&!s&&!c(e)){let t=X(Y(e)),n=g(t).nodeGap,i=!0;for(;i&&ve.severity===`error`).flatMap(e=>e.elementIds)),s=[...p.nodes].filter(e=>d.has(e.id)).sort((e,t)=>Number(o.has(t.id))-Number(o.has(e.id))||Oi(e,t));for(let c of s){let s=p.edges.filter(e=>e.source===c.id||e.target===c.id).map(e=>p.nodes.find(t=>t.id===(e.source===c.id?e.target:e.source))).filter(e=>e.id!==c.id),l=s.length?s:p.nodes.filter(e=>e.id!==c.id&&e.groupId===c.groupId),d=c.position,f=u.nodes.find(e=>e.id===c.id).position,m=[];for(let r of[...l].sort(Oi))for(let i of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`]){let e=i===`x`?`width`:`height`,t=r.position[i]-d[i]>0?r.position[i]-c.size[e]-n:r.position[i]+r.size[e]+n;Math.abs(t-d[i])>1&&m.push({axis:i,value:d[i]+Math.sign(t-d[i])*Math.min(32,Math.abs(t-d[i]))})}if(o.size)for(let n of t.sequence?[`x`]:a?[a===`x`?`y`:`x`]:[`flowchart`,`state`,`class`].includes(Y(e))?[`y`]:[`x`,`y`])for(let e of[-32,32])m.push({axis:n,value:d[n]+e});let h=new Set;for(let{axis:e,value:t}of m){if(v>=r)break;let n=e+`:`+t;if(h.has(n)||t<0||Math.abs(t-f[e])>156)continue;h.add(n);let a=structuredClone(p);if(a.nodes.find(e=>e.id===c.id).position[e]=t,Mi(u,a)&&!Di(a).diagnostics.some(e=>e.severity===`error`&&(e.ruleId.startsWith(`semantic.`)||e.ruleId.startsWith(`group.`)||e.ruleId===`spacing.nodes`))&&y(a,c.id)){i=!0;break}}if(i||v>=r)break}}}let b={budget:r,evaluations:v,termination:v>=r?`evaluation-budget`:n?`no-improving-local-candidate`:`routing-only`,provenImpossible:!1,routing:_,before:ki(u),after:h,attempts:f};try{Ei(p,{strictEdgeIds:m})}catch(e){throw Object.assign(e,{routingReport:{...b,termination:`no-valid-candidate`}})}let x=p.nodes.filter(e=>{let t=u.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);return{graph:p,movedNodeIds:x,report:b}}function Li(n,r,i={}){let a=[n];if(!t(r)&&Y(r)!==`sequence`&&[...r.nodes,...r.groups??[]].every(e=>e.position&&e.size)){let t=structuredClone(r);t.layout={...t.layout,version:e,strategy:t.layout?.strategy??`legacy-refined`},a.push(t)}let o=i.evaluations??60,s,c,l=0,u=0,d=[];for(let[e,t]of a.entries()){let n=Math.floor(o/(a.length-e));try{let r=Ii(t,{...i,global:!0,evaluations:n});o-=r.report.evaluations,l+=r.report.evaluations,d.push(r.report),(!s||Ai(r.report.after,s.report.after))&&(s=r,u=e)}catch(e){c=e;let t=e.routingReport?.evaluations??n;o-=t,l+=t,d.push(e.routingReport??{termination:`no-valid-candidate`,evaluations:t})}}if(!s)throw Object.assign(c??Error(`No valid refinement candidate`),{routingReport:{budget:i.evaluations??60,evaluations:l,termination:`no-valid-candidate`,seeds:d}});return{...s,report:{...s.report,budget:i.evaluations??60,evaluations:l,selectedSeed:u,...a.length>1?{seeds:d}:{}}}}self.onmessage=({data:t})=>{try{let n=!t.overview&&S(t.graph),r=n?{...t,graph:T(t.graph)}:t,i;if(r.overview)i={graph:r.options?.relayout?Xn(r.graph,Ei):Jn(r.graph,r.reference??r.graph,Ei)};else if(r.options?.relayout&&r.graph.meta.diagramType===`sequence`){let t=[];for(let n=0;n<6;n++)try{let i=ci(r.graph,n);i.layout={...i.layout,version:e},Ei(i),t.push({graph:i})}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid sequence layout`);i=t[0]}else if(r.options?.relayout&&oi(r.graph)){let t=[];for(let n=0;n<4;n++)try{let i=oi(r.graph,n);i.layout={...i.layout,version:e,strategy:`template-${ii(i).structure}-${n}`},t.push(Rn(i,{passes:3,accept:Ei}))}catch{}if(t.sort((e,t)=>ki(e.graph).cost-ki(t.graph).cost),!t.length)throw Error(`No valid semantic layout`);i=Li(t[0].graph,r.graph,{global:!0,evaluations:60})}else i=Ii(r.options?.relayout?{...r.graph,layout:{...r.graph.layout,version:e}}:r.graph,{...r.options,global:!!r.options?.relayout});self.postMessage({result:{graph:n?E(t.graph,i.graph):i.graph,movedNodeIds:i.movedNodeIds??[]}})}catch(e){self.postMessage({error:{message:e.message,diagnostics:e.diagnostics??[],routingReport:e.routingReport}})}}})();',o_=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,a_],{type:`text/javascript;charset=utf-8`});function s_(e){let t;try{if(t=o_&&(self.URL||self.webkitURL).createObjectURL(o_),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(a_),{name:e?.name})}}var c_=(e,t)=>Math.ceil(Z(String(e??``).replace(/\r?\n/g,` `),1/0,t).width*1.15),l_=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Math.ceil(t)]));function u_(e,t,n=`en`){if(t===`architecture`&&Cg(e))return{width:300,height:Tg(e,e.size?.width??300).minHeight};let r=$(t),i=c_(e.label,X.title),a=c_(e.subtitle,X.body);if(t===`state`&&[`initial`,`final`].includes(e.kind)){if(!e.subtitle)return{width:28,height:28};let t=Math.max(i,a);return l_({width:t+50,height:Math.max(80,Z(e.label,t,X.title,29).height+5+Z(e.subtitle,t,X.body,23.2).height+16)})}if(t===`state`&&Am.some(t=>e.kind===`state`&&typeof e[t]==`string`&&e[t].trim())){let t=Math.max(240,Math.min(480,Math.max(Math.max(i,a)+60,...Am.filter(t=>e[t]).map(t=>c_(e[t],X.small)+Nm)))),n=Z(e.label,t-24,X.title,29),r=Z(e.subtitle,t-24,X.body,23.2);return l_({width:t,height:Math.max(72,n.height+(r.height?5+r.height:0)+16)+Mm({...e,size:{width:t,height:0}}).height})}if(r.sequence){let t=Math.max(160,Math.min(280,Math.max(i,a)+28));return{width:t,height:mm({...e,size:{width:t}})+48}}if(e.kind===`actor`)return{width:Math.max(160,i+28,a+28),height:r.sequence?mm(e)+48:104+(e.subtitle?24:0)};if(r.cardinalities){let t=e.fields.map(e=>{let t=c_(e.name,X.body),n=c_(e.type,X.body);return Math.max(t+n+74,n/.55)});return l_({width:Math.max(240,i+26,a+60,...t),height:Math.max(X.erHeader/.4,X.erHeader+e.fields.length*X.erRow)})}if(r.compartments){let t=e.attributes??[],n=e.methods??[];return l_({width:Math.max(240,i+26,a+26,...[...t,...n].map(e=>c_(e,X.body)+26)),height:X.classHeader+(e.subtitle?24:0)+(t.length?t.length*X.classRow+13:30)+(n.length?n.length*X.classRow+13:30)})}if(r.cardLayout){let t=r.cardCorner?.(e)??0,o=Math.max(i+wp(e,n).width+xp.tagGap+t,a,c_(Sp(e),X.small))+xp.textX+xp.pad,s=r.contentInset?.({...e,size:{width:Math.min(xp.maxWidth,o+56),height:0}})??0,c={width:Math.max(240,Math.min(xp.maxWidth,o+2*s)),height:0};return c.height=Tp({...e,size:{...c,width:c.width-2*(r.contentInset?.({...e,size:c})??0)}},n,!1,t).minHeight,l_(c)}let o={width:Math.max(240,Math.min(480,Math.max(i,a)+60)),height:t===`flowchart`?72:100},s=r.textArea??(e=>({width:e.size.width-36,height:e.size.height-20}));for(let t=0;t<16;t++){let t=s({...e,size:o}),n=Z(e.label,t.width,X.title,29),r=Z(e.subtitle,t.width,X.body,23.2),i=n.height+(r.height?5+r.height:0);if(t.height>=i)return l_(o);o.height+=Math.ceil((i-t.height)*2+2)}throw Error(`Cannot measure full text for ${t} node ${e.id}`)}var d_=Object.freeze([`external`,`application`,`infrastructure`,`data`]);function f_(e){return e.layout?.tier?d_.indexOf(e.layout.tier):[`external`,`actor`,`client`].includes(e.kind)?0:e.kind===`database`?3:[`queue`,`cache`].includes(e.kind)?2:1}var p_=new Set([`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`]),m_=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function h_(e,t,n){(typeof e!=`string`||e.trim()===``)&&n.push(`${t} must be a non-empty string`)}function g_(e,t,n){e!==void 0&&typeof e!=`string`&&n.push(`${t} must be a string`)}function __(e,t,n){h_(e.file,`${t}.file`,n),g_(e.symbol,`${t}.symbol`,n),(!Number.isInteger(e.lineStart)||e.lineStart<1)&&n.push(`${t}.lineStart must be a positive integer`),e.lineEnd!==void 0&&(!Number.isInteger(e.lineEnd)||Number.isInteger(e.lineStart)&&e.lineEndtypeof e!=`string`||e.trim()===``))&&n.push(`${t} must be an array of non-empty strings`)}function x_(e,t){b_(e,`meta.notes`,t),Array.isArray(e)&&(e.length>6&&t.push(`meta.notes must have at most 6 items`),e.forEach((e,n)=>{typeof e==`string`&&[...e].length>120&&t.push(`meta.notes[${n}] exceeds 120 characters`)}))}function S_(e,{inputOnly:t=!1,audit:n=!0}={}){let r=[];if(!m_(e))return[`graph must be an object`];m_(e.meta)||r.push(`meta must be an object`),h_(e.meta?.title,`meta.title`,r),h_(e.meta?.sourceRef,`meta.sourceRef`,r),e.meta?.viewId!==void 0&&h_(e.meta.viewId,`meta.viewId`,r),e.meta?.architectureView!==void 0&&((e.meta.diagramType??`architecture`)!==`architecture`||![`relations`,`capabilities`,`engineering`].includes(e.meta.architectureView))&&r.push(`meta.architectureView is unsupported`);for(let t of[`subtitle`,`scope`])g_(e.meta?.[t],`meta.${t}`,r);x_(e.meta?.notes,r),e.meta?.locale!==void 0&&!yf.includes(e.meta.locale)&&r.push(`meta.locale is unsupported`);let i=eh(e);Qm.includes(i)||r.push(`meta.diagramType is unsupported`);let a=$(i)??$(`architecture`);if((!Array.isArray(e.nodes)||e.nodes.length===0)&&r.push(`nodes must be a non-empty array`),Array.isArray(e.edges)||r.push(`edges must be an array`),e.groups!==void 0&&!Array.isArray(e.groups)&&r.push(`groups must be an array when provided`),r.length)return r;let o=new Set,s=new Set;for(let[n,c]of(e.nodes??[]).entries()){let e=`nodes[${n}]`;if(!m_(c)){r.push(`${e} must be an object`);continue}h_(c?.id,`${e}.id`,r),h_(c?.label,`${e}.label`,r),g_(c.subtitle,`${e}.subtitle`,r),c.module!==void 0&&h_(c.module,`${e}.module`,r),a.nodeKinds.includes(c?.kind)||r.push(`${e}.kind is unsupported for ${i}`),v_(c??{},e,r,t),typeof c.id==`string`&&o.has(c.id)&&r.push(`${e}.id duplicates ${c.id}`),o.add(c?.id),s.add(c?.id),c.source!==void 0&&!m_(c.source)?r.push(`${e}.source must be an object`):c.source&&(__(c.source,`${e}.source`,r),c.source.kind!==void 0&&!p_.has(c.source.kind)&&r.push(`${e}.source.kind is unsupported`));for(let t of[`facts`,`tags`,`attributes`,`methods`])b_(c[t],`${e}.${t}`,r);if(c.fields!==void 0){if(!Array.isArray(c.fields))r.push(`${e}.fields must be an array`);else for(let[t,n]of c.fields.entries()){let i=`${e}.fields[${t}]`;if(!m_(n)){r.push(`${i} must be an object`);continue}h_(n.name,`${i}.name`,r),h_(n.type,`${i}.type`,r),n.key!==void 0&&![`PK`,`FK`,`UK`].includes(n.key)&&r.push(`${i}.key is unsupported`),n.nullable!==void 0&&typeof n.nullable!=`boolean`&&r.push(`${i}.nullable must be boolean`)}}a.validateNode?.(c,e,r,{requireString:h_,validateStringArray:b_})}for(let[n,s]of(e.groups??[]).entries()){let e=`groups[${n}]`;if(!m_(s)){r.push(`${e} must be an object`);continue}h_(s?.id,`${e}.id`,r),h_(s?.label,`${e}.label`,r),a.groupKinds.includes(s?.kind)||r.push(`${e}.kind is unsupported for ${i}`),v_(s??{},e,r,t),typeof s.id==`string`&&o.has(s.id)&&r.push(`${e}.id duplicates ${s.id}`),o.add(s?.id)}let c=new Set,l=new Set;for(let[n,o]of(e.edges??[]).entries()){let e=`edges[${n}]`;if(!m_(o)){r.push(`${e} must be an object`);continue}h_(o?.id,`${e}.id`,r),g_(o.label,`${e}.label`,r),o.module!==void 0&&h_(o.module,`${e}.module`,r),h_(o?.source,`${e}.source`,r),h_(o?.target,`${e}.target`,r),a.edgeKinds.includes(o?.kind)||r.push(`${e}.kind is unsupported for ${i}`),p_.has(o?.evidence)||r.push(`${e}.evidence is unsupported`),o.site!==void 0&&!m_(o.site)?r.push(`${e}.site must be an object`):o.site&&__(o.site,`${e}.site`,r),typeof o.id==`string`&&c.has(o.id)&&r.push(`${e}.id duplicates ${o.id}`),c.add(o?.id),typeof o.source==`string`&&!s.has(o.source)&&r.push(`${e}.source does not name a node: ${o.source}`),typeof o.target==`string`&&!s.has(o.target)&&r.push(`${e}.target does not name a node: ${o.target}`),o?.route!==void 0&&(!o.route||typeof o.route!=`object`||Array.isArray(o.route)?r.push(`${e}.route must be an object`):(o.route.via!==void 0&&(Array.isArray(o.route.via)?o.route.via.forEach((t,n)=>y_(t,`${e}.route.via[${n}]`,r)):r.push(`${e}.route.via must be an array`)),o.route.labelAt!==void 0&&y_(o.route.labelAt,`${e}.route.labelAt`,r),o.route.messageY!==void 0&&(i!==`sequence`||!Number.isFinite(o.route.messageY)||o.route.messageY<0)&&r.push(`${e}.route.messageY must be a non-negative finite number for sequence`))),i===`sequence`&&!t&&o.route?.messageY===void 0&&r.push(`${e}.route.messageY is required for a positioned sequence message; regenerate with --layout auto`),a.validateEdge?.(o,e,r,{requireString:h_,sequenceOrders:l})}return r.length===0&&r.push(...wg(e,{inputOnly:t,validateAnchor:__,evidenceKinds:p_})),r.length===0&&r.push(...C_(e)),r.length===0&&r.push(...hh(e)),r.length===0&&r.push(...Oh(e,{inputOnly:t})),r.length===0&&!t&&n&&r.push(...sg(e).errors),r}function C_(e){let t=[],n=eh(e),r=n===`sequence`,i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map((e.groups??[]).map(e=>[e.id,e]));for(let i of e.nodes)if(i.groupId!==void 0&&(r?t.push(`node ${i.id}.groupId is not supported for sequence participants`):typeof i.groupId!=`string`||!a.has(i.groupId)?t.push(`node ${i.id}.groupId does not name a group: ${String(i.groupId)}`):n===`usecase`&&i.kind===`actor`&&t.push(`node ${i.id}.groupId places an actor inside a system boundary`)),i.layout!==void 0&&(m_(i.layout)?i.layout.tier!==void 0&&(n!==`deployment`||!d_.includes(i.layout.tier))&&t.push(`node ${i.id}.layout.tier requires deployment and one of ${d_.join(`, `)}`):t.push(`node ${i.id}.layout must be an object`),m_(i.layout)))for(let e of[`rank`,`order`])i.layout[e]!==void 0&&(!Number.isInteger(i.layout[e])||i.layout[e]<0)&&t.push(`node ${i.id}.layout.${e} must be a non-negative integer`);if(!r)for(let e of a.values()){if(e.parentId===void 0)continue;(typeof e.parentId!=`string`||!a.has(e.parentId))&&t.push(`group ${e.id}.parentId does not name a group: ${String(e.parentId)}`);let n=new Set([e.id]),r=a.get(e.parentId);for(;r;){if(n.has(r.id)){t.push(`group ${e.id}.parentId contains a cycle at ${r.id}`);break}n.add(r.id),r=a.get(r.parentId)}}if(e.layout!==void 0&&!m_(e.layout)?t.push(`layout must be an object`):e.layout?.direction!==void 0&&!Nf(n).includes(e.layout.direction)&&t.push(`layout.direction must be one of ${Nf(n).join(`, `)} for ${n}`),e.layout?.overviewConnections!==void 0&&(!ff(e)||![`within-category`,`all`].includes(e.layout.overviewConnections))&&t.push(`layout.overviewConnections requires an architecture overview and within-category or all`),e.layout?.sharedDependencies!==void 0){let r=e.layout.sharedDependencies;n!==`architecture`||ff(e)?t.push(`layout.sharedDependencies requires an architecture relations view`):!Array.isArray(r)||!r.length||r.some(e=>typeof e!=`string`||!i.has(e))||new Set(r).size!==r.length?t.push(`layout.sharedDependencies must be a non-empty list of distinct node IDs`):Array.isArray(e.layout.primaryPath)&&e.layout.primaryPath.slice(1).some(e=>r.includes(e))&&t.push(`layout.primaryPath cannot enter a shared dependency`)}if(m_(e.layout))for(let n of[`primaryPath`,`participantOrder`]){let a=e.layout?.[n];if(a!==void 0){if(!Array.isArray(a)||!a.length||a.some(e=>typeof e!=`string`||!i.has(e))||new Set(a).size!==a.length){t.push(`layout.${n} must be a non-empty list of distinct node IDs`);continue}if(n===`participantOrder`){(!r||a.length!==i.size)&&t.push(`layout.participantOrder must be a complete permutation of sequence participants`);let e=a.map(e=>i.get(e).layout?.order).filter(e=>e!==void 0);e.some((t,n)=>n&&t<=e[n-1])&&t.push(`layout.participantOrder conflicts with node.layout.order`)}else{r&&t.push(`layout.primaryPath is not supported for sequence; use participantOrder`);for(let n=1;ne.source===a[n-1]&&e.target===a[n])||t.push(`layout.primaryPath has no directed edge from ${a[n-1]} to ${a[n]}`);let r=i.get(a[n-1]).layout?.rank,o=i.get(a[n]).layout?.rank;r!==void 0&&o!==void 0&&r>=o&&t.push(`layout.primaryPath conflicts with node.layout.rank at ${a[n]}`)}}}}r&&new Set(e.nodes.map(e=>e.layout?.rank).filter(e=>e!==void 0)).size>1&&t.push(`sequence participants must share one layout.rank`);for(let r of e.edges){let e=i.get(r.source),a=i.get(r.target);n===`class`&&[`inheritance`,`implementation`].includes(r.kind)&&(r.kind===`implementation`&&a.kind!==`interface`&&t.push(`edge ${r.id} implementation target must be an interface`),e.layout?.rank!==void 0&&a.layout?.rank!==void 0&&a.layout.rank>=e.layout.rank&&t.push(`edge ${r.id} layout.rank must place parent/interface ${a.id} above ${e.id}`)),n===`usecase`&&[`include`,`extend`].includes(r.kind)&&(e.kind!==`usecase`||a.kind!==`usecase`)&&t.push(`edge ${r.id} ${r.kind} endpoints must both be use cases`)}return t}var w_=e=>({...e.position,...e.size}),T_=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height,E_=(e,t)=>e.xe.points.slice(1).map((t,n)=>[e.points[n],t]);function O_(e,t,n,r=[]){return r.length||(r=(String(n).includes(` - `)?String(n).split(` -- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function C_(e,t={}){let n=g_(e,{inputOnly:!0}),r=n.length?[]:g_(e,{audit:!1}),i=n.length||r.length?null:w_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw S_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` -- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function w_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(o_(t)>=o_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)y_(d,v_(e))||s(`group.member-inset`,[i.id,e.id],v_(e),d,[o,v_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&b_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,v_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=x_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[v_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(v_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function T_(e){return function(){return e}}var E_=1664525,D_=1013904223,O_=4294967296;function k_(){let e=1;return()=>(e=(E_*e+D_)%O_)/O_}var A_=10,j_=Math.PI*(3-Math.sqrt(5));function M_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=k_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function N_(e){var t=T_(.1),n,r,i;typeof e!=`function`&&(e=T_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),I_=e=>e.members.map(e=>e.kind),L_=(e,t)=>I_(e).some(e=>t.includes(e)),R_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function z_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(F_))}function B_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function V_(e,t){let n=z_(e,t.edges);return n.length===1&&e.length>5?B_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||F_(e,t)))}function H_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(F_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(F_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function U_(e,t){let n=t.layout?.primaryPath??[],r=z_(e,H_(t));return r.length===1&&e.length>5?B_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||F_(e,t)}))}function W_(e,t){let n=[...e].sort((e,n)=>R_(n,t.edges)-R_(e,t.edges)||F_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return B_(r)}function G_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(o_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>z_(e,t.edges))}function K_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=z_(r,n),o=z_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>L_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function q_(e,t){let n=e.filter(e=>L_(e,[`initial`])),r=e.filter(e=>L_(e,[`final`]));return[n,...z_(e.filter(e=>!n.includes(e)&&!r.includes(e)),H_(t)),r].filter(e=>e.length)}function J_(e,t,n=0){let r=e.filter(e=>L_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(F_),i.sort(F_)].filter(e=>e.length):n>=2?i.sort(F_).map(e=>[e]):W_(i,t)}function Y_(e,t){let n=e.filter(e=>L_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=z_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(F_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:V_},flowchart:{structure:`workflow-spine`,arrange:U_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:W_},deployment:{structure:`runtime-tiers`,arrange:G_},class:{structure:`contract-hierarchy`,arrange:K_},state:{structure:`lifecycle-branches`,arrange:q_},usecase:{structure:`actor-system`,arrange:J_},dataflow:{structure:`process-store`,arrange:Y_}});function X_(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var Z_=156,Q_=160,$_=(e,t,n)=>Math.max(t,Math.min(n,e));function ev(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function tv(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function nv(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-Z_),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+Z_),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:Z_)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:Z_))}}function rv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function iv(e,t=null){if(!t)try{return C_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=ev(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=nv(t,tv(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=M_(o).velocityDecay(.42).force(`anchor-x`,N_(e=>e.anchorX).strength(.16)).force(`anchor-y`,P_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,rv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:$_(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-Z_),e.position.x+Z_),y:r?e.position.y:$_(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-Z_),e.position.y+Z_)};return t.bounds&&(n.x=$_(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=$_(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!X_(e,d))throw Error(`Arrange would invert template bands`);C_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var av=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function ov(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;av(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function cv(e,t,n){let r=sv(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function lv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function uv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var dv=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]),fv=e=>e.meta?.diagramType===`sequence`?Af:jf;function pv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var mv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,hv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function gv(e,t){if(!mv.test(e))throw Error(`page has no graph-data element`);return e.replace(mv,(e,n,r,i)=>`${n}${hv(t)}${i}`)}function _v(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function vv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function yv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function bv(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function xv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return C_(bv(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function Sv(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(Yg(e,a)),[l,u]=Dd(Xg(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:ov},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>vv(_,o,l),[_,o,l]),x=e=>{v(e),s(Yg(e,a)),u(Xg(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new t_,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:S_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(yv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return C_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return C_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=bv(i,xv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=i_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&pv(a,dv(e),sv(i,o,s),void 0,fv(e))||lo(a,i.clientWidth,i.clientHeight,.08,2,cv(i,o,s));return g(c,{duration:n,ease:ov})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:ov});return}let i=p.current;if(!i)return;let o=sv(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=uv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:ov})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(Yg(r,a)),u(Xg(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=iv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function Cv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function wv(e,t){return e.map(e=>({node:e,rank:Cv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function Tv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?wv(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function Ev(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&Cv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function Dv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Ov(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function kv(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Av(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function jv(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Mv={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function Nv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Mv.indent,X.body,Mv.line)),o=r+Mv.top+Mv.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Mv.indent,t+r*Mv.line,e,`body`)).join(``);return o+=e.length*Mv.line+Mv.gap,r}).join(``);return{height:o-r+Mv.bottom,svg:`${Q(n,r+Mv.top,bf(t,`Key points`),`group`)}${s}`}}function Pv(e,t=`light`,n){C_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?Nv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Av(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>jv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Fv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:Pv(e,`light`,r)}))}function Iv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Lv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Rv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=gv(await(await s.getFile()).text(),e),l;try{l=Fv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Lv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function zv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw S_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw S_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Bv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Lv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function Vv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Pv(e,t,i),s=`${Iv(e.meta.title)}.${n}`;await zv(o,e),n===`svg`?Lv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Bv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Hv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=Sv(e,s,d,i),[m,h]=o,g=m&&!s,_=Dv(d,()=>p.readGraph(p.currentGraph,0)),v=Tv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=Ev(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await Vv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Rv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Uv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Wv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=lv(p,sv(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:ov});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:ov})},[e,r,n,t,i,a,o])}var Gv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Kv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Gv[e]})}function qv(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` +- `).slice(1):[String(n)]).map(n=>{let r=[`nodes`,`edges`,`groups`].flatMap(t=>(Array.isArray(e?.[t])?e[t]:[]).filter((e,r)=>e&&typeof e==`object`&&(n.includes(`${t}[${r}]`)||RegExp(`(^|[^\\w.-])${String(e.id).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}($|[^\\w.-])`).test(n))));for(let t of r.filter(e=>e.source&&e.target))r.push(...(e.nodes??[]).filter(e=>e.id===t.source||e.id===t.target));return r.push(...bg(e??{}).filter(e=>String(n).includes(e.id))),{ruleId:`${t}.invalid`,severity:`error`,diagramType:eh(e),elementIds:r.map(e=>e.id),measured:n,required:`Valid ${t} content and complete notation`,bounds:r.filter(e=>e.position&&e.size).map(e=>({...e.position,...e.size})),remediation:t===`semantic`?`Correct the reported input field or reference before layout.`:`Correct the identified content or geometry and retry without removing semantic facts.`}})),Object.assign(Error(String(n)),{diagnostics:r,phases:{semantic:{status:t===`semantic`?`failed`:`passed`},geometry:{status:t===`semantic`?`not-checked`:t===`geometry`?`failed`:`passed`},rendering:{status:t===`rendering`?`failed`:`not-checked`}}})}function k_(e,t={}){let n=S_(e,{inputOnly:!0}),r=n.length?[]:S_(e,{audit:!1}),i=n.length||r.length?null:A_(e,t),a=[...n,...r,...i?.errors??[]],o={semantic:{status:n.length?`failed`:`passed`},geometry:{status:n.length?`not-checked`:a.length?`failed`:`passed`},rendering:{status:`not-checked`}};if(a.length)throw O_(e,n.length?`semantic`:`geometry`,`Diagram quality failed:\n- ${a.join(` +- `)}`,i?.diagnostics??[]);return{...o,diagnostics:i.diagnostics}}function A_(e,{strictEdgeIds:t=null}={}){e=Tf(e);let n=sg(e),r=eh(e),i=$(r),a=ff(e)?{...kf(i),nodeGap:14,labelGap:6,parallelGap:8,groupInset:22,groupHeadingGap:14}:kf(i),o=[...n.diagnostics,...n.crossings],s=(e,t,n,i,a,s)=>o.push({ruleId:e,severity:`error`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),c=new Map(e.nodes.map(e=>[e.id,Zh(e,r)])),l=new Map(e.nodes.map(e=>[e.id,e]));if(!i.sequence){let t=e.nodes.flatMap(t=>e.nodes.filter(e=>t.layout?.rank!==void 0&&e.layout?.rank!==void 0&&t.layout.rank[t,e])),i=e.layout?.primaryPath??[];if(r===`flowchart`&&!i.length&&e.edges.length===e.nodes.length-1){let t=new Map(e.nodes.map(t=>[t.id,e.edges.filter(e=>e.source===t.id)])),n=e.nodes.filter(t=>!e.edges.some(e=>e.target===t.id));if(n.length===1&&[...t.values()].every(e=>e.length<=1)){let r=[],a=new Set;for(let e=n[0].id;e&&!a.has(e);e=t.get(e)[0]?.target)r.push(e),a.add(e);r.length===e.nodes.length&&(i=r)}}let o=[`flowchart`,`state`].includes(r)?i.slice(1).map((e,t)=>[l.get(i[t]),l.get(e)]):[],u=[`flowchart`,`state`].includes(r)?e.nodes.filter(e=>[`decision`,`choice`].includes(e.kind)).map(t=>{let r=e.edges.filter(e=>e.source===t.id&&e.target!==t.id);return{node:t,branches:r,sides:new Set(r.map(e=>n.routes.get(e.id).sourceSide))}}).filter(e=>e.branches.length>=2):[],d=Pf(r,e.layout),f=d?`y`:`x`,p=d?`height`:`width`,m=(e,t,n)=>t.position.x-e.position.x-e.size.width+.001>=a.nodeGap&&(!n||t.position.y5&&Math.max(...e.nodes.map(e=>e.position.y))e.position.y+e.size.height))&&s(`semantic.single-row`,e.nodes.map(e=>e.id),1,`multiple rows`,[...c.values()],`Arrange responsibility layers or wrap peer nodes; tiny y offsets do not create another row.`),r===`deployment`&&(lh(e)||e.layout?.strategy?.startsWith(`template-runtime-tiers`)||e.nodes.some(e=>e.layout?.tier)))for(let t of e.nodes)for(let n of e.nodes){if(f_(t)>=f_(n))continue;let e=n.position.y-t.position.y-t.size.height;e+.001[`inheritance`,`implementation`].includes(e.kind))){let e=l.get(t.source),n=l.get(t.target),r=e.position.y-n.position.y-n.size.height;r+.001[`initial`,`final`].includes(e.kind)))for(let n of e.nodes.filter(e=>![`initial`,`final`].includes(e.kind))){let e=t.kind===`initial`?n.position.y-t.position.y-t.size.height:t.position.y-n.position.y-n.size.height;e+.001n.has(e))||s(`semantic.branch-sides`,[e.id,...t.map(e=>e.id)],[...n],[`left`,`right`],[c.get(e.id)],`Give alternatives separate left and right corridors while retaining their real targets and merges.`)}let u=!nh(e);for(let t=0;t{let t=n.routes.get(e.id);return[...t.label?[{id:e.id,box:t.labelBox}]:[],...(t.endpointLabels??[]).map(t=>({id:e.id,role:t.role,box:t.labelBox}))]});for(let t=0;teg(t,n,e))&&s(`spacing.label-edge`,[r.id,t.id],`<6`,i,[r.box],`Reserve a clear label area away from other relations.`)}}for(let t=0;tMath.hypot(e.x-Math.max(Math.min(t.x,n.x),Math.min(Math.max(t.x,n.x),e.x)),e.y-Math.max(Math.min(t.y,n.y),Math.min(Math.max(t.y,n.y),e.y)))));t>.001&&s(`label.on-route`,[r.id],t,0,[o.labelBox],`Keep the relationship label centred on its own straight segment.`)}if(!i.sequence)for(let[e,t,n]of[[o.points[0],o.points[1],r.route?.via?.[0]],[o.points.at(-1),o.points.at(-2),r.route?.via?.at(-1)]]){let c=Math.hypot(e.x-t.x,e.y-t.y),l=i.endpointStub??a.endpoint,u=n&&c?((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/c:c,d=o.points.length===2&&u>=0?c:Math.min(c,u);d+.001=a.parallelGap)continue;let h=(e,t)=>[{id:e.source,point:t.points[0]},{id:e.target,point:t.points.at(-1)}];m<.001&&p<=a.endpoint&&h(r,o).some(t=>h(i,e).some(e=>t.id===e.id&&t.point.x===e.point.x&&t.point.y===e.point.y&&(t.point===n||t.point===s)&&(e.point===c||e.point===l)))||t.push({x:Math.min(n.x,s.x,c.x,l.x),y:Math.min(n.y,s.y,c.y,l.y),width:Math.max(n.x,s.x,c.x,l.x)-Math.min(n.x,s.x,c.x,l.x),height:Math.max(n.y,s.y,c.y,l.y)-Math.min(n.y,s.y,c.y,l.y),separation:m,shared:p})}t.length&&s(`route.parallel-channels`,[r.id,i.id],Math.min(...t.map(e=>e.separation)),a.parallelGap,t,`Separate parallel channels; only the initial ${a.endpoint}px at one common port may overlap.`)}}if(!i.sequence){let t=e.groups??[],n=new Map(t.map(e=>[e.id,e])),r=(e,t)=>{let r=e.groupId,i=new Set;for(;r&&!i.has(r);){if(r===t.id)return!0;i.add(r),r=n.get(r)?.parentId}return!1};for(let n=0;ne.groupId===i.id),...t.filter(e=>e.parentId===i.id)];for(let e of f)T_(d,w_(e))||s(`group.member-inset`,[i.id,e.id],w_(e),d,[o,w_(e)],`Expand the owning boundary to preserve heading and side clearance.`);for(let t of e.nodes)!r(t,i)&&E_(o,c.get(t.id))&&s(`group.unowned-node`,[i.id,t.id],t.groupId??null,`outside`,[o,c.get(t.id)],`Keep nodes outside boundaries they do not belong to.`);for(let e of t.slice(n+1))i.parentId===e.parentId&&Qh(o,w_(e))+.001({node:e,probe:_g(e,r)}));for(let s of e.edges){let l=n.routes.get(s.id),u=D_(l),d=sh(e)||t?.has(s.id),p=(e,t,n,i,a,s,c=!0)=>o.push({ruleId:e,severity:c&&d?`error`:`warning`,diagramType:r,elementIds:t,measured:n,required:i,bounds:a,remediation:s}),m=1/0,h=0;for(let{node:e,probe:t}of a){let n=u.flatMap(([n,r],i)=>e.id===s.source&&i===0||e.id===s.target&&i===u.length-1?[]:[t(n,r)]),r=Math.min(...n);m=Math.min(m,r),r+.001vg(e,n,t)).filter(e=>e.distance+.001e+t.length,0),e.length&&p(`route.boundary-clearance`,[s.id,t.id],Math.min(...e.map(e=>e.distance)),i.boundary,[w_(t)],`Cross the boundary perpendicularly or leave a clear parallel channel.`)}let g=u.reduce((e,[t,n])=>e+Math.abs(t.x-n.x)+Math.abs(t.y-n.y),0),_=l.points[0],v=l.points.at(-1),y=Math.abs(_.x-v.x)+Math.abs(_.y-v.y),b=Math.max(0,l.points.length-2),x=y?g/y:null,S=u.slice(1,-1).filter(([e,t])=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y)4||S||s.source!==s.target&&x>1.8)&&p(`route.complexity`,[s.id],{bends:b,shortSegments:S,detour:x},{bends:4,shortSegments:0,detour:1.8},[{x:Math.min(...l.points.map(e=>e.x)),y:Math.min(...l.points.map(e=>e.y)),width:Math.max(...l.points.map(e=>e.x))-Math.min(...l.points.map(e=>e.x)),height:Math.max(...l.points.map(e=>e.y))-Math.min(...l.points.map(e=>e.y))}],`Try a simpler corridor or arrange nearby components; necessary detours remain supported.`,!1)}}for(let t of Pg(e,n.routes)){let n=bg(e).filter(e=>t.includes(e.id));s(`overview.section`,n.map(e=>e.id),t,`Complete section text and contained items`,n.map(w_),`Expand and re-layout the identified section without removing facts.`)}let p=[...o.filter(e=>e.severity===`error`).map(e=>`${e.ruleId}: ${e.elementIds.join(`, `)} (${JSON.stringify(e.measured)}; required ${JSON.stringify(e.required)})`)];return{...n,errors:p,diagnostics:o,routeMetrics:f,bounds:Ph(e,n.routes)}}function j_(e){return function(){return e}}var M_=1664525,N_=1013904223,P_=4294967296;function F_(){let e=1;return()=>(e=(M_*e+N_)%P_)/P_}var I_=10,L_=Math.PI*(3-Math.sqrt(5));function R_(e){var t,n=1,r=.001,i=1-r**(1/300),a=0,o=.6,s=new Map,c=Pr(d),l=w(`tick`,`end`),u=F_();e??=[];function d(){f(),l.call(`tick`,t),n1?(n==null?s.delete(e):s.set(e,m(n)),t):s.get(e)},find:function(t,n,r){var i=0,a=e.length,o,s,c,l,u;for(r==null?r=1/0:r*=r,i=0;i1?(l.on(e,n),t):l.on(e)}}}function z_(e){var t=j_(.1),n,r,i;typeof e!=`function`&&(e=j_(e==null?0:+e));function a(e){for(var t=0,a=n.length,o;t(e.layout?.order??0)-(t.layout?.order??0)||e.id.localeCompare(t.id,`en`),H_=e=>e.members.map(e=>e.kind),U_=(e,t)=>H_(e).some(e=>t.includes(e)),W_=(e,t)=>t.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).length;function G_(e,t){let n=new Map(e.flatMap((e,t)=>[...e.ids].map(e=>[e,t]))),r=e.map(()=>new Set);for(let e of t){let t=n.get(e.source),i=n.get(e.target);t!==void 0&&i!==void 0&&t!==i&&r[t].add(i)}let i=0,a=new Map,o=new Map,s=[],c=new Set,l=[];function u(e){a.set(e,i),o.set(e,i++),s.push(e),c.add(e);for(let t of r[e])a.has(t)?c.has(t)&&o.set(e,Math.min(o.get(e),a.get(t))):(u(t),o.set(e,Math.min(o.get(e),o.get(t))));if(o.get(e)===a.get(e)){let t=[],n;do n=s.pop(),c.delete(n),t.push(n);while(n!==e);l.push(t)}}e.forEach((e,t)=>{a.has(t)||u(t)});let d=new Map(l.flatMap((e,t)=>e.map(e=>[e,t]))),f=new Map;function p(e){if(f.has(e))return f.get(e);let t=new Set;r.forEach((n,r)=>{d.get(r)!==e&&[...n].some(t=>d.get(t)===e)&&t.add(d.get(r))});let n=t.size?Math.max(...[...t].map(p))+1:0;return f.set(e,n),n}let m=[];return e.forEach((e,t)=>{let n=p(d.get(t));(m[n]??=[]).push(e)}),m.filter(Boolean).map(e=>e.sort(V_))}function K_(e,t=1.45){if(!e.length)return[];if(e.length<=2)return[e];let n=t=>e.reduce((e,n)=>e+n.size[t],0)/e.length,r=Math.max(1,Math.min(e.length,Math.round(Math.sqrt(e.length*n(`height`)*t/n(`width`)))));return Array.from({length:Math.ceil(e.length/r)},(t,n)=>e.slice(n*r,(n+1)*r))}function q_(e,t){let n=G_(e,t.edges);return n.length===1&&e.length>5?K_(n[0]):n.map(e=>e.sort((e,t)=>String(e.members[0]?.module??``).localeCompare(String(t.members[0]?.module??``))||V_(e,t)))}function J_(e){let t=new Set,n=new Set,r=new Set,i=t=>e.edges.filter(e=>e.source===t).sort(V_);function a(e){if(!t.has(e)){t.add(e),n.add(e);for(let t of i(e))n.has(t.target)?r.add(t.id):a(t.target);n.delete(e)}}return[...e.layout?.primaryPath??e.nodes.filter(e=>[`initial`,`start`].includes(e.kind)).map(e=>e.id),...[...e.nodes].sort(V_).map(e=>e.id)].forEach(a),e.edges.filter(e=>!r.has(e.id))}function Y_(e,t){let n=t.layout?.primaryPath??[],r=G_(e,J_(t));return r.length===1&&e.length>5?K_(r[0]):r.map(e=>e.sort((e,t)=>{let r=e=>e.members.some(e=>n.includes(e.id));return Number(r(t))-Number(r(e))||V_(e,t)}))}function X_(e,t){let n=[...e].sort((e,n)=>W_(n,t.edges)-W_(e,t.edges)||V_(e,n)),r=[];for(;n.length;){let e=r.length?n.findIndex(e=>t.edges.some(t=>e.ids.has(t.source)&&r.at(-1).ids.has(t.target)||e.ids.has(t.target)&&r.at(-1).ids.has(t.source))):0;r.push(...n.splice(Math.max(0,e),1))}return K_(r)}function Z_(e,t){let n=new Map;for(let t of e){let e=Math.min(...t.members.map(f_));n.set(e,[...n.get(e)??[],t])}return[...n].sort(([e],[t])=>e-t).flatMap(([,e])=>G_(e,t.edges))}function Q_(e,t){let n=t.edges.filter(e=>[`inheritance`,`implementation`].includes(e.kind)).map(e=>({source:e.target,target:e.source})),r=e.filter(e=>n.some(t=>e.ids.has(t.source)||e.ids.has(t.target))),i=e.filter(e=>!r.includes(e)),a=G_(r,n),o=G_(i,t.edges),s=Math.max(-1,...a.map((e,t)=>e.some(e=>U_(e,[`abstract`,`interface`]))?t:-1))+1;return Array.from({length:Math.max(a.length,s+o.length)},(e,t)=>[...a[t]??[],...o[t-s]??[]])}function $_(e,t){let n=e.filter(e=>U_(e,[`initial`])),r=e.filter(e=>U_(e,[`final`]));return[n,...G_(e.filter(e=>!n.includes(e)&&!r.includes(e)),J_(t)),r].filter(e=>e.length)}function ev(e,t,n=0){let r=e.filter(e=>U_(e,[`actor`])),i=e.filter(e=>!r.includes(e));return r.length?[r.sort(V_),i.sort(V_)].filter(e=>e.length):n>=2?i.sort(V_).map(e=>[e]):X_(i,t)}function tv(e,t){let n=e.filter(e=>U_(e,[`dataStore`])),r=e.filter(e=>!n.includes(e)),i=n.flatMap(e=>t.edges.filter(t=>e.ids.has(t.target)).flatMap(n=>t.edges.filter(t=>e.ids.has(t.source)&&t.target!==n.source).map(e=>({source:n.source,target:e.target})))),a=G_(r,[...t.edges,...i]),o=new Map(a.flatMap((e,t)=>e.flatMap(e=>[...e.ids].map(e=>[e,t]))));for(let e of n.sort(V_)){let n=t.edges.filter(t=>e.ids.has(t.source)||e.ids.has(t.target)).map(t=>o.get(e.ids.has(t.source)?t.target:t.source)).filter(e=>e!==void 0).sort((e,t)=>e-t),r=n.length?n[Math.floor(n.length/2)]:Math.max(0,a.length-1);(a[r]??=[]).push(e)}return a}Object.freeze({capabilities:{structure:`capability-bands`,existing:`overview`},engineering:{structure:`engineering-layers`,existing:`overview`},relations:{structure:`component-clusters`,arrange:q_},flowchart:{structure:`workflow-spine`,arrange:Y_},sequence:{structure:`lifelines`,existing:`sequence`},er:{structure:`entity-matrix`,arrange:X_},deployment:{structure:`runtime-tiers`,arrange:Z_},class:{structure:`contract-hierarchy`,arrange:Q_},state:{structure:`lifecycle-branches`,arrange:$_},usecase:{structure:`actor-system`,arrange:ev},dataflow:{structure:`process-store`,arrange:tv}});function nv(e,t){if(eh(e)!==`sequence`)for(let n of e.nodes)for(let r of e.nodes){if(n.id>=r.id||n.groupId!==r.groupId)continue;let e=t.nodes.find(e=>e.id===n.id),i=t.nodes.find(e=>e.id===r.id);for(let[t,a]of[[`x`,`width`],[`y`,`height`]])for(let o of[0,.5]){let s=(e,n)=>e.position[t]+o*e.size[a]-n.position[t]-o*n.size[a];if(Math.abs(s(n,r))<.001&&Math.abs(s(e,i))>.001)return!1}}if(!e.layout?.strategy?.startsWith(`template-`))return!0;let n=hf(e),r=new Map(t.nodes.map(e=>[e.id,e])),i=[`usecase`,`dataflow`].includes(n)?`x`:`y`,a=i===`x`?`width`:`height`;for(let t of e.nodes)for(let o of e.nodes)if(n===`deployment`&&t.id!==o.id&&t.groupId===o.groupId&&t.position.y===o.position.y&&r.get(t.id).position.y!==r.get(o.id).position.y||!(t.id===o.id||t.groupId!==o.groupId&&(n!==`usecase`||t.kind!==`actor`&&o.kind!==`actor`))&&t.position[i]+t.size[a]<=o.position[i]&&r.get(t.id).position[i]+r.get(t.id).size[a]>r.get(o.id).position[i])return!1;return!0}var rv=156,iv=160,av=(e,t,n)=>Math.max(t,Math.min(n,e));function ov(e,t){if(!t)return new Set(e.nodes.map(e=>e.id));let n=new Set([t]);for(let r of e.edges)r.source===t&&n.add(r.target),r.target===t&&n.add(r.source);return n}function sv(e,t){return e.groupId?t.find(t=>t.id===e.groupId):t.filter(t=>e.position.x>=t.position.x&&e.position.y>=t.position.y&&e.position.x+e.size.width<=t.position.x+t.size.width&&e.position.y+e.size.height<=t.position.y+t.size.height).sort((e,t)=>e.size.width*e.size.height-t.size.width*t.size.height)[0]}function cv(e,t,n,r){if(!t)return null;let i=e.size.width/2,a=e.size.height/2,o=e.position.x+i,s=e.position.y+a;return{minimumX:Math.max(t.position.x+r.groupInset+i,o-rv),maximumX:Math.min(t.position.x+t.size.width-r.groupInset-i,o+rv),minimumY:Math.max(t.position.y+Ap(t).height+r.groupHeadingGap+a,s-(n?0:rv)),maximumY:Math.min(t.position.y+t.size.height-r.groupInset-a,s+(n?0:rv))}}function lv(e,t){let n=[],r=()=>{for(let r=0;r{n=e},r}function uv(e,t=null){if(!t)try{return k_(e),{graph:structuredClone(e),movedNodeIds:[]}}catch{}let n=$(e.meta.diagramType),r=n.sequence,i=kf(n),a=ov(e,t),o=e.nodes.map(t=>{let n=t.position.x+t.size.width/2,o=t.position.y+t.size.height/2,s=cv(t,sv(t,e.groups??[]),r,i),c=a.has(t.id)&&(!s||s.minimumX<=s.maximumX&&s.minimumY<=s.maximumY);return{id:t.id,width:t.size.width,height:t.size.height,anchorX:n,anchorY:o,x:n,y:o,vx:0,vy:0,movable:c,bounds:s,fx:c?void 0:n,fy:c?void 0:o}}),s=R_(o).velocityDecay(.42).force(`anchor-x`,z_(e=>e.anchorX).strength(.16)).force(`anchor-y`,B_(e=>e.anchorY).strength(r?1:.16)).force(`rectangles`,lv(r,i.nodeGap+1)).stop();for(let e=0;e[e.id,e])),l=[],u=e.nodes.map(e=>{let t=c.get(e.id);if(!t.movable)return e;let n={x:av(Math.round(t.x-e.size.width/2),Math.max(0,e.position.x-rv),e.position.x+rv),y:r?e.position.y:av(Math.round(t.y-e.size.height/2),Math.max(0,e.position.y-rv),e.position.y+rv)};return t.bounds&&(n.x=av(n.x,t.bounds.minimumX-e.size.width/2,t.bounds.maximumX-e.size.width/2),r||(n.y=av(n.y,t.bounds.minimumY-e.size.height/2,t.bounds.maximumY-e.size.height/2))),(n.x!==e.position.x||n.y!==e.position.y)&&l.push(e.id),{...e,position:n}}),d={...e,nodes:u};try{if(!nv(e,d))throw Error(`Arrange would invert template bands`);k_(d)}catch(t){return{graph:e,movedNodeIds:[],rejected:{message:t.message,diagnostics:t.diagnostics??[]}}}return{graph:d,movedNodeIds:l}}var dv=(e,t,n)=>3*t*e*(1-e)**2+3*n*e*e*(1-e)+e**3;function fv(e){let t=0,n=1;for(let r=0;r<20;r++){let r=(t+n)/2;dv(r,.32,0)e.getBoundingClientRect()).filter(e=>e.width>0&&e.height>0),u=Math.min(i-12-12,...l.map(e=>e.top-c-12));return{left:o,right:s,top:76,bottom:u,width:Math.max(0,s-o),height:Math.max(0,u-76)}}function mv(e,t,n){let r=pv(e,t,n),i=e=>`${e}px`;return{top:i(r.top),right:i(e.clientWidth-r.right),bottom:i(e.clientHeight-r.bottom),left:i(r.left)}}function hv(e,t,n){let r={left:e.x*n.zoom+n.x,right:(e.x+e.width)*n.zoom+n.x,top:e.y*n.zoom+n.y,bottom:(e.y+e.height)*n.zoom+n.y};if(r.left>=t.left&&r.right<=t.right&&r.top>=t.top&&r.bottom<=t.bottom)return n;let i=e.width*n.zoom>t.width?t.left+t.width/2-(r.left+r.right)/2:r.leftt.right?t.right-r.right:0,a=r.topt.height?t.top-r.top:r.bottom>t.bottom?t.bottom-r.bottom:0;return{...n,x:n.x+i,y:n.y+a}}function gv(e,t,n){let r=Math.min(2,Math.max(Af,n.zoom));return{zoom:r,x:t.left+t.width/2-(e.x+e.width/2)*r,y:t.top-e.y*r}}var _v=e=>e.nodes.find(t=>t.id===e.layout?.primaryPath?.[0])??e.nodes.find(e=>[`start`,`initial`].includes(e.kind))??(e.meta?.diagramType===`sequence`||!e.nodes.every(e=>e.position)?void 0:e.nodes.find(Yf)??[...e.nodes].sort((e,t)=>e.position.y-t.position.y||e.position.x-t.position.x)[0]),vv=e=>e.meta?.diagramType===`sequence`?Af:jf;function yv(e,t,n,r=Af,i=jf){if(Math.min(n.width/e.width,n.height/e.height)>=i)return null;let a=(e,t,n,i)=>{let a=i/r;return t<=a?e+(t-a)/2:Math.min(e+t-a,Math.max(e,n-a/2))},o=t?t.position.x+t.size.width/2:e.x,s=t?t.position.y+t.size.height/2:e.y;return{zoom:r,x:n.left-a(e.x,e.width,o,n.width)*r,y:n.top+28-a(e.y,e.height,s,n.height-28)*r}}var bv=/(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/,xv=e=>JSON.stringify(e).replaceAll(`&`,`\\u0026`).replaceAll(`<`,`\\u003c`).replaceAll(`>`,`\\u003e`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function Sv(e,t){if(!bv.test(e))throw Error(`page has no graph-data element`);return e.replace(bv,(e,n,r,i)=>`${n}${xv(t)}${i}`)}function Cv(e,t,n){let r=e=>uf(e)===uf(n)?n:t.get(uf(e))??e;return Array.isArray(e.diagrams)?{...e,diagrams:e.diagrams.map(r)}:n}function wv(e,t,n){let r=new Map(t.filter(e=>e.type===`diagram`).map(e=>[e.id,e])),i=new Map(t.filter(e=>e.type===`boundary`).map(e=>[e.id,e])),a=new Map(n.map(e=>[e.id,e]));return{...e,nodes:e.nodes.map(e=>{let t=r.get(e.id);if(!t)return e;let n={label:t.data.label};for(let e of[`overviewText`,`badges`])Object.hasOwn(t.data,e)&&(n[e]=t.data[e]);return Object.hasOwn(t.data,`subtitle`)&&(n.subtitle=t.data.subtitle),{...e,...n,position:t.position,size:t.data.size}}),...e.groups&&{groups:e.groups.map(e=>{let t=i.get(e.id);return t?{...e,position:t.position,size:t.data.size}:e})},edges:e.edges.map(e=>{let t=a.get(e.id);return t&&Object.hasOwn(t.data,`label`)?{...e,label:t.data.label}:e})}}function Tv(e,t,n){if(n!==`sequence`)return e;let r=new Map(t.map(e=>[e.id,e.position]));return e.map(e=>e.type===`position`&&e.position&&r.has(e.id)?{...e,position:{...e.position,y:r.get(e.id).y}}:e)}function Ev(e,t){let n=e=>t.has(e.id)?{...e,...t.get(e.id)}:e;return{...e,nodes:e.nodes.map(n),...e.groups&&{groups:e.groups.map(n)}}}function Dv(e,t,n){let r=eh(e),i=$(r),a=e.nodes.find(e=>e.id===t),o=Tf(e).nodes.find(e=>e.id===t),s=i.cardLayout?th(o,r,e.meta.locale,n).minHeight-a.size.height:0;if(s<=0)return new Map;let{groupInset:c,groupHeadingGap:l}=kf(i),u=new Map((e.groups??[]).map(e=>[e.id,e])),d=e=>{let n={position:{x:a.position.x,y:Math.max(0,a.position.y-s*e)},size:{width:a.size.width,height:a.size.height+s}},r=new Map([[t,n]]);for(let e=u.get(a.groupId),t=0;e&&t{try{return k_(Ev(e,t)),!0}catch{return!1}},p=[.5,1,0].map(d);return p.find(f)??p[0]}function Ov(e,t,n,r=e){let i=(t,n)=>bf(e.meta.locale,t,n),a=eh(e),[o,s,c]=Ed(t_(e,a)),[l,u]=Dd(n_(e,a)),[d,f]=(0,y.useState)(!0),p=(0,y.useRef)(null),{getViewport:m,setCenter:h,setViewport:g}=vl();(0,y.useEffect)(()=>{if(new URLSearchParams(window.location.search).has(`automation`))return window.__qgraphflowAutomation={getViewport:m,setViewport:g,setCenter:h,ease:fv},()=>{delete window.__qgraphflowAutomation}},[m,g,h]);let[_,v]=(0,y.useState)(e),b=(0,y.useMemo)(()=>wv(_,o,l),[_,o,l]),x=e=>{v(e),s(t_(e,a)),u(n_(e,a))},S=(0,y.useRef)(null),C=(0,y.useRef)(0),[w,T]=(0,y.useState)(!1),E=({superseded:e=!1}={})=>{if(C.current++,!S.current)return;let t=S.current;S.current=null,t.worker.terminate(),T(!1),t.reject(Object.assign(Error(`Cancelled`),{cancelled:!0,superseded:e}))};(0,y.useEffect)(()=>()=>E({superseded:!0}),[]);let D=(e,t={},n=!1)=>new Promise((r,i)=>{E({superseded:!0});let a=new s_,o={worker:a,reject:i};S.current=o,T(!0);let s=(e,t)=>{S.current===o&&(S.current=null,T(!1),a.terminate(),t?i(t):r(e))};a.onmessage=({data:e})=>s(e.result,e.error&&Object.assign(Error(e.error.message),e.error)),a.onerror=e=>s(null,Error(e.message)),t.relayout||(t={...t,edgeIds:[...yg(_,e,t.edgeIds)]}),a.postMessage({graph:e,reference:_,options:t,overview:n})}),O=async(e,t={},n=!1)=>{let r;try{let a=D(e,{move:!1,evaluations:1,passes:2,...t},n);r=C.current;let o=await a;return r===C.current?(x(o.graph),N(null),o):{error:i(`Cancelled`),cancelled:!0,superseded:!0}}catch(t){if(!t.cancelled&&r!==C.current)return{error:i(`Cancelled`),cancelled:!0,superseded:!0};if(t.cancelled)return{error:i(`Cancelled`),cancelled:!0,superseded:t.superseded};let n=t.diagnostics?.length?t:O_(e,`geometry`,t.message);return N({graph:b,message:n.message,diagnostics:n.diagnostics}),{error:n.message}}},k=async(e,t={})=>(await O(e,t,!0)).error,A=async(e,t)=>{if(t.type===`diagram`){if(ff(b))try{let e=await O(b,{},!0);e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}catch(e){x(_),n(e.message)}else{let e=await O(b,{growBoundaries:!0});e.error&&!e.superseded&&(x(_),e.cancelled||n(e.error))}}},j=async e=>{let t={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1}[e.key],r=e.target.closest(`.react-flow__node-diagram`);if(!ff(b)||!t||!r||(e.preventDefault(),e.stopPropagation(),d||e.repeat))return;let i=r.dataset.id,a=_.nodes.find(e=>e.id===i),o=bg(_).find(e=>e.items?.some(e=>e.nodeId===i)),s=o?o.items.filter(e=>e.nodeId).map(e=>_.nodes.find(t=>t.id===e.nodeId)):_.nodes.filter(e=>e.groupId&&e.groupId===a?.groupId),c=s[s.findIndex(e=>e.id===i)+t];if(c){let e=await k(kg(_,i,c.position));e&&n(e)}},[M,N]=(0,y.useState)(null),P=(0,y.useCallback)(e=>c(Tv(e,o,a)),[c,a,o]),ee=(0,y.useMemo)(()=>{try{return k_(b),M?.graph===b?M:null}catch(e){return{message:e.message,diagnostics:e.diagnostics??[]}}},[b,M]),F=(0,y.useMemo)(()=>{try{return k_(b).diagnostics.filter(e=>e.severity===`warning`)}catch{return[]}},[b]),I=async(e,t,n,r={})=>{if(ff(b)){let i=structuredClone(b),a=bg(i).find(t=>t.id===e);return a?(a.title=t,a.text=r.overviewText??a.text):i.nodes=i.nodes.map(i=>i.id===e?{...i,label:t,subtitle:n,...r}:i),k(i)}let i={...b,nodes:b.nodes.map(r=>r.id===e?{...r,label:t,subtitle:n}:r)},o=Ev(i,Dv(i,e,!nh(b))),s=o.nodes.find(t=>t.id===e);if(!s)return;if(!nh(o)||![`architecture`,`deployment`].includes(a)){let e=u_(s,a,o.meta.locale);s.size={width:Math.max(s.size.width,e.width),height:Math.max(s.size.height,e.height)}}let c=await O(o);return c.error&&!c.cancelled&&(c=await O(o,{move:!0,focusId:e,evaluations:12,passes:1})),c.error},te=async(e,t)=>ff(b)?k({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)}):(await O({...b,edges:b.edges.map(n=>n.id===e?{...n,label:t}:n)})).error,ne=(e,n=t?0:320,r=!1)=>{let i=p.current;if(!i)return;let a=Ph(e),o=i.dataset.navOpen===`true`,s=i.dataset.drawerOpen===`true`,c=!r&&yv(a,_v(e),pv(i,o,s),void 0,vv(e))||lo(a,i.clientWidth,i.clientHeight,.08,2,mv(i,o,s));return g(c,{duration:n,ease:fv})};return{layoutPending:w,cancelLayout:E,nodes:o,edges:l,onNodesChange:P,onNodeDragStop:A,onOverviewKeyDown:j,setRenderProblem:N,updateNodeText:I,updateEdgeText:te,locked:d,setLocked:f,canvasRef:p,currentGraph:b,acceptedGraph:_,layoutProblem:ee,layoutWarnings:F,focusProblem:e=>{let n=e.bounds?.[0];n&&h(n.x+n.width/2,n.y+n.height/2,{zoom:1,duration:t?0:320})},readGraph:ne,focusNode:(0,y.useCallback)((e,n={})=>{let r=b.nodes.find(t=>t.id===e)??bg(b).find(t=>t.id===e);if(!r)return;if(a!==`sequence`){h(r.position.x+r.size.width/2,r.position.y+r.size.height/2,{zoom:1.1,duration:t?0:420,ease:fv});return}let i=p.current;if(!i)return;let o=pv(i,n.navOpen??i.dataset.navOpen===`true`,n.drawerOpen??i.dataset.drawerOpen===`true`),s=gv(Zh(r,a),o,m());g(s,{duration:t?0:420,ease:fv})},[b,a,m,t,h,g]),resetLayout:()=>{E({superseded:!0}),v(r),N(null),s(t_(r,a)),u(n_(r,a)),requestAnimationFrame(()=>ne(r))},nudgeLayout:async e=>{if(d){n(`Unlock the layout before arranging nodes`);return}if(ff(b)){await k(b,{relayout:!e})||n(`Overview aligned`);return}let t=uv(b,e),r=t.rejected?b:t.graph,a=await O(r,{move:!0,relayout:!e,focusId:e,evaluations:20,passes:1});if(a.cancelled)return;if(a.error){n(`Cannot arrange further within the current constraints`);return}a.movedNodeIds=a.graph.nodes.filter(e=>{let t=b.nodes.find(t=>t.id===e.id);return t.position.x!==e.position.x||t.position.y!==e.position.y}).map(e=>e.id);let o=a.movedNodeIds.length,s=i(e?`Local`:`Full diagram`);n(o?i(`{scope} arranged: {count} nodes moved`,{scope:s,count:o}):i(`No spacing changes needed`))},focusDiagram:()=>ne(b,t?0:320,!0)}}function kv(e,t){let n=t.trim().toLowerCase();if(!n)return 0;let r=e.label.trim().toLowerCase();if(r===n)return 5;if(r.startsWith(n))return 4;if(r.includes(n))return 3;let i=e=>e.some(e=>String(e??``).toLowerCase().includes(n));return i([e.subtitle,...e.tags??[]])?2:+!!i([...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...e.facts??[],...e.attributes??[],...e.methods??[],...(e.fields??[]).flatMap(e=>[e.key,e.name,e.type])])}function Av(e,t){return e.map(e=>({node:e,rank:kv(e,t)})).filter(e=>e.rank>0).sort((e,t)=>t.rank-e.rank).slice(0,8).map(e=>e.node)}function jv(e,{focusNode:t,panels:n,isFullscreen:r=!1,toggleFullscreen:i}){let[a,o]=(0,y.useState)(()=>e.nodes.find(Yf)?.id??null),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(0),[d,f]=(0,y.useState)(``),p=d.trim().toLowerCase(),m=(0,y.useMemo)(()=>[...e.nodes,...bg(e).map(e=>({...e,label:e.title,kind:`annotation`,section:!0,overviewText:e.text??[]}))],[e]),h=(0,y.useMemo)(()=>p?Av(m,p):e.nodes,[e,m,p]),g=m.find(e=>e.id===a),_=e.edges.find(e=>e.id===s),{toolbarOpen:v,drawerOpen:b,openDetails:x,closeDetails:S,closeNav:C}=n,w=(0,y.useCallback)((e,n=!0)=>{o(e.id),c(null),u(e=>e+1),f(``),n&&(!r&&!b&&x(),t(e.id,{navOpen:v,drawerOpen:!r||b}))},[b,x,t,r,v]),T=(0,y.useCallback)((e,t=!1)=>{o(null),c(e.id),u(e=>e+1),f(``),t&&!r&&!b&&x()},[b,r,x]),E=(0,y.useCallback)((e=!1)=>{o(null),c(null),S(e)},[S]);return(0,y.useEffect)(()=>{let e=e=>{if(e.key!==`Escape`)return;if(r){e.preventDefault(),document.fullscreenElement&&i();return}let t=document.activeElement;if(t?.closest(`.nav`)){C(!0);return}if(t?.closest(`.inspector`)){S(!0);return}E(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,S,C,r,i]),{selectedId:a,selectedEdgeId:s,selectionPulse:l,selected:g,selectedEdge:_,query:d,setQuery:f,normalizedQuery:p,results:h,selectNode:w,selectEdge:T,clearSelectedNode:E,handleCanvasKeyDown:t=>{if(![`Enter`,` `].includes(t.key))return;let n=t.target.closest(`.react-flow__edge`);if(n){if(t.preventDefault(),t.stopPropagation(),t.repeat)return;let r=e.edges.find(e=>e.id===n.dataset.id);r&&T(r);return}let r=t.target.closest(`.react-flow__node-diagram,.react-flow__node-overview`);if(!r||(t.preventDefault(),t.stopPropagation(),t.repeat))return;let i=m.find(e=>e.id===r.dataset.id);i&&w(i)},resetSelection:()=>{o(null),c(null),u(0),f(``)}}}function Mv(e,t,n,r,i,a){let o=eh(e),{nodes:s,edges:c,locked:l,currentGraph:u}=t,{selectedId:d,selectedEdgeId:f,selectEdge:p,selectNode:m,selectionPulse:h,normalizedQuery:g}=n,_=(0,y.useMemo)(()=>Yh(u),[u]),v=(0,y.useMemo)(()=>Ch(u),[u]),b=(0,y.useMemo)(()=>kh(u),[u]),x=(0,y.useMemo)(()=>np(u.groups??[],i),[u,i]);return{visibleNodes:(0,y.useMemo)(()=>s.map(t=>t.type===`overview`?{...t,draggable:!1,data:{...t.data,palette:i,onSelect:()=>m({...t.data,label:t.data.title,kind:`annotation`,section:!0,overviewText:t.data.text??[]})}}:t.type===`boundary`?{...t,data:{...t.data,appearance:x.get(t.id),fragment:o===`sequence`?xh(t.data,_,e.meta.locale,u.groups??[],b):null}}:{...t,selected:t.id===d,draggable:!l,data:{...t.data,executionRects:b.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(v.get(e.start.edgeId),i)??i.edge})),selectionPulse:h,palette:i,moduleColors:a,dimmed:!!g&&kv(t.data,g)===0}}),[m,l,s,g,d,h,i,a,_,o,e.meta.locale,u,b,v,x]),visibleEdges:(0,y.useMemo)(()=>{let e=$(o).sequence;return c.map(t=>{let n=_.get(t.id),s=t.data.kind===`failure`,c=t.id===f||t.source===d||t.target===d,l=v.get(t.id),m=ih(t.data,o),g=u.nodes.find(e=>e.id===t.target),y=u.nodes.find(e=>e.id===t.source),b=op(t.data,g,i,a,y,l),S=l?b:s?i.warn:i.accent;return{...t,sourceHandle:$(o).sequence?`source-right`:`source-${_.get(t.id).sourceSide}`,targetHandle:$(o).sequence?`target-left`:`target-${_.get(t.id).targetSide}`,className:[e?`flow-edge--sequence`:``,m?`flow-edge--dashed`:``].filter(Boolean).join(` `),style:{stroke:b,strokeWidth:1.6},ariaLabel:n.label||`${y.label} → ${g.label}`,markerEnd:t.markerEnd?{type:Da.ArrowClosed,color:b}:void 0,selected:t.id===f,data:{...t.data,pair:l,selectionLinked:c,selectionId:f??d,selectionPulse:h,selectionColor:S,route:n,relationColor:i.accent,directed:!!t.markerEnd,flowRunning:r,dashed:m,labelColor:i.ink3,roleColors:ah(o,i),labelSurface:e&&n.label?_h(n.labelBox,u.groups??[],x):void 0,onSelect:()=>p(t.data)}}})},[o,c,e,u,i,a,r,p,f,d,h,_,v,x])}}function Nv(e,t){let n=(0,y.useRef)(null),r=(0,y.useRef)(null),i=(0,y.useRef)(!1),a=(0,y.useRef)(!1),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=(0,y.useEffectEvent)(t),d=!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen&&document.exitFullscreen),f=(0,y.useCallback)(async()=>{let t=n.current;if(!t||a.current)return;let r=document.fullscreenElement===t;if(!r&&!d){e(`Fullscreen is not available in this browser or page`);return}a.current=!0,l(!0),e(``);try{return r?await document.exitFullscreen():await t.requestFullscreen(),!0}catch{t.isConnected&&e(r?`Could not exit fullscreen. Press Esc to try again.`:`Could not enter fullscreen. Check browser or page permissions and try again.`)}finally{a.current=!1,t.isConnected&&l(!1)}},[d,e]);return(0,y.useEffect)(()=>{let e,t=()=>{let t=!!(n.current&&document.fullscreenElement===n.current),a=!i.current&&t,o=i.current&&!t;i.current=t,s(t),a&&(e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{i.current&&u()})})),o&&(cancelAnimationFrame(e),r.current?.focus({preventScroll:!0}))};return document.addEventListener(`fullscreenchange`,t),t(),()=>{document.removeEventListener(`fullscreenchange`,t),cancelAnimationFrame(e)}},[]),{boardRef:n,fullscreenButtonRef:r,isFullscreen:o,fullscreenPending:c,fullscreenSupported:d,toggleFullscreen:f}}function Pv(e,t,n,r,i,a){let{end:o}=oh(e,t);return o?o===`arrow`?` marker-end="url(#${a?`arrow-module`:e.kind===`failure`?`arrow-warn`:e.kind===`success`?`arrow-ok`:r?.has(e.module??i?.module??n?.module)?`arrow-module`:Jf.has(n?.kind)?`arrow-data`:`arrow`})"`:` marker-end="url(#${o})"`:``}function Fv(e,t){let{start:n}=oh(e,t);return n?` marker-start="url(#${n})"`:``}function Iv(e,t,n,r,i){let a=e.position.x+t,o=e.position.y+n,s=Pp(e.label,r?.heading?.width??e.size.width-([`alt`,`opt`,`loop`,`par`].includes(e.kind)?88:32));return`${Np(e.label)}${Mp(e,i,a,o)}${r?(r.heading?.lines??[s]).map((e,n)=>Q(r.heading?r.heading.x+t:a+16,o+23+n*22,e,`group`)).join(``):jp(e,a,o)}${[`alt`,`opt`,`loop`,`par`].includes(e.kind)?Q(a+e.size.width-16,o+25,e.kind,`group-kind`,` text-anchor="end"`):``}`}function Lv(e,t,n,r,i,a,o,s,c,l,u){let d=op(e,o,a,s,c,l),f=ih(e,n)?` stroke-dasharray="7 6"`:``,p=t.label,m=t.labelPoint.x+r,h=t.labelPoint.y+i,g=t.labelBox,_=l?``:``,v=p?``:``,y=$(n).cardinalities?[Nh(e.sourceCardinality,t.points[0],t.points[1]),Nh(e.targetCardinality,t.points.at(-1),t.points.at(-2))].map((e,t)=>`${e.circle?``:``}`).join(``):``,b=(t.endpointLabels??[]).map(e=>`${Q(e.labelPoint.x+r,e.labelBox.y+i+3+X.body,e.label,`edge`,` text-anchor="middle"`)}`).join(``);return`${y}${v}${_}${p?t.labelLines.map((e,r)=>Q(m,h-g.height/2+3+X.body+r*X.edgeLineHeight,t.labelRuns?{runs:t.labelRuns[r],colors:ah(n,a)}:e,`edge`,` text-anchor="middle"`)).join(``):``}${b}`}var Rv={indent:20,line:24,gap:6,top:12,afterHeading:14,bottom:18};function zv(e,t,n,r,i){let a=e.map(e=>Z(e,i-Rv.indent,X.body,Rv.line)),o=r+Rv.top+Rv.afterHeading,s=a.map(({lines:e})=>{let t=o+17,r=Q(n,t,`•`,`body`)+e.map((e,r)=>Q(n+Rv.indent,t+r*Rv.line,e,`body`)).join(``);return o+=e.length*Rv.line+Rv.gap,r}).join(``);return{height:o-r+Rv.bottom,svg:`${Q(n,r+Rv.top,bf(t,`Key points`),`group`)}${s}`}}function Bv(e,t=`light`,n){k_(e),e=Tf(e);let r=Kf[t]??Kf.light;n??=$f([e],r);let i=np(e.groups??[],r),a=eh(e),o=Yh(e),s=Ch(e),c=kh(e),l=new Map(e.nodes.map(e=>[e.id,e])),u=Ph(e,o),d=u.width+128,f=Z(e.meta.title,d-128,24),p=Z(e.meta.subtitle??``,d-128,X.small),m=66+Math.max(0,f.lines.length-1)*f.lineHeight,h=Math.max(88,p.lines.length?m+(p.lines.length-1)*p.lineHeight+22:43+Math.max(0,f.lines.length-1)*f.lineHeight+24),g=u.height+128+h,_=e.meta.notes?.length?zv(e.meta.notes,e.meta.locale,64,g,d-128):{height:0,svg:``},v=g+_.height,y=64-u.x,b=64+h-u.y,x=new Map((e.groups??[]).map(t=>[t.id,a===`sequence`?xh(t,o,e.meta.locale,e.groups??[],c):null])),S=[...e.groups??[]].sort((t,n)=>gh(t,e.groups??[])-gh(n,e.groups??[])).map(e=>Iv(e,y,b,x.get(e.id),i.get(e.id))+(a===`sequence`?Sh({...x.get(e.id),guards:[],bodies:[]},e,y,b,r.ink3,i.get(e.id).fill):``)).join(``),C=bg(e).map(e=>Ng(e,r,y,b)).join(``),w=a===`sequence`?(e.groups??[]).map(e=>Sh({...x.get(e.id),separators:[]},e,y,b,r.ink3,i.get(e.id).fill)).join(``):``,T=e.edges.map(t=>Lv(t,o.get(t.id),a,y,b,r,l.get(t.target),n,l.get(t.source),s.get(t.id),a===`sequence`&&o.get(t.id).label?_h(o.get(t.id).labelBox,e.groups??[],i):void 0)).join(``),E=!nh(e),D=e.nodes.map(t=>Fg({...t,classicCard:E,executionRects:c.filter(e=>e.participantId===t.id).map(e=>({...e,x:e.x-t.position.x,y:e.y-t.position.y,color:ap(s.get(e.start.edgeId),r)??r.edge}))},a,y,b,r,e.meta.locale,n)).join(``),O=h,k=d-48,A=g-h-24;return`\n\x3C!-- Radix Colors\n${Rf}-->\n${Np(e.meta.title)}${Np(a)} diagram for ${Np(e.meta.sourceRef)}${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${C}${S}${a===`sequence`?D+T:T+D}${w}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Qm.join(`|`)}))?\\.svg$`);function Vv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=$f(n,Kf.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${eh(e)}.svg`:`diagram.svg`,svg:Bv(e,`light`,r)}))}function Hv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function Uv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function Wv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>bf(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=Sv(await(await s.getFile()).text(),e),l;try{l=Vv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(Uv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Gv(e,t){t=Tf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw O_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id],[data-overview-section-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId??c.dataset.overviewSectionId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...e.overviewText??[],...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)};for(let e of bg(t))n=[e.id],_([...[...o.querySelectorAll(`[data-overview-section-id]`)].find(t=>t.dataset.overviewSectionId===e.id)?.querySelectorAll(`:scope > text`)??[]],[e.title,...e.text??[]].join(``),m({...e.position,...e.size}),e.id,`section`);let v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=kh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?xh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:Ap(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Nh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(oh(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Zh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw O_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:eh(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Kv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));Uv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function qv(e,t,n,r,i){e=structuredClone(e),i&&=ep(i);let a=(t,n)=>bf(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=Bv(e,t,i),s=`${Hv(e.meta.title)}.${n}`;await Gv(o,e),n===`svg`?Uv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Kv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Jv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Kf[t],p=Ov(e,s,d,i),[m,h]=o,g=m&&!s,_=Nv(d,()=>p.readGraph(p.currentGraph,0)),v=jv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=Mv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await qv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>Wv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:eh(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:wf(e).some(t=>rh(t,eh(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Yv(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Xv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Yh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Zh(d,r):f?.labelBox;if(!p)return;let m=hv(p,pv(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:fv});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:fv})},[e,r,n,t,i,a,o])}var Zv={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function Qv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Zv[e]})}function $v(e,t,n,r,i,a=!1,o=()=>{}){let s=t??e,c=s?`${t?`edge`:`node`}:${s.id}`:null,l=!!(e&&(a||e.section||e.overviewText!==void 0)),u=(0,y.useRef)(0),[d,f]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,overviewText:``,badges:[],error:``}),p=(t=!1)=>f({editing:!1,pending:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` `),badges:structuredClone(e?.badges??[]),error:``,returnFocus:t});(0,y.useEffect)(()=>{u.current++,o(),p()},[c]);let m=e=>f(t=>({...t,...e}));return{...d,section:!!e?.section,overview:l,set:m,cancel:()=>{u.current++,o(),p(!0)},begin:()=>m({editing:!0,returnFocus:!1,label:s?.label??``,subtitle:e?.subtitle??``,overviewText:(e?.overviewText??[]).join(` -`),badges:structuredClone(e?.badges??[]),error:``}),save:async a=>{if(a.preventDefault(),d.pending)return;let o=d.label.trim();if(!o){m({error:bf(i,`Name is required`)});return}if(d.badges.some(e=>!e.label.trim())){m({error:bf(i,`Name is required`)});return}let s=++u.current;m({pending:!0});let c=await(t?r(t.id,o):n(e.id,o,d.subtitle.trim(),l?{overviewText:d.overviewText.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),...e.section?{}:{badges:d.badges}}:{}));if(u.current===s){if(m({pending:!1}),c){m({error:c});return}m({editing:!1,error:``})}}}}function Jv({editor:e,relation:t,locked:n,locale:r}){let i=e=>bf(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&!e.section&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),!t&&e.overview&&(0,x.jsxs)(`label`,{children:[i(`Overview text`),(0,x.jsx)(`textarea`,{disabled:e.pending,"aria-label":i(`Overview text`),value:e.overviewText,onChange:t=>e.set({overviewText:t.target.value,error:``})})]}),!t&&e.overview&&!e.section&&(0,x.jsxs)(`fieldset`,{disabled:e.pending,children:[(0,x.jsx)(`legend`,{children:i(`Badges`)}),e.badges.map((t,n)=>{let r=t=>e.set({badges:e.badges.map((e,r)=>r===n?{...e,...t}:e)});return(0,x.jsxs)(`div`,{className:`badge-editor`,children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{"aria-label":`${i(`Badges`)} ${n+1}`,value:t.label,onChange:e=>{let{source:n,...i}=t;r({...i,source:void 0,label:e.target.value,evidence:`document`})}})]}),(0,x.jsxs)(`label`,{children:[i(`Badge type`),(0,x.jsx)(`select`,{value:t.role,onChange:e=>r({role:e.target.value}),children:[`status`,`version`,`requirement`].map(e=>(0,x.jsx)(`option`,{value:e,children:i({status:`Status`,version:`Version`,requirement:`Requirement`}[e])},e))})]}),(0,x.jsxs)(`label`,{children:[i(`Evidence`),(0,x.jsx)(`select`,{value:t.evidence,onChange:e=>r({evidence:e.target.value}),children:[`source`,`code`,`config`,`schema`,`test`,`document`,`framework`,`inference`].map(e=>(0,x.jsx)(`option`,{value:e,children:i(cp[e]??e)},e))})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:e.badges.filter((e,t)=>t!==n)}),children:i(`Remove badge`)})]},n)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>e.set({badges:[...e.badges,{label:``,role:`status`,evidence:`document`}]}),children:i(`Add badge`)})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var Yv=292,Xv=232,Zv=14;function Qv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>bf(c,e,t),_=!!t,v=_?(Yh(d).get(t.id)?.label??Mh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(Xv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??Xv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Zh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=sv(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Zv,y:N.top},{side:`left`,x:N.left-Zv-Yv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Zv},{side:`above`,x:N.left,y:N.top-Zv-C}],F=e=>e.x>=P.left&&e.x+Yv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Zh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Yh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...dh(e)]),n=kh(d);for(let r of d.groups??[]){let i=xh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+Yv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-Yv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?lp(e.source):_&&t.site?lp(t.site):null,ae=_?op(t,r,o,s,n,Ch(d).get(t.id)):ip(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:Yv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(Kv,{name:`close`})}),u.editing?(0,x.jsx)(Jv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(up[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(cp[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(Kv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(Jv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(Kv,{name:`arrowRight`})]})]})]})]})}var $v=[`system`,`light`,`dark`],ey={system:`Follow system`,light:`Light`,dark:`Dark`};function ty(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function ny({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>bf(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,onOverviewKeyDown:ie,layoutPending:ae,cancelLayout:oe,updateNodeText:se,updateEdgeText:ce,readGraph:le,focusDiagram:ue,nudgeLayout:de,visibleNodes:fe,visibleEdges:pe,reset:me,exportDiagram:he,saveGraph:ge,exportStatus:_e,layoutProblem:ve,layoutWarnings:ye,focusProblem:be,boardRef:xe,fullscreenButtonRef:Se,isFullscreen:Ce,fullscreenPending:we,fullscreenSupported:Te,toggleFullscreen:Ee,toolbarOpen:De,drawerOpen:Oe,toolbarButtonRef:ke,drawerButtonRef:Ae,searchInputRef:je,inspectorRef:Me,panelRef:Ne,toggleToolbar:Pe,toggleDrawer:Fe,openDetails:Ie}=Hv(e,c,d,i,t,n,f),[Le,Re]=ty(De,v,Ne),[ze,Be]=ty(Oe,v,Me),Ve=(0,y.useRef)(null),He=qv(w,T,se,ce,e.meta.locale,ff(e),oe),{open:Ue,toggle:We,close:Ge}=Uv(),Ke=e.meta.notes??[],qe=zg(e),Je=Ke.length?{title:h(`Key points`),count:Ke.length,hide:h(`Hide key points`),show:h(`Show key points`)}:{title:h(`Source changes`),count:qe.length,hide:h(`Hide source changes`),show:h(`Show source changes`)},[Ye,Xe]=(0,y.useState)(!0),Ze=Je.count>0&&Ye&&!ze,Qe=Oe||Ze&&!Ce,$e=(0,y.useRef)(!1),et=(0,y.useRef)(null);(0,y.useEffect)(()=>{$e.current&&et.current?.focus({preventScroll:!0})},[Ye]);let tt=Wv(ne,z,L,g,v),[nt,rt]=(0,y.useState)(!1),[it,at]=(0,y.useState)(``),[ot,st]=(0,y.useState)(0);(0,y.useEffect)(()=>{(Oe||O===0)&&st(O)},[Oe,O]);let ct=(0,y.useMemo)(()=>{let e=new Map(fe.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:Mp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=Lg(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,fe]);(0,y.useEffect)(()=>{if(!_e)return;at(h(_e.message));let e=window.setTimeout(()=>at(``),4500);return()=>window.clearTimeout(e)},[_e]);let lt=O>0&&!Oe&&(g!==`sequence`||O!==ot)&&!z.some(e=>e.dragging),ut=lt?z.find(e=>e.id===E&&e.type===`diagram`):null,dt=lt?pe.find(e=>e.id===D):null,ft=dt?L.edges.find(e=>e.id===dt.id):null,pt=dt?{position:dt.data.route.labelPoint,size:{width:0,height:0}}:null,mt=ft?L.nodes.find(e=>e.id===ft.source):null,ht=ft?L.nodes.find(e=>e.id===ft.target):null,gt=T?L.nodes.find(e=>e.id===T.source):null,_t=T?L.nodes.find(e=>e.id===T.target):null,vt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id),yt=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(Kv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ip(w,_,i).stroke}}),h(w.section?`Section`:up[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.overviewText?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Overview text`)}),(0,x.jsx)(`ul`,{children:w.overviewText.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))})]}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(cp[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.source)})]},t))})]}),(e=>e.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Shared dependencies`)}),(0,x.jsx)(`ul`,{children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>P(e),children:[e.label??e.kind,` → `,L.nodes.find(t=>t.id===e.target)?.label]}),e.site&&(0,x.jsx)(`code`,{className:`source-path`,children:lp(e.site)})]},e.id))})]}))(Cf(L).filter(e=>e.source===w.id)),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(cp[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:lp(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:pe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Yh(L).get(T.id)?.label??Mh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[gt?.label,` → `,_t?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(cp[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:lp(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(Kv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:He.editing?``:`card-actions`,children:(0,x.jsx)(Jv,{editor:He,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return Oe&&(Ve.current=yt),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||tt(E,D,!0,Qe)},"aria-controls":`graph-tools`,"aria-expanded":De,"aria-pressed":De,"aria-label":h(De?`Hide graph navigation`:`Show graph navigation`),title:h(De?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(Kv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(gf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>rt(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||rt(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(Kv,{name:`search`}),(0,x.jsx)(`input`,{ref:je,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),nt&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(up[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>We(`views`),"aria-haspopup":`menu`,"aria-expanded":Ue===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(Kv,{name:`views`}),(0,x.jsx)(`span`,{children:h(gf(e))}),(0,x.jsx)(Kv,{name:`chevron`})]}),Ue===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{eh(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(Kv,{name:`check`}):null}),`${h(gf(t))}${r.filter(e=>hf(e)===hf(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(Kv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>We(`more`),"aria-haspopup":`menu`,"aria-expanded":Ue===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(Kv,{name:`more`})}),Ue===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`svg`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{he(`png`),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ae,onClick:()=>{ge(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{me(),Ge()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{de(),Ge()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(Kv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":$v.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${$v.indexOf(l)*100}%)`}}),$v.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(ey[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:Ae,onClick:()=>{Fe(),Oe||tt(E,D,De,!0)},"aria-controls":`node-inspector`,"aria-expanded":Oe,"aria-pressed":Oe,title:h(Oe?`Hide details`:`Show details`),"aria-label":h(Oe?`Hide details`:`Show details`),children:(0,x.jsx)(Kv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${De?`nav-open`:``} ${Oe?`drawer-open`:``}`,children:[Le&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Ne,tabIndex:-1,className:`sidebar nav${Re}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Pe,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(Kv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(vt)})]}),(0,x.jsxs)(`figure`,{ref:xe,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:Yp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ae,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":De,"data-drawer-open":Qe,onKeyDownCapture:e=>{ie(e),e.defaultPrevented||F(e)},"aria-label":h(`Interactive {type}`,{type:h(gf(e))}),children:[(0,x.jsxs)(Sd,{nodes:fe,edges:pe,nodeTypes:qg,edgeTypes:Jg,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),Ge()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>le(L,0)),nodesDraggable:!I&&!ae,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:ue,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(Kv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:Se,onClick:Ee,"aria-pressed":Ce,"aria-busy":we,"aria-disabled":we||!Te&&!Ce,"aria-label":h(Ce?`Exit fullscreen`:`Enter fullscreen`),title:h(!Te&&!Ce?`Fullscreen is not available in this browser or page`:Ce?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(Kv,{name:Ce?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ct,nodeStrokeColor:e=>e.type===`boundary`?`none`:ip(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:ip(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>We(`legend`),"aria-expanded":Ue===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(Kv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),Ue===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:Qg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:Zg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Je.count>0&&!ze&&(Ze?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":Je.title,children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[Je.title,` · `,Je.count]}),(0,x.jsx)(`button`,{className:`side-close`,ref:et,onClick:()=>{$e.current=!0,Xe(!1)},"aria-label":Je.hide,title:Je.hide,children:(0,x.jsx)(Kv,{name:`close`})})]}),Ke.length>0&&(0,x.jsx)(`ul`,{children:Ke.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))}),qe.length>0&&(0,x.jsxs)(x.Fragment,{children:[Ke.length>0&&(0,x.jsxs)(`p`,{className:`panel-title source-changes-title`,children:[h(`Source changes`),` · `,qe.length]}),(0,x.jsx)(`ul`,{className:`source-changes`,children:qe.map((e,t)=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`code`,{children:[String(e?.file??``).split(`/`).pop(),`:`,e?.line]}),` `,e?.change,(e?.elements??[]).map(e=>{let t=L.nodes.find(t=>t.id===e),n=t?null:L.edges.find(t=>t.id===e);return t||n?(0,x.jsx)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>t?N(t):P(n,!0),children:t?t.label:n.label??e},e):null}),(e?.removed?.length>0||e?.added?.length>0)&&(0,x.jsx)(`pre`,{children:[...(e.removed??[]).slice(0,3).map(e=>`- ${e}`),...(e.added??[]).slice(0,3).map(e=>`+ ${e}`)].join(` -`)})]},t))})]})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:et,"aria-expanded":`false`,onClick:()=>{$e.current=!0,Xe(!0),Ce||tt(E,D,De,!0)},"aria-label":Je.show,title:Je.show,children:[(0,x.jsx)(Kv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[Je.title,` · `,Je.count]})]})),ut&&(0,x.jsx)(Qv,{node:{...ut.data,position:ut.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),tt(E,D,De,!0))},onClose:()=>ee()}),ft&&(0,x.jsx)(Qv,{node:pt,edge:{...ft,diagramType:g},source:mt,target:ht,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:He,graph:L,isFullscreen:Ce,onDetails:async()=>{Ce&&!await Ee()||(Ie(),tt(E,D,De,!0))},onClose:()=>ee()}),!ve&&ye.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ye.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>be(ye.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),ve&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:ve.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>be(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:ve.message})]}),(0,x.jsx)(`div`,{className:`toast ${it?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:it})]})]}),ze&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:Me,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${Be}`,"aria-label":h(`Details`),children:Ve.current})]})]})}function ry(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var iy=JSON.parse(document.querySelector(`#graph-data`).textContent),ay=[...Array.isArray(iy.diagrams)?iy.diagrams:[iy]].sort(_f),oy=window.matchMedia(`(prefers-color-scheme: dark)`);function sy(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(oy.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return oy.addEventListener(`change`,e),()=>oy.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function cy(){let[e,t]=(0,y.useState)(uf(ay[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=sy(),s=ry(),c=ay.find(t=>uf(t)===e)??ay[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>_v(iy,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=$f(ay,Kf[o]);return f?e:tp(e,Kf[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(sp(Kf[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)(ny,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:ay,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(cy,{})); - diff --git a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx index a58f944..6f47071 100644 --- a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx +++ b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx @@ -10,6 +10,7 @@ import { renderFragment, fragmentDepth } from './sequence-fragments.js'; import { isCore, TYPOGRAPHY } from './visual-style.js'; import { groupHeadingSvg, groupFrameSvg } from './diagrams/drawing.js'; import { driftedElements } from './source-changes.js'; +import { comparisonOf } from './graph-diff.js'; function NodeHandles({ sequence = false }) { if (sequence) return <> @@ -31,7 +32,7 @@ function NodeHandles({ sequence = false }) { function DiagramNode({ data, selected }) { const moduleColor = data.moduleColors?.get(data.module); const markup = renderNode({ ...data, position: { x: 0, y: 0 } }, data.diagramType, 0, 0, data.palette, data.locale, data.moduleColors); - return
+ return
{selected && } @@ -80,7 +81,7 @@ function RoutedEdge({ id, markerEnd, style, data }) { {label.label} )} - {route.label && } + {route.label && } ; } @@ -90,6 +91,12 @@ function OverviewSection({ data }) { export const nodeTypes = { diagram: DiagramNode, boundary: BoundaryNode, overview: OverviewSection }; export const edgeTypes = { routed: RoutedEdge }; +// generate-viewer --compare: 'added' or 'changed' for an element of this view, else undefined. +function diffOf(graph) { + const compared = comparisonOf(graph); + return id => compared?.added.includes(id) ? 'added' : compared?.changed.includes(id) ? 'changed' : undefined; +} + export function initialNodes(graph, diagramType) { const boundaries = [...(graph.groups ?? [])].sort((a, b) => fragmentDepth(a, graph.groups ?? []) - fragmentDepth(b, graph.groups ?? [])).map(group => ({ id: group.id, @@ -102,20 +109,20 @@ export function initialNodes(graph, diagramType) { connectable: false, zIndex: -(graph.groups?.length ?? 0) + fragmentDepth(group, graph.groups ?? []) })); - const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])), drifted = driftedElements(graph); + const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])), drifted = driftedElements(graph), diff = diffOf(graph); return [...overviewSections(graph).map((section, index) => ({ id: section.id, type: 'overview', position: section.position, data: { ...section }, style: { width: section.size.width, height: section.size.height, pointerEvents: 'none' }, draggable: false, selectable: false, zIndex: -100 + index })), ...boundaries, ...graph.nodes.map(node => ({ id: node.id, type: 'diagram', className: diagramType === 'sequence' ? 'sequence-column' : undefined, position: node.position, - data: { ...drawn.get(node.id), diagramType, locale: graph.meta.locale, classicCard, drifted: drifted.has(node.id) }, + data: { ...drawn.get(node.id), diagramType, locale: graph.meta.locale, classicCard, drifted: drifted.has(node.id), diff: diff(node.id) }, style: { width: node.size.width, height: node.size.height, ...(diagramType === 'sequence' ? { pointerEvents: 'none' } : {}) }, zIndex: 2 }))]; } export function initialEdges(graph, diagramType) { - const drifted = driftedElements(graph); + const drifted = driftedElements(graph), diff = diffOf(graph); return visibleEdges(graph).map(edge => ({ id: edge.id, source: edge.source, @@ -123,6 +130,6 @@ export function initialEdges(graph, diagramType) { type: 'routed', zIndex: diagramType === 'sequence' ? 3 : 0, markerEnd: hasArrow(edge, diagramType) ? { type: MarkerType.ArrowClosed } : undefined, - data: { ...edge, diagramType, drifted: drifted.has(edge.id) } + data: { ...edge, diagramType, drifted: drifted.has(edge.id), diff: diff(edge.id) } })); } diff --git a/skills/q-flow/assets/viewer/src/ViewerShell.jsx b/skills/q-flow/assets/viewer/src/ViewerShell.jsx index 8a6976d..fc456dc 100644 --- a/skills/q-flow/assets/viewer/src/ViewerShell.jsx +++ b/skills/q-flow/assets/viewer/src/ViewerShell.jsx @@ -10,6 +10,7 @@ import { svgStyles, groupFrameSvg } from './diagrams/drawing.js'; import { anchorText, evidenceLabels, kindLabels, nodeAppearance } from './visual-style.js'; import { foldedEdges } from './presentation-graph.js'; import { sourceChanges } from './source-changes.js'; +import { comparisonOf, elementName, updateCount } from './graph-diff.js'; import { graphLegend, rampGradient } from './legend.js'; import { useViewerController } from './features/useViewerController.js'; import { usePopover } from './features/usePopover.js'; @@ -59,10 +60,17 @@ export default function ViewerShell({ graph, originalGraph, graphForSave, allDia // everything but name: while it shows, the reading area gives up the right edge exactly as it does for the details drawer, // and it waits for that drawer (even while it slides out) to be gone before it appears. Fullscreen has no panels, so // there it simply floats over the canvas until it is hidden. - // Unresolved source changes (meta.sourceDrift) share the card: they follow the key points, or stand alone. - const notes = graph.meta.notes ?? [], changes = sourceChanges(graph); + // Unresolved source changes (meta.sourceDrift) and what generate --compare found changed share the card: they follow + // the key points, or the first of them stands alone. + const notes = graph.meta.notes ?? [], changes = sourceChanges(graph), update = comparisonOf(graph), updates = updateCount(update); const side = notes.length ? { title: t('Key points'), count: notes.length, hide: t('Hide key points'), show: t('Show key points') } - : { title: t('Source changes'), count: changes.length, hide: t('Hide source changes'), show: t('Show source changes') }; + : changes.length ? { title: t('Source changes'), count: changes.length, hide: t('Hide source changes'), show: t('Show source changes') } + : { title: t('This update'), count: updates, hide: t('Hide this update'), show: t('Show this update') }; + const elementButton = id => { + const node = currentGraph.nodes.find(entry => entry.id === id), edge = node ? null : currentGraph.edges.find(entry => entry.id === id); + return node || edge ? + : {currentGraph.groups?.find(group => group.id === id)?.label ?? id}; + }; const [notesOpen, setNotesOpen] = useState(true); const notesShown = side.count > 0 && notesOpen && !drawerShown; const rightReserved = drawerOpen || (notesShown && !isFullscreen); @@ -246,12 +254,15 @@ export default function ViewerShell({ graph, originalGraph, graphForSave, allDia {notes.length > 0 &&
    {notes.map((note, index) =>
  • {note}
  • )}
} {changes.length > 0 && <>{notes.length > 0 &&

{t('Source changes')} · {changes.length}

}
    {changes.map((item, index) =>
  • {String(item?.file ?? '').split('/').pop()}:{item?.line} {item?.change} - {(item?.elements ?? []).map(id => { - const node = currentGraph.nodes.find(entry => entry.id === id), edge = node ? null : currentGraph.edges.find(entry => entry.id === id); - return node || edge ? : null; - })} + {(item?.elements ?? []).map(elementButton)} {(item?.removed?.length > 0 || item?.added?.length > 0) &&
    {[...(item.removed ?? []).slice(0, 3).map(line => `- ${line}`), ...(item.added ?? []).slice(0, 3).map(line => `+ ${line}`)].join('\n')}
    }
  • )}
} + {updates > 0 && <>{(notes.length > 0 || changes.length > 0) &&

{t('This update')} · {updates}

}
    + {update.added.length > 0 &&
  • {t('Added')} · {update.added.length}{update.added.map(elementButton)}
  • } + {update.changed.length > 0 &&
  • {t('Changed')} · {update.changed.length}{update.changed.map(elementButton)}
  • } + {update.removed.length > 0 &&
  • {t('Removed')} · {update.removed.length}{update.removed.map(item => {item.label})}
  • } + {update.meta &&
  • {t('View notes updated')}
  • } +
}
: )} diff --git a/skills/q-flow/assets/viewer/src/graph-diff.js b/skills/q-flow/assets/viewer/src/graph-diff.js new file mode 100644 index 0000000..e4e06bc --- /dev/null +++ b/skills/q-flow/assets/viewer/src/graph-diff.js @@ -0,0 +1,39 @@ +// Structural comparison of two versions of a graph input (generate-viewer --compare): per view, matched by viewIdOf, the +// node, edge and group ids added, changed or removed, and whether the view's title, scope or notes changed. Geometry and +// anchor line numbers are not content, so a refresh that only moved or realigned them changes nothing here. +import { viewIdOf } from './view-identity.js'; + +const VOLATILE = new Set(['position', 'size', 'route', 'layout', 'lineStart', 'lineEnd']); +const content = value => JSON.stringify(value ?? null, (key, item) => VOLATILE.has(key) ? undefined : item); +const viewsOf = input => Array.isArray(input?.diagrams) ? input.diagrams : input ? [input] : []; +const KINDS = ['nodes', 'edges', 'groups']; + +// A readable name for an element: a node's or group's label, or "source → target: label" for an edge. +export function elementName(graph, id) { + const label = nodeId => graph.nodes.find(node => node.id === nodeId)?.label ?? nodeId; + const edge = (graph.edges ?? []).find(item => item.id === id); + if (edge) return `${label(edge.source)} → ${label(edge.target)}${edge.label ? `: ${edge.label}` : ''}`; + return graph.nodes.find(node => node.id === id)?.label ?? (graph.groups ?? []).find(group => group.id === id)?.label ?? id; +} + +export function compareGraphs(before, after) { + const old = new Map(viewsOf(before).map(graph => [viewIdOf(graph), graph])); + const views = Object.fromEntries(viewsOf(after).map(graph => { + const previous = old.get(viewIdOf(graph)) ?? { meta: {}, nodes: [], edges: [], groups: [] }; + const diff = { added: [], changed: [], removed: [], meta: ['title', 'scope', 'notes'].some(key => content(previous.meta?.[key]) !== content(graph.meta?.[key])) }; + for (const kind of KINDS) { + const was = new Map((previous[kind] ?? []).map(item => [item.id, item])), now = new Set((graph[kind] ?? []).map(item => item.id)); + for (const item of graph[kind] ?? []) if (!was.has(item.id)) diff.added.push(item.id); else if (content(was.get(item.id)) !== content(item)) diff.changed.push(item.id); + for (const id of was.keys()) if (!now.has(id)) diff.removed.push({ id, label: elementName(previous, id) }); + } + return [viewIdOf(graph), diff]; + })); + const removedViews = [...old.keys()].filter(id => !Object.hasOwn(views, id)); + return { views, ...(removedViews.length ? { removedViews } : {}) }; +} + +// The page reads the comparison once at start (main.jsx); views and their elements look it up by view id. +let comparison = null; +export const setComparison = value => { comparison = value; }; +export const comparisonOf = graph => comparison?.views?.[viewIdOf(graph)] ?? null; +export const updateCount = diff => diff ? diff.added.length + diff.changed.length + diff.removed.length + (diff.meta ? 1 : 0) : 0; diff --git a/skills/q-flow/assets/viewer/src/i18n-messages.json b/skills/q-flow/assets/viewer/src/i18n-messages.json index 8562fc5..86a3fd2 100644 --- a/skills/q-flow/assets/viewer/src/i18n-messages.json +++ b/skills/q-flow/assets/viewer/src/i18n-messages.json @@ -187,7 +187,14 @@ "Shared dependencies": "公共依赖", "Source changes": "源码变化", "Show source changes": "显示源码变化", - "Hide source changes": "隐藏源码变化" + "Hide source changes": "隐藏源码变化", + "This update": "本次更新", + "Show this update": "显示本次更新", + "Hide this update": "隐藏本次更新", + "Added": "新增", + "Changed": "改动", + "Removed": "删除", + "View notes updated": "视图说明已更新" }, "ja": { "Architecture": "アーキテクチャ", @@ -377,7 +384,14 @@ "Shared dependencies": "共通の依存先", "Source changes": "ソースの変更", "Show source changes": "ソースの変更を表示", - "Hide source changes": "ソースの変更を隠す" + "Hide source changes": "ソースの変更を隠す", + "This update": "今回の更新", + "Show this update": "今回の更新を表示", + "Hide this update": "今回の更新を隠す", + "Added": "追加", + "Changed": "変更", + "Removed": "削除", + "View notes updated": "ビューの説明を更新" }, "ko": { "Architecture": "아키텍처", @@ -567,7 +581,14 @@ "Shared dependencies": "공통 의존성", "Source changes": "소스 변경", "Show source changes": "소스 변경 표시", - "Hide source changes": "소스 변경 숨기기" + "Hide source changes": "소스 변경 숨기기", + "This update": "이번 업데이트", + "Show this update": "이번 업데이트 표시", + "Hide this update": "이번 업데이트 숨기기", + "Added": "추가", + "Changed": "변경", + "Removed": "삭제", + "View notes updated": "뷰 설명이 갱신됨" }, "de": { "Architecture": "Architektur", @@ -757,7 +778,14 @@ "Shared dependencies": "Gemeinsame Abhängigkeiten", "Source changes": "Quellcode-Änderungen", "Show source changes": "Quellcode-Änderungen anzeigen", - "Hide source changes": "Quellcode-Änderungen ausblenden" + "Hide source changes": "Quellcode-Änderungen ausblenden", + "This update": "Diese Aktualisierung", + "Show this update": "Diese Aktualisierung anzeigen", + "Hide this update": "Diese Aktualisierung ausblenden", + "Added": "Hinzugefügt", + "Changed": "Geändert", + "Removed": "Entfernt", + "View notes updated": "Ansichtsbeschreibung aktualisiert" }, "fr": { "Architecture": "Architecture", @@ -947,7 +975,14 @@ "Shared dependencies": "Dépendances partagées", "Source changes": "Modifications du code", "Show source changes": "Afficher les modifications du code", - "Hide source changes": "Masquer les modifications du code" + "Hide source changes": "Masquer les modifications du code", + "This update": "Cette mise à jour", + "Show this update": "Afficher cette mise à jour", + "Hide this update": "Masquer cette mise à jour", + "Added": "Ajouté", + "Changed": "Modifié", + "Removed": "Supprimé", + "View notes updated": "Description de la vue mise à jour" }, "es": { "Architecture": "Arquitectura", @@ -1137,7 +1172,14 @@ "Shared dependencies": "Dependencias compartidas", "Source changes": "Cambios en el código", "Show source changes": "Mostrar cambios en el código", - "Hide source changes": "Ocultar cambios en el código" + "Hide source changes": "Ocultar cambios en el código", + "This update": "Esta actualización", + "Show this update": "Mostrar esta actualización", + "Hide this update": "Ocultar esta actualización", + "Added": "Añadido", + "Changed": "Modificado", + "Removed": "Eliminado", + "View notes updated": "Descripción de la vista actualizada" }, "ru": { "Architecture": "Архитектура", @@ -1327,7 +1369,14 @@ "Shared dependencies": "Общие зависимости", "Source changes": "Изменения в коде", "Show source changes": "Показать изменения в коде", - "Hide source changes": "Скрыть изменения в коде" + "Hide source changes": "Скрыть изменения в коде", + "This update": "Это обновление", + "Show this update": "Показать это обновление", + "Hide this update": "Скрыть это обновление", + "Added": "Добавлено", + "Changed": "Изменено", + "Removed": "Удалено", + "View notes updated": "Описание представления обновлено" }, "pt": { "Architecture": "Arquitetura", @@ -1517,6 +1566,13 @@ "Shared dependencies": "Dependências compartilhadas", "Source changes": "Alterações no código", "Show source changes": "Mostrar alterações no código", - "Hide source changes": "Ocultar alterações no código" + "Hide source changes": "Ocultar alterações no código", + "This update": "Esta atualização", + "Show this update": "Mostrar esta atualização", + "Hide this update": "Ocultar esta atualização", + "Added": "Adicionado", + "Changed": "Alterado", + "Removed": "Removido", + "View notes updated": "Descrição da visão atualizada" } } diff --git a/skills/q-flow/assets/viewer/src/main.jsx b/skills/q-flow/assets/viewer/src/main.jsx index 63448fc..2c0fc8a 100644 --- a/skills/q-flow/assets/viewer/src/main.jsx +++ b/skills/q-flow/assets/viewer/src/main.jsx @@ -10,8 +10,10 @@ import { moduleColorMap, PALETTES, themeVariables, withoutWash } from './visual- import { usePanels } from './features/usePanels.js'; import { graphInputWithEdits } from './session-graph.js'; import { DEFAULT_LOCALE } from './i18n.js'; +import { setComparison } from './graph-diff.js'; const input = JSON.parse(document.querySelector('#graph-data').textContent); +setComparison(JSON.parse(document.querySelector('#graph-compare')?.textContent ?? 'null')); const diagrams = [...(Array.isArray(input.diagrams) ? input.diagrams : [input])] .sort(compareViews); diff --git a/skills/q-flow/assets/viewer/src/session-graph.js b/skills/q-flow/assets/viewer/src/session-graph.js index cb49408..680ca94 100644 --- a/skills/q-flow/assets/viewer/src/session-graph.js +++ b/skills/q-flow/assets/viewer/src/session-graph.js @@ -10,6 +10,16 @@ import { presentationGraph } from './presentation-graph.js'; const DATA_ELEMENT = /(]*\bid="graph-data"[^>]*>)([\s\S]*?)(<\/script>)/; export const safeJson = graph => JSON.stringify(graph).replaceAll('&', '\\u0026').replaceAll('<', '\\u003c').replaceAll('>', '\\u003e').replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029'); +// generate-viewer --compare: the structural comparison sits in its own element after the graph, so a page saved from the +// Viewer (which rewrites only graph-data) keeps it and graph.json never carries it. +const COMPARE_ELEMENT = /]*\bid="graph-compare"[^>]*>[\s\S]*?<\/script>/; +export function pageWithComparison(html, comparison) { + const element = ``; + if (COMPARE_ELEMENT.test(html)) return html.replace(COMPARE_ELEMENT, () => element); + if (!DATA_ELEMENT.test(html)) throw new Error('page has no graph-data element'); + return html.replace(DATA_ELEMENT, match => `${match}${element}`); +} + export function pageWithGraph(html, graph) { if (!DATA_ELEMENT.test(html)) throw new Error('page has no graph-data element'); return html.replace(DATA_ELEMENT, (match, open, data, close) => `${open}${safeJson(graph)}${close}`); diff --git a/skills/q-flow/assets/viewer/src/styles.css b/skills/q-flow/assets/viewer/src/styles.css index d420c63..7d25948 100644 --- a/skills/q-flow/assets/viewer/src/styles.css +++ b/skills/q-flow/assets/viewer/src/styles.css @@ -15,6 +15,8 @@ --accent: #5753c6; --accent-soft: #f8f8ff; --warm: #c44b00; + --diff-added: #218358; + --diff-changed: #0d74ce; --font-body: 16px; --font-small: 14px; --edge-line-height: 24px; @@ -53,6 +55,8 @@ :root[data-theme="dark"] { color-scheme: dark; + --diff-added: #3dd68c; + --diff-changed: #70b8ff; --material-thick: color-mix(in srgb, var(--panel) 92%, transparent); --material: color-mix(in srgb, var(--panel) 86%, transparent); --material-thin: color-mix(in srgb, var(--panel) 74%, transparent); @@ -192,6 +196,16 @@ button:disabled { cursor: not-allowed; } .source-changes code { font-size: 12px; color: var(--label); } .source-changes .folded-edge { display: block; margin-top: 2px; color: var(--warm); } .source-changes pre { margin: 4px 0 0; padding: 4px 6px; border-radius: var(--r-control); background: var(--fill); color: var(--label-2); font-size: 11px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; } +.graph-update { margin: 0; padding-left: 16px; color: var(--label-2); font-size: 13px; line-height: 1.6; } +.graph-update li + li { margin-top: 5px; } +.graph-update .folded-edge, .graph-update s, .graph-update .update-group { display: block; margin-top: 2px; } +.graph-update .update-added::marker, .graph-update .update-added .folded-edge { color: var(--diff-added); } +.graph-update .update-changed::marker, .graph-update .update-changed .folded-edge { color: var(--diff-changed); } +.graph-update s { color: var(--label-3); } +.diagram-node.is-added { outline: 2px solid var(--diff-added); outline-offset: 3px; } +.diagram-node.is-changed { outline: 2px solid var(--diff-changed); outline-offset: 3px; } +.edge-label.is-added { box-shadow: 0 0 0 1.5px var(--diff-added); } +.edge-label.is-changed { box-shadow: 0 0 0 1.5px var(--diff-changed); } .diagram-node.is-drifted { outline: 2px dashed var(--warm); outline-offset: 3px; } .edge-label.is-drifted { box-shadow: 0 0 0 1.5px var(--warm); } .workspace.nav-open .legend-anchor { left: calc(var(--side-w) + 2 * var(--gutter)); } diff --git a/skills/q-flow/references/graph-schema.md b/skills/q-flow/references/graph-schema.md index d7f166d..b331a4d 100644 --- a/skills/q-flow/references/graph-schema.md +++ b/skills/q-flow/references/graph-schema.md @@ -98,7 +98,8 @@ The abbreviated graphs above show only the wrapper; every graph still follows th - Optional node `source.kind` uses the same evidence values. `source.file` and `source.lineStart` identify the exact anchor. - Optional edge `site` (`file`, `lineStart`, optional `lineEnd` and `symbol`) records the line that makes the relationship hold: the call, write, foreign key, `extends` clause or state assignment. It has the same shape and checks as a node `source` but no `kind`: the edge's own `evidence` names the kind. An edge needs one when its `evidence` is `source`, `code`, `config`, `schema` or `test` and it is not a sequence `return` (`needsSite()`); the field is optional everywhere, so graphs written without it stay valid. - With `--repo-root `, validation and generation read every node's `source.file` and every edge's `site.file` as repository-relative UTF-8 text and check the inclusive line range. Absolute paths, parent traversal, directories, binary files and symlinks escaping the root are rejected. Repeated references share one file read. When `source.symbol` is present, its last segment (split on every character other than a letter, digit, `_` or `$`) must occur as a whole word within the range; write the name as it appears at the definition, not a description. A failure names the lines where the word does occur in the file, and the receipt counts symbol checks in `sourceEvidence.symbols` and relationship coverage in `sourceEvidence.relations` (`sited` of `eligible`, computed with or without the root). A site failure is named `diagrams[i].edges[j].site`. `--fix --repo-root` moves a node `source` or edge `site` `lineStart` to the only such line in the file and shifts `lineEnd` with it, clamped to the last line; anchors with several or no matches stay for the author (`edge .site` in the messages). Without the root, receipts explicitly mark existing source anchors `skipped`; without anchors they report `not-applicable`. These checks cover the local working tree, not `sourceRef` revision identity, definition parsing or claim correctness: a mention of the name left inside the range still passes. -- Source drift. With `--repo-root` inside a git work tree, generation and `validate --fix` record `meta.sourceFiles` on every view: each anchored file mapped to the git blob hash of the content its anchors point at (computed with `git hash-object`, nothing written to the repository). Later validation diffs each file against that blob: an anchor on a line that only moved follows it (in memory; `--fix` and generation write the new numbers) and passes, while changed code fails as source drift, grouped per changed hunk with the old and new lines, the anchored elements and the text that names what changed. Drift is reported when (1) an anchored line was rewritten, with any text still stating a number the rewrite changed; (2) a removed call leaves a method with no caller in the repository, naming the anchors inside it and the text that names what only it used; (3) added code that mentions an anchored symbol or calls a receiver named like an anchored file sits on no anchor; (4) an identifier gone from the anchored files is still written in the graph. `validate --fix --repo-root` realigns every anchor, renews `meta.sourceFiles` and appends one `meta.sourceDrift` item per change to each view it touches (`file`, `line`, `change`, `elements` — the ids in that view the change touches —, `removed`, `added`, `anchors`, `mentions`); validation fails while any item remains, so the author updates the named elements and deletes each item. Generation does not fail on listed items: it exempts their elements from the line check and the Viewer marks them (a dashed outline on nodes, an outlined edge label) and lists the items beside the key points; drift not yet listed still fails generation. `validate --changes --repo-root` writes the listed and newly detected changes as Markdown for a pull request comment: per view, the readable names of the touched elements, `file:line`, the change and the old and new code; the exit code is unchanged. A baseline blob missing from the repository (a shallow CI clone: use `fetch-depth: 0`) is reported and that file falls back to the working-tree check above; graphs without `meta.sourceFiles` keep that check unchanged. The rules are C-family text heuristics, not a parser: a call split across lines or an overloaded name can be missed. +- Source drift. With `--repo-root` inside a git work tree, generation and `validate --fix` record `meta.sourceFiles` on every view: each anchored file mapped to the git blob hash of the content its anchors point at (computed with `git hash-object`, nothing written to the repository). Later validation diffs each file against that blob: an anchor on a line that only moved follows it (in memory; `--fix` and generation write the new numbers) and passes, while changed code fails as source drift, grouped per changed hunk with the old and new lines, the anchored elements and the text that names what changed. Drift is reported when (1) an anchored line was rewritten, with any text still stating a number the rewrite changed; (2) a removed call leaves a method with no caller in the repository, naming the anchors inside it and the text that names what only it used; (3) added code that mentions an anchored symbol or calls a receiver named like an anchored file sits on no anchor; (4) an identifier gone from the anchored files is still written in the graph. `validate --fix --repo-root` realigns every anchor, renews `meta.sourceFiles` and appends one `meta.sourceDrift` item per change to each view it touches (`file`, `line`, `change`, `elements` — the ids in that view the change touches —, `removed`, `added`, `anchors`, `mentions`); validation fails while any item remains, so the author updates the named elements and deletes each item. Generation does not fail on listed items: it exempts their elements from the line check and the Viewer marks them (a dashed outline on nodes, an outlined edge label) and lists the items beside the key points; drift not yet listed still fails generation. `validate --changes --repo-root` writes the listed and newly detected changes as Markdown for a pull request comment: per view, the readable names of the touched elements, `file:line`, the change and the old and new code; the exit code is unchanged. Stamping also records `meta.sourceCommit` (HEAD at that moment). Files changed since that commit that the view does not anchor, in the languages it anchors (at most 100), are checked only for text-backed changes: a removed call that leaves a method with no caller, when the graph's text names something only that method used, and a name the graph's text uses that is gone from the whole repository; each alarm names the elements whose text matched. Plain prose ("runs the automatic split") is not a name and is not matched. A baseline blob missing from the repository (a shallow CI clone: use `fetch-depth: 0`) is reported and that file falls back to the working-tree check above; graphs without `meta.sourceFiles` keep that check unchanged. The rules are C-family text heuristics, not a parser: a call split across lines or an overloaded name can be missed. +- Comparison. `generate-viewer.mjs --compare ` compares the generated graph with an earlier version: a file, or the input graph at a git revision (`HEAD` = as last committed; a graph with no version there is generated without a comparison). Views pair by view id; per view, node, edge and group ids are added, changed or removed, and the view's title, scope or notes changed or not. Geometry (`position`, `size`, `route`, `layout`) and anchor line numbers are not content. The result (`compareGraphs()` in `graph-diff.js`) is written to its own `graph-compare` element of the page, never to `graph.json`, and survives saving from the page; the Viewer outlines added elements in green and changed ones in blue and lists them, with removed ones by name, beside the key points; the receipt counts them as `compare`. - To emphasize the business center, use the existing `business` kind where supported, or include `core` or `business` in `tags` (matched case-insensitively). Keep the diagram's legal node kind; `core` is not a new kind or schema field. In a state diagram the `core` state is the goal and a `failure` tag marks a failed state; both only feed the Viewer's derived state colors. - Composition review (`reviewComposition()` in `graph-validation.js`, printed in full by `validate-graph.mjs --input-only` as `Composition warning () : …`, counted as `warnings: n` in every receipt) is advisory: warnings never fail validation or generation, and a collection with no `module` anywhere gets none. Rules: `module.missing` (an ordinary node without `module` once the collection uses modules; `initial` / `final` and the outsider kinds `external`, `actor`, `device` are exempt), `module.inconsistent` (the same node label carries a module in one view and none or another in a second view), `module.single-tone` (a flowchart or data flow of ≥ 6 washed nodes all in one module — a prompt to check, legitimate when the flow lives in one subsystem), `flowchart.process-branch` (a non-decision with more than one outgoing edge), `edge.site-missing` (an edge that needs a `site` while at least one other edge of the same graph records one; a graph with no site anywhere stays quiet). One rule needs the laid-out graph: `view.oversized` (`overviewWarnings()`, printed by `generate-viewer.mjs` once and only counted by output validation) fires when a view's bounds need more than `MAX_SCREENS` (4) reading rectangles of `OVERVIEW_AREA` (1392×688, a 1440×900 window with both panels closed) at `READABLE_ZOOM` (.75); a graph without positions reports nothing. The receipt carries `warnings: ` only when there are any. - The cool-neutral visual system is a Viewer presentation rule. Color, typography, and core styling require no new graph fields. The order-fulfillment preview model is example content, not a default dataset or evidence source. diff --git a/skills/q-flow/scripts/generate-viewer.mjs b/skills/q-flow/scripts/generate-viewer.mjs index 749b7f2..6066b7e 100644 --- a/skills/q-flow/scripts/generate-viewer.mjs +++ b/skills/q-flow/scripts/generate-viewer.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node import { viewIdOf } from '../assets/viewer/src/view-identity.js'; +import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -9,7 +10,8 @@ import { isDeepStrictEqual, parseArgs } from 'node:util'; import { diagramTypeOf, graphsOf, printCompositionReview, printViewReview, readAndValidateGraph, stampSourceFiles, verifySourceEvidence, layoutComposition } from './validate-graph.mjs'; import { compileGraphLayout } from './compile-layout.mjs'; import { requireDiagramQuality } from '../assets/viewer/src/layout-quality.js'; -import { pageWithGraph } from '../assets/viewer/src/session-graph.js'; +import { pageWithComparison, pageWithGraph } from '../assets/viewer/src/session-graph.js'; +import { compareGraphs } from '../assets/viewer/src/graph-diff.js'; import { SVG_FILE, diagramSvgFiles } from '../assets/viewer/src/export-svg.js'; const scriptDir = path.dirname(fileURLToPath(import.meta.url)); @@ -59,18 +61,32 @@ export async function compileViews(graphs, compile) { return compiled; } +// The earlier version for --compare: a file, or the input graph as stored at a git revision of its repository. A graph +// with no such version (not committed yet, or outside git) is generated without a comparison. +function earlierGraph(value, inputPath) { + if (fs.existsSync(value) && fs.statSync(value).isFile()) return JSON.parse(fs.readFileSync(value, 'utf8')); + const file = fs.realpathSync(inputPath), dir = path.dirname(file); + const top = spawnSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }); + if (top.status !== 0) { console.warn(`--compare ${value}: not a file, and ${inputPath} is not in a git repository; generating without a comparison`); return null; } + const shown = spawnSync('git', ['-C', dir, 'show', `${value}:${path.relative(top.stdout.trim(), file).split(path.sep).join('/')}`], { encoding: 'utf8', maxBuffer: 256 << 20 }); + if (shown.status !== 0) { console.warn(`--compare ${value}: ${inputPath} has no version at that revision; generating without a comparison`); return null; } + return JSON.parse(shown.stdout); +} + const USAGE = `Usage: node generate-viewer.mjs [options] --repo-root verify every node source (file, line range, symbol) against this working tree --layout auto|preserve auto (default) computes positions; preserve keeps authored geometry under the same gate --view auto-layout only this view; repeat for several; all other views must pass preserve --force replace existing index.html / graph.json / diagram*.svg in the output directory (needs approval) + --compare mark what changed against an earlier version: a graph.json file, or a git revision of the input + (HEAD = as last committed); the page colors added and changed elements and lists removed ones --verbose print the full receipt (layout candidates, folds, diagnostics) instead of one summary line -h, --help this text Writes index.html, graph.json and one SVG per view (diagram.svg, or diagram--.svg for a collection). Success prints one JSON line; failure prints the failing elements with rule, measurement and remediation.`; async function main() { - const { positionals: positional, values } = parseArgs({ allowPositionals: true, options: { force: { type: 'boolean' }, 'repo-root': { type: 'string' }, layout: { type: 'string', default: 'auto' }, view: { type: 'string', multiple: true }, verbose: { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h', default: false } } }); + const { positionals: positional, values } = parseArgs({ allowPositionals: true, options: { force: { type: 'boolean' }, 'repo-root': { type: 'string' }, layout: { type: 'string', default: 'auto' }, view: { type: 'string', multiple: true }, compare: { type: 'string' }, verbose: { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h', default: false } } }); const force = values.force; if (values.help) { console.log(USAGE); process.exit(0); } if (positional.length !== 2) { @@ -82,6 +98,7 @@ async function main() { const outputDir = path.resolve(outputArg); if (outputDir === path.parse(outputDir).root || outputDir === os.homedir()) throw new Error('Refusing broad output directory'); const input = readAndValidateGraph(inputPath, { inputOnly: true }); + const earlier = values.compare === undefined ? null : earlierGraph(values.compare, inputPath); const selected = new Set(values.view ?? []), views = graphsOf(input); if (selected.size && values.layout !== 'auto') throw new Error('--view requires --layout auto'); const unknown = [...selected].filter(id => !views.some(graph => viewIdOf(graph) === id)); @@ -109,7 +126,8 @@ async function main() { // Record what the anchors point at now, so validate can later tell moved lines from changed code. if (values['repo-root'] !== undefined) stampSourceFiles(graph, values['repo-root']); const oversized = printViewReview(graph, { print: true }); // geometry exists only now; the input review could not see it - const contents = { 'index.html': pageWithGraph(shell, graph), 'graph.json': `${JSON.stringify(graph, null, 2)}\n` }; + const comparison = earlier && compareGraphs(earlier, graph); + const contents = { 'index.html': comparison ? pageWithComparison(pageWithGraph(shell, graph), comparison) : pageWithGraph(shell, graph), 'graph.json': `${JSON.stringify(graph, null, 2)}\n` }; for (const { name, svg } of diagramSvgFiles(graph)) contents[name] = svg; writeOutputs(outputDir, contents, svgs.filter(name => !Object.hasOwn(contents, name))); const files = Object.keys(contents); @@ -128,6 +146,10 @@ async function main() { const repaired = compiled.flatMap((item, i) => item.report?.repair ? [{ view: viewIdOf(views[i]) ?? i, ...(item.report.repair.rows ? { rows: true } : { rerouted: item.report.repair.rerouted, moved: item.report.repair.movedNodeIds }) }] : []); if (repaired.length) summary.repaired = repaired; if (pendingDrift) summary.sourceDrift = pendingDrift; + if (comparison) { + const diffs = Object.values(comparison.views), total = key => diffs.reduce((sum, diff) => sum + diff[key].length, 0); + summary.compare = { added: total('added'), changed: total('changed'), removed: total('removed'), ...(comparison.removedViews ? { removedViews: comparison.removedViews.length } : {}) }; + } const detail = values.verbose ? { layoutComposition: graphs.map(layoutComposition), layout: compiled.map(item => item.report), quality } : {}; console.log(JSON.stringify(graphs.length === 1 && !Object.hasOwn(graph, 'diagrams') ? { generated: true, diagramType: diagramTypeOf(graphs[0]), outputDir, files, ...summary, ...detail, sourceEvidence } diff --git a/skills/q-flow/scripts/graph-diff.test.mjs b/skills/q-flow/scripts/graph-diff.test.mjs new file mode 100644 index 0000000..4e084e3 --- /dev/null +++ b/skills/q-flow/scripts/graph-diff.test.mjs @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { compareGraphs, elementName, updateCount } from '../assets/viewer/src/graph-diff.js'; +import { pageWithComparison, pageWithGraph } from '../assets/viewer/src/session-graph.js'; + +const view = (viewId, extra = {}) => ({ + meta: { title: 'Orders', diagramType: 'state', viewId, notes: ['n'] }, + nodes: [{ id: 'a', label: 'Open', position: { x: 0, y: 0 }, size: { width: 90, height: 40 }, source: { file: 'A.java', lineStart: 3, lineEnd: 9, symbol: 'open' } }, { id: 'b', label: 'Paid' }], + edges: [{ id: 'e', source: 'a', target: 'b', label: 'pay', route: { points: [{ x: 1, y: 2 }] }, site: { file: 'A.java', lineStart: 5, symbol: 'pay' } }], + ...extra +}); + +test('moved geometry and realigned anchor lines are not changes', () => { + const after = structuredClone(view('v')); + after.nodes[0].position = { x: 300, y: 80 }; after.nodes[0].source.lineStart = 13; after.edges[0].route = { points: [] }; after.edges[0].site.lineStart = 15; + const diff = compareGraphs(view('v'), after).views.v; + assert.deepEqual(diff, { added: [], changed: [], removed: [], meta: false }); + assert.equal(updateCount(diff), 0); +}); + +test('content changes, additions and removals are found per element, with readable names for removed ones', () => { + const after = structuredClone(view('v')); + after.nodes[1].label = 'Paid in full'; after.nodes.push({ id: 'c', label: 'Cancelled' }); after.edges = [{ id: 'f', source: 'a', target: 'c', label: 'cancel' }]; after.meta.notes = ['changed']; + const diff = compareGraphs(view('v'), after).views.v; + assert.deepEqual(diff.added.sort(), ['c', 'f']); + assert.deepEqual(diff.changed, ['b']); + assert.deepEqual(diff.removed, [{ id: 'e', label: 'Open → Paid: pay' }]); + assert.equal(diff.meta, true); + assert.equal(elementName(after, 'f'), 'Open → Cancelled: cancel'); +}); + +test('views pair by view id: a new view is all added, a dropped view is reported', () => { + const result = compareGraphs({ diagrams: [view('v1'), view('v2')] }, { diagrams: [view('v2'), view('v3')] }); + assert.deepEqual(result.views.v2.added, []); + assert.deepEqual(result.views.v3.added.sort(), ['a', 'b', 'e']); + assert.deepEqual(result.removedViews, ['v1']); +}); + +test('the comparison sits in its own page element and survives rewriting the graph data', () => { + const shell = ''; + const page = pageWithComparison(pageWithGraph(shell, view('v')), { views: { v: { added: ['a'], changed: [], removed: [], meta: false } } }); + assert.match(page, / - diff --git a/skills/q-flow/assets/viewer/src/ViewerShell.jsx b/skills/q-flow/assets/viewer/src/ViewerShell.jsx index fc456dc..39d366c 100644 --- a/skills/q-flow/assets/viewer/src/ViewerShell.jsx +++ b/skills/q-flow/assets/viewer/src/ViewerShell.jsx @@ -208,6 +208,7 @@ export default function ViewerShell({ graph, originalGraph, graphForSave, allDia
{ onOverviewKeyDown(event); if (!event.defaultPrevented) handleCanvasKeyDown(event); }} aria-label={t('Interactive {type}', { type: t(viewTypeLabel(graph)) })}> text(cx, titleY + i * 26, line, 'participant-title', ' text-anchor="middle"')).join(''); const subtitle = node.subtitle ? layoutText(node.subtitle, node.size.width - 28, 16, 22).lines.map((line, i) => text(cx, titleY + (titleLines.length - 1) * 26 + (actorNode ? 28 : 22) + i * 22, line, 'body', ' text-anchor="middle"')).join('') : ''; const executions = (node.executionRects ?? []).map(item => ``).join(''); - return `${escapeXml([node.label, node.subtitle].filter(Boolean).join(" · "))}${head}${label}${subtitle}${executions}`; + return `${head}${label}${subtitle}${executions}`; } export default { diff --git a/skills/q-flow/assets/viewer/src/features/useGraphLayout.js b/skills/q-flow/assets/viewer/src/features/useGraphLayout.js index c8c9806..7a060cc 100644 --- a/skills/q-flow/assets/viewer/src/features/useGraphLayout.js +++ b/skills/q-flow/assets/viewer/src/features/useGraphLayout.js @@ -76,7 +76,8 @@ export function useGraphLayout(graph, reduceMotion, setStatus, originalGraph = g const onNodeDragStop = async (_, node) => { if (node.type !== 'diagram') return; if (isArchitectureOverview(currentGraph)) { - try { const result = await applyShared(currentGraph, {}, true); if (result.error && !result.superseded) { installOverview(graphDraft); if (!result.cancelled) setStatus(result.error); } } + // A dragged card reorders its section like the arrow keys do; the drop point only picks the new slot. + try { const result = await applyShared(reorderOverview(graphDraft, node.id, node.position), {}, true); if (result.error && !result.superseded) { installOverview(graphDraft); if (!result.cancelled) setStatus(result.error); } } catch (error) { installOverview(graphDraft); setStatus(error.message); } } else { const result = await applyShared(currentGraph, { growBoundaries: true }); diff --git a/skills/q-flow/assets/viewer/src/styles.css b/skills/q-flow/assets/viewer/src/styles.css index 7d25948..431b7c5 100644 --- a/skills/q-flow/assets/viewer/src/styles.css +++ b/skills/q-flow/assets/viewer/src/styles.css @@ -302,6 +302,8 @@ button:disabled { cursor: not-allowed; } .flow-edge--sequence .selection-feedback.is-animated .selection-edge-shine { animation-name: sequence-line-jelly; } .selection-feedback.has-flow .selection-edge-halo { stroke-opacity: .5; } .selection-feedback.has-flow .selection-edge-shine { opacity: .1; } +/* Under running flow the shine stays still: its widening keyframes would fill the dash gaps and wash out the motion. */ +.selection-feedback.has-flow .selection-edge-shine { animation: none; } @keyframes selection-glow { 0% { stroke-width: 2px; opacity: 0; } 24% { stroke-width: 18px; opacity: .27; } diff --git a/skills/q-flow/scripts/layout-cancellation.test.mjs b/skills/q-flow/scripts/layout-cancellation.test.mjs index 25ff329..a2bea3a 100644 --- a/skills/q-flow/scripts/layout-cancellation.test.mjs +++ b/skills/q-flow/scripts/layout-cancellation.test.mjs @@ -18,7 +18,7 @@ function harness(overview = false) { LayoutWorker:class {constructor(){workers.push(this);}postMessage(data){this.data=data;}terminate(){this.terminated=true;}}, initialNodes:g=>g.nodes,initialEdges:g=>g.edges,currentGraphFromFlow:()=>dragging, affectedRouteIds:()=>new Set(),diagramTypeOf:()=> 'architecture',isArchitectureOverview:()=>overview, - overviewSections:()=>[],requireDiagramQuality:()=>({diagnostics:[]}),translate:(_locale,text)=>text, + overviewSections:()=>[],reorderOverview:graph=>graph,requireDiagramQuality:()=>({diagnostics:[]}),translate:(_locale,text)=>text, requestAnimationFrame:()=>{}, }; const source=fs.readFileSync(new URL('../assets/viewer/src/features/useGraphLayout.js',import.meta.url),'utf8').replace(/^import .*;\n/gm,'').replace('export function useGraphLayout','function useGraphLayout'); From c332b24d1205f93d174ced8f8e403c0a34e0c2f1 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 15:42:29 +0800 Subject: [PATCH 11/16] =?UTF-8?q?test(matrix):=20=E4=BF=AE=E6=AD=A3=2044?= =?UTF-8?q?=20=E9=A1=B9=E9=95=BF=E6=9C=9F=E5=A4=B1=E8=B4=A5=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E6=B5=8B=E8=AF=95=E9=97=AE=E9=A2=98=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=20QA=5FEXTRAS=20=E9=80=89=E4=B8=8D=E4=B8=AD=E6=A3=80?= =?UTF-8?q?=E6=9F=A5=E5=92=8C=E4=B8=A4=E4=B8=AA=E4=B8=8D=E7=A8=B3=E5=AE=9A?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../q-flow/scripts/browser-interactions.mjs | 101 ++++++++++++------ 1 file changed, 66 insertions(+), 35 deletions(-) diff --git a/skills/q-flow/scripts/browser-interactions.mjs b/skills/q-flow/scripts/browser-interactions.mjs index 4c50fc6..e576c37 100644 --- a/skills/q-flow/scripts/browser-interactions.mjs +++ b/skills/q-flow/scripts/browser-interactions.mjs @@ -5,7 +5,13 @@ import { visibleEdges, presentationGraph } from '../assets/viewer/src/presentati // Usage: node browser-interactions.mjs GENERATED_DIRECTORY REPORT_DIRECTORY // Optional: PLAYWRIGHT_MODULE, CHROME_PATH, QA_HEADED=1, QA_TYPES, QA_VIEWS, QA_WIDTHS, QA_DPR=1, QA_MOTION_CALIBRATION=1, QA_ONLY_EXTRAS=1, QA_LAYOUT_ONLY=1, // QA_EXTRAS=none|all|edit-persistence|overview|manual-ownership|layout-worker|save-failures|strict-draft|acceptance|acceptance-details|editor-boundaries|flow-direction|export-failures|motion-matrix|motion-preferences|selection-entrypoints|ambient-flow|flow-contrast|inspector-sync|information-layout|facts-layout|fullscreen|fullscreen-errors|quick-details|repeat-notice|long-preview|text-bounds|relationship-card-avoidance|edge-site|notes|sequence-reading|file-url, QA_FIXTURE_DIR. -import { overviewSections, fitArchitectureOverview, hasOverviewContent } from '../assets/viewer/src/architecture-overview.js'; +import { overviewSections, fitArchitectureOverview, hasOverviewContent, maintainArchitectureOverview } from '../assets/viewer/src/architecture-overview.js'; +// An overview edit that needs more height than its slot is rejected by design (docs/layout-v4-acceptance.md); edit a card with room. +// Outside overviews a local edit may widen a card but never pushes a neighbour away (the draft is kept instead): edit the +// target only when ~110px to its right are clear, else the first ordinary node that has that room. +const roomy = node => graph => !graph.nodes.some(other => other !== node && other.position && node.position && other.position.y < node.position.y + node.size.height && other.position.y + other.size.height > node.position.y && other.position.x >= node.position.x + node.size.width - 1 && other.position.x < node.position.x + node.size.width + 110); +const roomyNode = graph => [target(graph), ...graph.nodes].find(node => !['initial', 'final'].includes(node.kind) && roomy(node)(graph)) ?? target(graph); +const editableNode = (graph, suffixes) => graph.nodes.find(node => !['initial', 'final'].includes(node.kind) && (!isArchitectureOverview(graph) || suffixes.every(suffix => { const edited = structuredClone(graph); edited.nodes.find(item => item.id === node.id).label += suffix; try { maintainArchitectureOverview(edited, graph, requireDiagramQuality); return true; } catch { return false; } }))) ?? graph.nodes[0]; import { isArchitectureOverview, viewIdOf, compareViews, viewTypeLabel } from '../assets/viewer/src/view-identity.js'; import { overviewPalette } from '../assets/viewer/src/architecture-overview-theme.js'; import assert from 'node:assert/strict'; @@ -181,6 +187,7 @@ async function selection(page, graph, id) { assert.equal(await count(page, '.diagram-node.is-selected'), 1); assert.equal(await count(page, '.selection-outline'), 1); const edges = visibleEdges(graph).filter(edge => edge.source === id || edge.target === id).map(edge => edge.id).sort(); + await page.waitForFunction(expected => JSON.stringify([...document.querySelectorAll('.react-flow__edge')].filter(element => element.querySelector('.selection-edge-shine')).map(element => element.dataset.id).sort()) === JSON.stringify(expected), edges, { timeout: 2000 }).catch(() => {}); const actual = await page.locator('.react-flow__edge').evaluateAll(elements => elements.filter(element => element.querySelector('.selection-edge-shine')).map(element => element.dataset.id).sort()); assert.deepEqual(actual, edges, 'Exactly the directly incident relationships are highlighted, including each self-loop once.'); const feedback = await page.locator('.react-flow__edge').evaluateAll(elements => elements.map(element => { @@ -573,7 +580,7 @@ async function exportsMatch(page, graph, name) { return { svgFile, pngFile }; } async function runCase(browser, name, viewport, options, run, extra = false) { - if (extra && process.env.QA_EXTRAS && !process.env.QA_EXTRAS.split(',').some(value => name === value || name.endsWith('-' + value) || value === 'acceptance' && name.endsWith('-overview'))) return; + if (extra && process.env.QA_EXTRAS && !process.env.QA_EXTRAS.split(',').some(value => value === 'all' || name === value || name.endsWith('-' + value) || value === 'acceptance' && name.endsWith('-overview'))) return; const context = await browser.newContext({ viewport, deviceScaleFactor: Number(process.env.QA_DPR ?? 1), acceptDownloads: true, reducedMotion: 'no-preference', ...options }); const traced=!/motion-matrix|motion-preferences|flow-contrast/.test(name); if(traced)await context.tracing.start({ screenshots: false, snapshots: false }); @@ -731,7 +738,7 @@ async function strictDraftChecks(browser, url, graph) { }; }); await page.goto(url); await theme(page, 'light'); await chooseGraph(page, graph, false); - const selected = graph.nodes.find(node => !['initial', 'final'].includes(node.kind)) ?? graph.nodes[0]; + const selected = editableNode(graph, [' <>& "中文草稿"', ' QA']); await searchSelect(page, graph, selected); await setLocked(page, false); await button(page, '编辑文字').click(); const label = page.getByRole('textbox', { name: '名称', exact: true }); @@ -1397,6 +1404,18 @@ async function pointerNode(page, node, drag = false) { await page.mouse.up(); if (drag) await page.waitForFunction(() => !document.querySelector('.canvas[aria-busy="true"]')); } +async function dragUntilKept(page, node, vectors = [[36, 22], [36, -22], [-36, 22], [-36, -22], [0, 30], [0, -30], [36, 0], [-36, 0]]) { + for (const [index, vector] of vectors.entries()) { + if (index && await count(page, '.node-card')) { await page.locator('.node-card .card-close').click(); await page.locator('.node-card').waitFor({ state: 'detached' }); } + const boxes = async () => (await geometry(page)).nodes.map(({ id, position, width, height }) => ({ id, position, width, height })); + const before = await boxes(), edgeCount = await count(page, '.react-flow__edge-path'); await pointerNode(page, node, vector); + // A rollback reinstalls the accepted graph; React Flow redraws its edges once the reinstalled nodes are measured. + await page.waitForFunction(n => document.querySelectorAll('.react-flow__edge-path').length === n, edgeCount); + const after = await boxes(); + if (JSON.stringify(after) !== JSON.stringify(before)) return { attempts: index + 1, kept: true }; + } + return { attempts: vectors.length, kept: false }; +} async function entrypoints(browser, url, graph) { if (graph.meta.diagramType === 'sequence') return; // Native sequence entry points and Inspector fallback are checked by sequence-reading/persistence. await runCase(browser, `${viewIdOf(graph)}-selection-entrypoints`, viewports[0], {}, async page => { @@ -1426,7 +1445,7 @@ async function entrypoints(browser, url, graph) { return { current, blocked: true, savedFile }; }; const legendAnchor = await assertLegendLayout(page); - const selected = target(graph); + const selected = isArchitectureOverview(graph) ? editableNode(graph, [' QA']) : roomyNode(graph); const viewBeforeClick = await page.locator('.react-flow__viewport').getAttribute('style'); await pointerNode(page, selected); await selection(page, graph, selected.id); await assertFlow(page); const card = page.locator('.node-card'); await card.waitFor(); @@ -1455,15 +1474,21 @@ async function entrypoints(browser, url, graph) { await clear(page); await searchSelect(page, graph, selected, true); const searchPulse = await pulse(page); await clear(page); await hidePanels(page); await fit(page); await setLocked(page, false); - const geometryBeforeDrag = await geometry(page); await pointerNode(page, selected, true); - await selection(page, graph, selected.id); await assertFlow(page); assert.equal(await count(page, '.inspector'), 0); await assertSelectedDetails(page, graph); assert.equal(await pulse(page), searchPulse + 1, 'Dragging selects once.'); + const geometryBeforeDrag = await geometry(page); + const overviewDrag = isArchitectureOverview(graph); + const dragged = overviewDrag ? (await pointerNode(page, selected, true), { attempts: 1 }) : await dragUntilKept(page, selected); + await selection(page, graph, selected.id); await assertFlow(page); assert.equal(await count(page, '.inspector'), 0); await assertSelectedDetails(page, graph); assert.equal(await pulse(page), searchPulse + dragged.attempts, 'Each drag selects once.'); const geometryAfterDrag = await geometry(page); - assert.notDeepEqual(geometryAfterDrag.nodes, geometryBeforeDrag.nodes, 'Unlocked drag moves a node.'); + if (overviewDrag) { assert.deepEqual(geometryAfterDrag.nodes, geometryBeforeDrag.nodes, 'An overview card dropped off any peer realigns to its slot.'); assert.ok(!(await status(page)).includes('Diagram quality failed'), `Realigning an overview card is not a failure: ${await status(page)}`); } + else assert.ok(dragged.kept, 'Unlocked drag moves a node.'); if (graph.meta.diagramType === 'sequence') assert.equal(geometryAfterDrag.nodes.find(node => node.id === selected.id).position.y, geometryBeforeDrag.nodes.find(node => node.id === selected.id).position.y, 'Sequence participants only move horizontally.'); await selection(page, graph, selected.id); await exportCurrentDraft('dragged'); const beforeSpacing = await geometry(page); - await openMore(page); await menuItem(page, '整理间距').click(); const spacingStatus = await status(page); - assert.match(spacingStatus, /移动 \d+ 个节点|当前间距无需调整|当前约束下无法继续整理|仍有.*(?:问题|手动)/); + const spacingResult = /移动 \d+ 个节点|当前间距无需调整|当前约束下无法继续整理|仍有.*(?:问题|手动)|总览已对齐/; + await openMore(page); await menuItem(page, '整理间距').click(); + await page.waitForFunction(source => new RegExp(source).test(document.querySelector('.toast')?.textContent ?? ''), spacingResult.source).catch(() => {}); + const spacingStatus = await status(page); + assert.match(spacingStatus, spacingResult); if (spacingStatus === '当前约束下无法继续整理') assert.deepEqual(await geometry(page), beforeSpacing, 'A rejected spacing candidate does not partially change geometry.'); await openMore(page); await menuItem(page, '重置').click(); await hidePanels(page); await fit(page); const authored = await geometry(page); @@ -1489,8 +1514,8 @@ async function entrypoints(browser, url, graph) { await editCard.getByRole('button', { name: '查看详情', exact: true }).click(); assert.equal(await page.locator('.drawer-body h2').innerText(), editedNodeLabel); assert.equal(await page.locator('.drawer-subtitle').innerText(), '会话说明'); await clear(page, 'close'); await hidePanels(page); - if (graph.edges.length) { - const edge = page.locator('.react-flow__edge').first(); + if (visibleEdges(graph).length) { + const edge = page.locator('.react-flow__edge').first(), editedEdgeId = await edge.getAttribute('data-id'); await edge.focus(); await page.keyboard.press('Enter'); await assertFlow(page); const relationCard = page.locator('.relation-card'); await relationCard.waitFor(); assert.equal(await count(page, '.inspector'), 0, 'Relationship click opens quick look before details.'); @@ -1507,7 +1532,7 @@ async function entrypoints(browser, url, graph) { // 45019fc too (text.node-size, spacing.label-node) and keep the blocked branch until their own edits are fixed. const downloads = await exportCurrentDraft('edited', Boolean(getDiagram(graph.meta.diagramType).cardLayout)); assert.equal(downloads.current.nodes.find(node => node.id === selected.id).label, editedNodeLabel); - assert.equal(downloads.current.edges[0].label, editedEdgeLabel); + assert.equal(downloads.current.edges.find(item => item.id === editedEdgeId).label, editedEdgeLabel); if (downloads.svgFile) { const editedSvg = fs.readFileSync(downloads.svgFile, 'utf8'); assert.ok(editedSvg.includes(editedNodeLabel) && editedSvg.includes(editedEdgeLabel), 'SVG export uses current session text.'); @@ -1515,6 +1540,9 @@ async function entrypoints(browser, url, graph) { await openMore(page); await menuItem(page, '重置').click(); await page.waitForFunction(({ id, label }) => document.querySelector(`.react-flow__node[data-id="${CSS.escape(id)}"] .node-visual title`)?.textContent.startsWith(label), { id: selected.id, label: selected.label }); assert.ok(!(await page.locator('.canvas').innerText()).includes(editedEdgeLabel), 'Reset restores authored relationship text.'); + } else { + await openMore(page); await menuItem(page, '重置').click(); + await page.waitForFunction(({ id, label }) => document.querySelector(`.react-flow__node[data-id="${CSS.escape(id)}"] .node-visual title`)?.textContent.startsWith(label), { id: selected.id, label: selected.label }); } const viewport = page.locator('.react-flow__viewport'); const beforeZoom = await viewport.evaluate(element => new DOMMatrix(getComputedStyle(element).transform).a); @@ -1624,7 +1652,10 @@ async function notesCheck(browser, url) { await button(page, '退出全屏').click(); await fullscreenState(page, false); return { notes: notes.length, openingRight: Math.round(opening) }; }, true); + const plain = structuredClone(input); for (const view of plain.diagrams ?? [plain]) delete view.meta.notes; + const plainHtml = fs.readFileSync(path.join(inputRoot, 'index.html'), 'utf8').replace(/( - diff --git a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx index 6f47071..75b3812 100644 --- a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx +++ b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx @@ -1,7 +1,7 @@ import { presentationGraph, visibleEdges } from './presentation-graph.js'; import { overviewSections, sectionSvg } from './architecture-overview.js'; import React, { useId } from 'react'; -import { BaseEdge, EdgeLabelRenderer, Handle, MarkerType, Position } from '@xyflow/react'; +import { BaseEdge, EdgeLabelRenderer, Handle, MarkerType, Position, useStore } from '@xyflow/react'; import SelectionOutline from './SelectionOutline.jsx'; import { renderNode } from './node-svg.js'; import { compactCards, getDiagram, hasArrow, edgeMarkers } from './diagrams/registry.js'; @@ -29,10 +29,14 @@ function NodeHandles({ sequence = false }) { ; } +// Cards whose body text would read under 10px on screen draw only their name, enlarged (diagrams/card.js summaryCard). +// The boolean subscription redraws a card only when zoom crosses that point, not on every zoom step. +const SUMMARY_TYPES = new Set(['architecture', 'deployment']); function DiagramNode({ data, selected }) { const moduleColor = data.moduleColors?.get(data.module); - const markup = renderNode({ ...data, position: { x: 0, y: 0 } }, data.diagramType, 0, 0, data.palette, data.locale, data.moduleColors); - return
+ const summary = useStore(state => SUMMARY_TYPES.has(data.diagramType) && state.transform[2] * TYPOGRAPHY.body < 10); + const markup = renderNode({ ...data, summary, position: { x: 0, y: 0 } }, data.diagramType, 0, 0, data.palette, data.locale, data.moduleColors); + return
{selected && } diff --git a/skills/q-flow/assets/viewer/src/diagrams/card.js b/skills/q-flow/assets/viewer/src/diagrams/card.js index f620f5e..c134f2c 100644 --- a/skills/q-flow/assets/viewer/src/diagrams/card.js +++ b/skills/q-flow/assets/viewer/src/diagrams/card.js @@ -1,8 +1,10 @@ -import { CARD, cardTag } from '../text-layout.js'; +import { CARD, cardTag, layoutText } from '../text-layout.js'; +import { TYPOGRAPHY } from '../visual-style.js'; import { cardTextLayout, text, coreNode, dataKinds, paint } from './drawing.js'; export function genericCard(node, x, y, fill, stroke, palette, locale, outline, contentInset = 0, corner = 0) { if (node.classicCard) return classicCard(node, x, y, fill, stroke, palette, locale, outline, contentInset); + if (node.summary) return summaryCard(node, x, y, fill, stroke, palette, locale, outline, contentInset, corner); const { title, subtitle, source, tag, chips, contentHeight } = cardTextLayout({ ...node, size: { ...node.size, width: node.size.width - contentInset * 2 } }, locale, false, corner); // Baselines sit 20/17/14px below the top of their 26/24/20px lines. const left = x + contentInset, row = y + Math.max(0, (node.size.height - contentHeight) / 2) + CARD.pad, column = left + CARD.textX; @@ -16,6 +18,23 @@ export function genericCard(node, x, y, fill, stroke, palette, locale, outline, return `${frame(node, x, y, fill, stroke, outline)}${iconPlate(node, plate.x, plate.y, CARD.plate, palette)}${text(tagX + tag.width / 2, row + 18, tag.text, 'stereotype', ' text-anchor="middle"')}${titleText}${subtitleText}${sourceText}${chipText}`; } +// Zoomed out (DiagramCanvas sets node.summary when card body text would read under 10px): the same frame, icon and kind +// tag, and only the name, enlarged up to 1.8x as far as the card holds it and centred below the tag row. Size, layout and +// exports are untouched; zooming in restores the full card. +function summaryCard(node, x, y, fill, stroke, palette, locale, outline, contentInset, corner) { + const tag = cardTag(node, locale), left = x + contentInset, width = node.size.width - contentInset * 2 - 2 * CARD.pad; + const top = y + CARD.pad + CARD.titleLine, room = node.size.height - 2 * CARD.pad - CARD.titleLine; + let title; + for (let scale = 1.8; scale >= 1; scale -= .1) { + title = layoutText(node.label, width, TYPOGRAPHY.title * scale, CARD.titleLine * scale); + if (title.height <= room) break; + } + const size = title.lineHeight / CARD.titleLine * TYPOGRAPHY.title, first = top + (room - title.height) / 2 + title.lineHeight * .77; + const titleText = title.lines.map((line, index) => text(left + CARD.pad + width / 2, first + index * title.lineHeight, line, 'title', ` text-anchor="middle" style="font-size:${size}px"`)).join(''); + const plate = { x: left + CARD.pad, y: y + CARD.pad + (CARD.titleLine - CARD.plate) / 2 }, tagX = x + node.size.width - contentInset - CARD.pad - tag.width - corner; + return `${frame(node, x, y, fill, stroke, outline)}${iconPlate(node, plate.x, plate.y, CARD.plate, palette)}${text(tagX + tag.width / 2, y + CARD.pad + 18, tag.text, 'stereotype', ' text-anchor="middle"')}${titleText}`; +} + const frame = (node, x, y, fill, stroke, outline) => paint(outline(node, x, y), { fill, stroke, 'stroke-width': node.appearance?.moduleColor || node.appearance?.ring ? 1.5 : 1 }); // The icon plate is the identity chip: solid module color with a white glyph. Without a module it stays a quiet plate diff --git a/skills/q-flow/assets/viewer/src/styles.css b/skills/q-flow/assets/viewer/src/styles.css index 431b7c5..336195c 100644 --- a/skills/q-flow/assets/viewer/src/styles.css +++ b/skills/q-flow/assets/viewer/src/styles.css @@ -415,7 +415,8 @@ button:disabled { cursor: not-allowed; } .fragment-visual { color: var(--label-2); overflow: visible; } -.layout-problems { position:absolute; top:calc(var(--tb-h) + 12px); left:50%; transform:translateX(-50%); z-index:21; width:min(420px,calc(100% - 112px)); max-height:35%; overflow:auto; padding:10px 14px; border:1px solid var(--sep); border-radius:10px; background:var(--material-thick); font-size:13px; } +/* Author-facing; the bottom strip is outside the reading area, so it never covers the fitted diagram. */ +.layout-problems { position:absolute; bottom:var(--gutter); left:50%; transform:translateX(-50%); z-index:21; width:min(420px,calc(100% - 112px)); max-height:35%; overflow:auto; padding:10px 14px; border:1px solid var(--sep); border-radius:10px; background:var(--material-thick); font-size:13px; } .layout-problems summary { cursor:pointer; } .layout-problems button { text-align:left; overflow-wrap:anywhere; } .layout-problems pre { white-space:pre-wrap; overflow-wrap:anywhere; font-size:12px; } diff --git a/skills/q-flow/scripts/browser-interactions.mjs b/skills/q-flow/scripts/browser-interactions.mjs index e576c37..4dfcebe 100644 --- a/skills/q-flow/scripts/browser-interactions.mjs +++ b/skills/q-flow/scripts/browser-interactions.mjs @@ -429,7 +429,10 @@ async function assertNodeDrawing(page, graph, colorTheme) { assert.equal(await page.locator(`[data-edge-id=${JSON.stringify(id)}] .pair-label`).innerText(), pair.label); } for (const node of graph.nodes) { - const expected = renderNode({ ...node, classicCard: !compactCards(graph), executionRects: sequenceExecutions(graph).filter(item => item.participantId === node.id).map(item => ({ ...item, x: item.x - node.position.x, y: item.y - node.position.y, color: sequenceGroupColor(sequencePairs(graph).get(item.start.edgeId), palette) ?? palette.edge })) }, graph.meta.diagramType, -node.position.x, -node.position.y, palette, graph.meta.locale, moduleColors); + // Zoomed out, cards draw their summary (diagrams/card.js): the page states which drawing it shows, and the shared + // renderer must produce exactly that one. + const summary = await nodeElement(page, node.id).locator('.diagram-node').getAttribute('data-summary') === 'true'; + const expected = renderNode({ ...node, summary, classicCard: !compactCards(graph), executionRects: sequenceExecutions(graph).filter(item => item.participantId === node.id).map(item => ({ ...item, x: item.x - node.position.x, y: item.y - node.position.y, color: sequenceGroupColor(sequencePairs(graph).get(item.start.edgeId), palette) ?? palette.edge })) }, graph.meta.diagramType, -node.position.x, -node.position.y, palette, graph.meta.locale, moduleColors); const same = await nodeElement(page, node.id).locator('.node-drawing').evaluate((element, xml) => { const expected = new DOMParser().parseFromString(`${xml}`, 'image/svg+xml').querySelector('.node-drawing'); // Compare parsed DOMs: serialization differences must not hide drawing differences. @@ -1369,7 +1372,8 @@ async function nodePointerTarget(page, node) { if (!point) { const shift = await element.evaluate(element => { const node = element.getBoundingClientRect(), banner = document.querySelector('.layout-problems')?.getBoundingClientRect(); - return banner && node.left < banner.right && node.right > banner.left && node.top < banner.bottom && node.bottom > banner.top ? banner.bottom - node.top + 24 : 0; + // The banner sits at the bottom of the canvas: lift a node it covers above it. + return banner && node.left < banner.right && node.right > banner.left && node.top < banner.bottom && node.bottom > banner.top ? banner.top - node.bottom - 24 : 0; }); if (shift) { const blank = await blankPoint(page); From a22c77b18de6937dc68601256fdc766703e19d31 Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 8 Nov 2026 18:25:05 +0800 Subject: [PATCH 14/16] =?UTF-8?q?refactor(architecture):=20=E6=9E=B6?= =?UTF-8?q?=E6=9E=84=E5=9B=BE=E5=8F=AA=E4=BF=9D=E7=95=99=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=E5=85=B3=E7=B3=BB=E8=A7=86=E5=9B=BE=EF=BC=8CREADME=20=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E4=B8=AD=E6=96=87=E4=B8=BB=E6=96=87=E4=BB=B6=E5=B9=B6?= =?UTF-8?q?=E5=8F=AA=E7=95=99=E4=B8=AD=E8=8B=B1=E4=B8=A4=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除平台能力、工程分层两种总览视图及其代码,图类型变为 9 种 - validate --fix 把旧总览图转成组件关系图:分区转归属分组、overviewText 并入 facts、说明分区并入要点,去掉几何后提示用 --layout auto 重排;不加 --fix 时校验报错并给出指引 - 示例、技能文档、浏览器矩阵与测试同步为九种视图,新增迁移测试 - README.md 改为中文,英文移到 README.en.md;删除其余 5 种语言的 README 和安装指南 --- .codex-plugin/plugin.json | 2 +- .github/workflows/publish-github-npm.yml | 2 +- README.en.md | 303 ++++++++++ README.md | 226 ++++---- docs/clients.de.md | 74 --- docs/clients.es.md | 74 --- docs/clients.ja.md | 74 --- docs/clients.md | 4 +- docs/clients.pt.md | 74 --- docs/clients.ru.md | 74 --- docs/clients.zh-CN.md | 4 +- docs/distribution.md | 2 +- docs/pages/index.html | 4 +- docs/readme/README.de.md | 317 ---------- docs/readme/README.es.md | 317 ---------- docs/readme/README.ja.md | 317 ---------- docs/readme/README.pt.md | 317 ---------- docs/readme/README.ru.md | 317 ---------- docs/readme/README.zh-CN.md | 317 ---------- examples/jeepay/README.md | 4 +- examples/jeepay/capabilities.graph.json | 270 --------- examples/jeepay/collection.graph.json | 547 ------------------ examples/jeepay/engineering.graph.json | 277 --------- examples/jeepay/source.json | 10 - package.json | 4 +- scripts/refresh-jeepay-fixtures.mjs | 2 - skills/q-flow/SKILL.md | 6 +- skills/q-flow/agents/openai.yaml | 2 +- skills/q-flow/assets/viewer-dist/index.html | 30 +- .../assets/viewer/src/DiagramCanvas.jsx | 8 +- .../q-flow/assets/viewer/src/TextEditor.jsx | 16 +- .../q-flow/assets/viewer/src/ViewerShell.jsx | 11 +- .../viewer/src/architecture-overview-theme.js | 22 - .../viewer/src/architecture-overview.js | 341 ----------- .../viewer/src/diagrams/architecture.js | 5 +- .../assets/viewer/src/diagrams/registry.js | 3 +- .../q-flow/assets/viewer/src/edge-routing.js | 5 +- skills/q-flow/assets/viewer/src/export-svg.js | 4 +- .../assets/viewer/src/features/download.js | 12 +- .../viewer/src/features/useGraphLayout.js | 51 +- .../viewer/src/features/usePresentation.js | 2 +- .../viewer/src/features/useSelection.js | 3 +- .../assets/viewer/src/graph-validation.js | 31 +- .../assets/viewer/src/i18n-messages.json | 64 -- .../viewer/src/layout-browser-worker.js | 6 +- .../assets/viewer/src/layout-measure.js | 2 - .../assets/viewer/src/layout-quality.js | 6 +- .../assets/viewer/src/layout-refinement.js | 7 +- .../assets/viewer/src/layout-templates.js | 2 - skills/q-flow/assets/viewer/src/node-svg.js | 2 +- .../assets/viewer/src/orthogonal-routing.js | 8 +- .../assets/viewer/src/presentation-graph.js | 27 +- .../assets/viewer/src/route-clearance.js | 5 +- skills/q-flow/assets/viewer/src/search.js | 2 +- .../q-flow/assets/viewer/src/session-graph.js | 2 +- skills/q-flow/assets/viewer/src/styles.css | 5 +- .../q-flow/assets/viewer/src/view-identity.js | 13 +- .../q-flow/assets/viewer/src/visual-style.js | 3 - skills/q-flow/references/graph-schema.md | 8 +- skills/q-flow/references/guided-intake.md | 16 +- skills/q-flow/references/layout-routing.md | 16 +- .../q-flow/references/types/architecture.md | 37 +- .../q-flow/references/viewer-development.md | 14 +- skills/q-flow/references/visual-contract.md | 4 +- .../q-flow/scripts/browser-interactions.mjs | 155 +---- .../scripts/compact-architecture.test.mjs | 18 - skills/q-flow/scripts/compile-layout.mjs | 12 +- skills/q-flow/scripts/joint-layout.test.mjs | 9 - .../scripts/layout-cancellation.test.mjs | 16 +- .../q-flow/scripts/routing-clearance.test.mjs | 8 - skills/q-flow/scripts/validate-fix.test.mjs | 31 + skills/q-flow/scripts/validate-graph.mjs | 69 ++- tests/jeepay-corpus.test.mjs | 4 +- tests/jeepay-generation.test.mjs | 6 +- tests/jeepay-pages.test.mjs | 2 +- tests/open-source-hygiene.test.mjs | 8 +- tests/plugin-package.test.mjs | 13 +- tests/viewer-locale.test.mjs | 2 +- 78 files changed, 682 insertions(+), 4405 deletions(-) create mode 100644 README.en.md delete mode 100644 docs/clients.de.md delete mode 100644 docs/clients.es.md delete mode 100644 docs/clients.ja.md delete mode 100644 docs/clients.pt.md delete mode 100644 docs/clients.ru.md delete mode 100644 docs/readme/README.de.md delete mode 100644 docs/readme/README.es.md delete mode 100644 docs/readme/README.ja.md delete mode 100644 docs/readme/README.pt.md delete mode 100644 docs/readme/README.ru.md delete mode 100644 docs/readme/README.zh-CN.md delete mode 100644 examples/jeepay/capabilities.graph.json delete mode 100644 examples/jeepay/engineering.graph.json delete mode 100644 skills/q-flow/assets/viewer/src/architecture-overview-theme.js delete mode 100644 skills/q-flow/assets/viewer/src/architecture-overview.js diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index ed7646b..e9f97f9 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -8,7 +8,7 @@ "skills": "./skills/", "interface": { "displayName": "QGraphFlow", - "shortDescription": "Architecture and flow diagrams: eleven kinds of interactive software diagrams from source, configuration and documents", + "shortDescription": "Architecture and flow diagrams: nine kinds of interactive software diagrams from source, configuration and documents", "longDescription": "Generate flow, architecture, sequence, ER, deployment, class, state, use-case and data-flow diagrams from CodeGraph or raw repository evidence; deliver an offline HTML viewer and an auditable graph.json with in-page SVG and PNG download.", "developerName": "Max Zheng", "category": "Productivity", diff --git a/.github/workflows/publish-github-npm.yml b/.github/workflows/publish-github-npm.yml index 8d20fef..726a417 100644 --- a/.github/workflows/publish-github-npm.yml +++ b/.github/workflows/publish-github-npm.yml @@ -52,7 +52,7 @@ jobs: node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/validate-graph.mjs examples/jeepay/flowchart.graph.json --input-only node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/flowchart.graph.json output/order # Generate the complete real-source Jeepay collection with the installed package. - node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/eleven + node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay - uses: actions/setup-node@v7 with: node-version: '22' diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..3a13240 --- /dev/null +++ b/README.en.md @@ -0,0 +1,303 @@ +
+ +

QGraphFlow

+ +### Turn complex code into diagrams you can explore. + +Follow the path. Inspect the evidence. Share one offline file. + +💡 Inspired by Cocoon-AI/architecture-diagram-generator — thanks to the original author for the idea. + +[中文](README.md) · [English](README.en.md) + +[Live demo](https://supermax92.github.io/qgraphflow/) · [Getting started](#getting-started) · [Client installation](#installation-guide) · [Report an issue](https://github.com/supermax92/qgraphflow/issues) · [MIT](LICENSE) + +
+ +*Nine diagram types: component relationship architecture, flowchart, sequence, ER, deployment, class, state, use case and data flow.* + +QGraphFlow turns source code, schemas, configuration and requirements into interactive software diagrams, with evidence you can inspect and an offline HTML file you can share. + +**What sets it apart:** nine diagram types from one skill, an evidence kind on every relationship and the source line behind each code-backed one, automatic layout, editing in the page, and no network requests from the plugin scripts or the Viewer itself. + +![Jeepay multi-view interaction demo: component relationship architecture, sequence and ER diagrams](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) + +Using real Jeepay source code, switch between component relationship architecture, sequence and ER diagrams to explore components and call relationships. [View full-size GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) + +**Complex sequence diagram showcase** + +![Complex sequence diagram drawn step by step: participants, lifelines, messages, activation bars and nested combined fragments](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) + +A fictional e-commerce scenario contains 9 participants, 29 messages and 6 combined fragments, covering stock retries, nested branches, parallel processing, failure compensation and asynchronous callbacks. The animation progressively reveals the generated diagram to show its structure and details. [View full-size GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) + +```bash +npx skills add supermax92/qgraphflow +``` + +One command installs the skill for Claude Code, Codex, Cursor and Qoder; the [installation guide](#installation-guide) covers the plugin installations and the other clients. + +- **Explore:** search, zoom and pan; inspect responsibilities and upstream/downstream relationships. + +- **Verify:** inspect nodes and edges for source files, lines, symbols and explicitly marked uncertainty. + +- **Edit:** unlock the layout, change text and move elements; reset when needed. + +- **Share:** open offline HTML or export the complete diagram as SVG / PNG. + +The real-source [Jeepay corpus](examples/jeepay) contains all nine views used by CI and the live demo. + +## Getting started + +After installation, open your application project in the client and select the `q-flow` skill. These examples use Claude Code's `/q-flow`; in Codex, use the `$q-flow` or `$qgraphflow:q-flow` entry actually provided by your client. Not installed yet? Read the [installation guide](#installation-guide) first. + +### 1. Empty input: Not sure where to start + +Invoke the skill without adding a request: + +```text +/q-flow +``` + +The skill guides you to choose the part to analyze and the question the diagram should answer. Drawing starts once the necessary information is clear. + +### 2. Ask about capabilities: Learn what it can draw + +```text +/q-flow What types of diagrams can you draw? What questions does each type answer? I have just taken over a project; introduce your capabilities and suggest a starting point. +``` + +Learn what the nine diagram types are for, then decide whether to explore project structure, call order, data relationships or something else. + +### 3. Vague input: Only a general goal + +```text +/q-flow Help me draw this project. I want to understand it as quickly as possible. +``` + +You do not need to specify a diagram type first. The skill selects a suitable view based on the project and your goal, and asks follow-up questions when necessary information is missing. + +### 4. Precise input: Define the scope and request drawing details + +Replace the business names and steps below with flows that actually exist in your project: + +```text +/q-flow Analyze the order creation flow in the current project and generate a sequence diagram in Chinese. +Cover the request entry point, pricing, stock reservation, payment authorization and order persistence. +Retain the synchronous calls, asynchronous messages, paired returns, activation bars, conditional branches, retries and failure compensation that actually exist in the source. Do not omit details for brevity. +Mark the source files and line numbers for components and calls, and save the result to docs/qgraphflow/order-sequence/. +``` + +State the subject, question, level of detail and output location clearly to start directly. The diagram retains only facts supported by evidence. + +### 5. Refine further: Expand part of the previous diagram + +After the result is generated, continue in the same conversation: + +```text +/q-flow Expand the stock reservation step in the previous sequence diagram into a separate flowchart in Chinese. +Show all branches for stock validation, successful reservation, retryable failures, the retry limit and stock release. Follow the source code and add no steps absent from it. +``` + +Start with the overall picture, then explore one step in depth. You can also request more detail in an existing diagram or verify its relationships. + +## Installation guide + +You need Node.js 22 or later and a plugin-capable client with model access configured. + +### Quick install + +```bash +npx skills add supermax92/qgraphflow +``` + +Tested with `skills` 1.7.0 for Claude Code, Codex, Cursor and Qoder. It asks which clients to install to; `-a claude-code` names one, and `-g` installs for your user instead of the current project. The skill installs as `q-flow`, without the `qgraphflow:` prefix of the plugin installations below. + +To install it as a plugin instead, follow the steps below. [Qoder Desktop](#qoder-desktop) users can install from the marketplace and skip step 1. + +### 1. Download the plugin + +Get the plugin from npmjs.com; no account, login or token is needed. Create a separate directory outside your application project: + +```bash +mkdir qgraphflow-install +cd qgraphflow-install +npm install qgraphflow --ignore-scripts +cd node_modules/qgraphflow +``` + +You are now in the plugin root. **Downloading through npm does not automatically install the plugin in your client;** continue with step 2. The package also provides the `qgraphflow` command used in [Keep diagrams in sync with code](#keep-diagrams-in-sync-with-code). + +Run the following terminal commands from **the plugin root containing `skills/`**. + +### 2. Install in your client + +#### Codex App / CLI + +Codex CLI must be installed and available in your terminal: + +```bash +codex plugin marketplace add . +codex plugin add qgraphflow@supermax92 +``` + +Start a new session, type `$`, and select `qgraphflow:q-flow`. + +#### Claude Code + +```bash +claude plugin marketplace add ./ +claude plugin install qgraphflow@supermax92 --scope user +``` + +Start a new session and enter `/q-flow` (or the fully qualified `/qgraphflow:q-flow`). + +#### Qoder CLI + +```bash +qodercli plugins install . +``` + +Start a new session and select `q-flow`. + +#### Qoder Desktop + +**Recommended:** Open **Settings → Plugins → Marketplace**, search for **QGraphFlow** or **代码图谱可视化**, and install the plugin. Start a new session and select `q-flow`. + +For local installation, complete step 1, then open **Settings → Plugins → Custom → Import** and import the complete plugin root directory. Start a new session and select `q-flow`. + +#### Cursor + +Copy everything in the plugin root, including hidden files, into: + +```text +~/.cursor/plugins/local/qgraphflow/ +``` + +Confirm that `.cursor-plugin/plugin.json` exists there, reload the window, and find `q-flow` in **Customize**. Back up any previous version first; do not mix old and new files. + +### 3. Start using it + +Open your application project in the client, start a new session and select the skill. Describe your request using the [Getting started](#getting-started) examples. Open the generated HTML in your browser. + +Building it yourself? See the [source build instructions](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). + +## Quick usage + +These examples use `$qgraphflow:q-flow` in Codex. If your client shows `$q-flow`, select that entry instead. For other clients, use the skill entry described above. + +**Not sure where to begin?** Invoke the skill and choose the subject and question when prompted. + +```text +$qgraphflow:q-flow +``` + +**Already have a goal?** Say which part to draw and what you want to understand. You do not need to choose a diagram type first. + +### Example 1: Understand the architecture + +```text +$qgraphflow:q-flow Analyze the current project and generate an architecture diagram in Chinese, showing the responsibilities of the main modules, dependencies and system boundaries. +``` + +Useful when joining a project and learning its overall structure. + +### Example 2: Trace a business flow + +```text +$qgraphflow:q-flow Analyze order creation and generate a sequence diagram in Chinese, showing the call order for pricing, stock reservation, payment and order persistence, and mark failure branches. +``` + +Replace order creation and its steps with your project's actual flow. Continue in the same conversation: + +```text +$qgraphflow:q-flow Expand the stock reservation step in the previous diagram into a separate flowchart in Chinese, showing success and failure handling. +``` + +Results go under `docs/qgraphflow/` by default. Open `index.html` to explore, edit and export; `graph.json` retains the graph data. Each view is also written as an SVG (`diagram.svg`, or `diagram--.svg` for several views) that you can embed as an image in a README, pull request or wiki. + +After editing in the page, **More → Save changes** in Chrome or Edge rewrites the page, `graph.json` and the SVGs in place once you pick the diagram's folder. Other browsers save `graph.json` only: put it in the folder and regenerate the page and SVGs with `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. + +
+Run the nine-view Jeepay source example + +Select your Jeepay source checkout to verify the evidence: + +```bash +export JEEPAY_REPO_ROOT="" +node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" +node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" +``` + +Open `output/jeepay/index.html`; its nine SVGs are in the same directory. See the [corpus README](examples/jeepay) for the source revision and refresh procedure. + +
+ +## Keep diagrams in sync with code + +A diagram generated with a repository root records where each component is defined, the line behind each code-backed relationship (a call, a foreign key) and a fingerprint of every file it points into. Validating it with `--repo-root` lets lines that only moved pass and fails when the code behind the diagram changed: a recorded line was rewritten, a call was removed, new code touches a drawn component that no relationship covers, or a name the diagram uses is gone. The error shows the old and new code and names the elements and text to update. Add this job to your CI; it needs no build, login or token, and full history (`fetch-depth: 0`) lets it compare against those fingerprints: + +```yaml +name: Diagrams +on: [push, pull_request] +jobs: + diagrams: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: actions/setup-node@v7 + with: + node-version: '22' + - run: | + for graph in docs/qgraphflow/*/graph.json; do + npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } + done + exit ${failed:-0} +``` + +To see the impact on the pull request, add `--changes changes.md` to the validate line and post the file when it fails, for example `gh pr comment "$PR" --body-file changes.md` (needs `pull-requests: write`). It lists, per view, the elements each change touches, the file and line, and the old and new code. The page regenerated after `--fix` also marks those elements and lists the changes beside the key points. + +When it fails, ask the skill to refresh that diagram: + +```text +$qgraphflow:q-flow CI says docs/qgraphflow/order-sequence is out of date. Refresh it. +``` + +The skill realigns every anchor, lists each change in the graph's `meta.sourceDrift`, updates only the elements those items name and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. + +Add `--compare HEAD` when regenerating to see what a refresh changed: the page colors added and changed elements, lists removed ones beside the key points, and leaves `graph.json` untouched. + +## What each of the nine diagram types answers + +| View · PNG | Main question | Example scope | +| --- | --- | --- | +| Component relationship architecture | Which responsibility boundaries collaborate in the system? | Channels, transaction orchestration, pricing, risk, stock, payment, orders, events and fulfillment | +| Flowchart | How does each decision point branch and converge? | Stock shortage, risk rejection, compensation for payment failure and successful commit | +| Sequence | In what order does a request make calls and receive returns? | Successful checkout main flow and asynchronous OrderPaid | +| ER | How does core data relate? | Cart, orders, items, payments, stock reservations and parcels | +| Deployment | Where are runtime units placed and how are they connected? | Edge, Kubernetes, data services, payment and warehouse/logistics networks | +| Class | How do domain objects and code contracts depend on each other? | Checkout application service, Order and four ports | +| State | Which events and guards advance an order? | Payment, fulfillment, cancellation, refund and closure | +| Use case | What capabilities does each actor have? | Buyer, merchant, warehouse and customer support | +| Data flow | What transformations and stores do data assets pass through? | Cart, transaction decisions, order events, warehouse/logistics and delivery receipts | + +This is a concept model demonstrating QGraphFlow, not a particular e-commerce repository. The example `graph.json` invents no source paths and marks relationship evidence as `inference`. Real project diagrams need traceable source, DDL, configuration, tests and accepted requirements. + +## Develop and contribute + +```bash +npm ci --prefix skills/q-flow/assets/viewer +npm run build --prefix skills/q-flow/assets/viewer +node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs +``` + +Development needs Node.js 22 or later, npm, tar, zip and unzip. Include a minimal redacted graph, client/browser versions and reproduction steps in issue reports. + +Reference documentation (English): [Evidence sources](skills/q-flow/references/evidence-sources.md) · [Graph data format](skills/q-flow/references/graph-schema.md) · [Guided intake](skills/q-flow/references/guided-intake.md) · [Viewer development and acceptance](skills/q-flow/references/viewer-development.md) · [Visual conventions](skills/q-flow/references/visual-contract.md) + +## License and attribution + +[MIT](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md) + +QGraphFlow is an independent MIT-licensed project. The scenarios in this document are conceptual examples and do not represent any real company's production architecture. diff --git a/README.md b/README.md index 9fc816e..dcca9fd 100644 --- a/README.md +++ b/README.md @@ -2,121 +2,121 @@

QGraphFlow

-### Turn complex code into diagrams you can explore. +### 把复杂代码,变成可以探索的图。 -Follow the path. Inspect the evidence. Share one offline file. +跟随路径,查看证据,用一个离线文件分享。 -💡 Inspired by Cocoon-AI/architecture-diagram-generator — thanks to the original author for the idea. +💡 灵感来自 Cocoon-AI/architecture-diagram-generator,感谢原作者的启发。 -[English](README.md) · [中文](docs/readme/README.zh-CN.md) · [Русский](docs/readme/README.ru.md) · [Português](docs/readme/README.pt.md) · [日本語](docs/readme/README.ja.md) · [Deutsch](docs/readme/README.de.md) · [Español](docs/readme/README.es.md) +[中文](README.md) · [English](README.en.md) -[Live demo](https://supermax92.github.io/qgraphflow/) · [Getting started](#getting-started) · [Client installation](#installation-guide) · [Report an issue](https://github.com/supermax92/qgraphflow/issues) · [MIT](LICENSE) +[在线演示](https://supermax92.github.io/qgraphflow/) · [快速入门](#快速入门) · [客户端安装](#安装指南) · [反馈问题](https://github.com/supermax92/qgraphflow/issues) · [MIT](LICENSE)
-*Eleven diagram types: platform capability architecture, engineering layer architecture, component relationship architecture, flowchart, sequence, ER, deployment, class, state, use case and data flow.* +*支持九类图:【组件关系架构图、流程图、时序图、ER 图、部署图、类图、状态图、用例图、数据流图】* -QGraphFlow turns source code, schemas, configuration and requirements into interactive software diagrams, with evidence you can inspect and an offline HTML file you can share. +QGraphFlow 从源码、数据结构、配置和需求生成交互式软件图,让关系有据可查,并将结果交付为可分享的离线 HTML。 -**What sets it apart:** eleven diagram types from one skill, an evidence kind on every relationship and the source line behind each code-backed one, automatic layout, editing in the page, and no network requests from the plugin scripts or the Viewer itself. +**差异在哪:** 一个技能覆盖九类图,每条关系都标明证据类别,有代码支撑的关系还记录对应的源码行,自动布局,能直接在页面里编辑,插件脚本和 Viewer 本身不发任何网络请求。 -![Jeepay multi-view interaction demo: component relationship architecture, sequence and ER diagrams](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) +![Jeepay 多视图交互演示:组件关系架构图、时序图与 ER 图](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.zh-CN.hero.gif) -Using real Jeepay source code, switch between component relationship architecture, sequence and ER diagrams to explore components and call relationships. [View full-size GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) +以 Jeepay 真实源码为例,在组件关系架构图、时序图与 ER 图之间切换,探索组件与调用关系。[查看原尺寸 GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.zh-CN.hero.gif) -**Complex sequence diagram showcase** +**复杂时序图展示** -![Complex sequence diagram drawn step by step: participants, lifelines, messages, activation bars and nested combined fragments](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) +![复杂时序图逐步绘制:参与者、生命线、消息、激活条与嵌套组合片段](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.zh-CN.sequence-drawing.gif) -A fictional e-commerce scenario contains 9 participants, 29 messages and 6 combined fragments, covering stock retries, nested branches, parallel processing, failure compensation and asynchronous callbacks. The animation progressively reveals the generated diagram to show its structure and details. [View full-size GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) +虚构电商场景包含 9 个参与者、29 条消息和 6 个组合片段,覆盖库存重试、嵌套分支、并行处理、失败补偿与异步回调。动画逐步呈现已生成的图形,展示复杂时序图的结构与细节。[查看原尺寸 GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.zh-CN.sequence-drawing.gif) ```bash npx skills add supermax92/qgraphflow ``` -One command installs the skill for Claude Code, Codex, Cursor and Qoder; the [installation guide](#installation-guide) covers the plugin installations and the other clients. +一条命令即可为 Claude Code、Codex、Cursor 和 Qoder 装好技能;以插件方式安装和其他客户端见[安装指南](#安装指南)。 -- **Explore:** search, zoom and pan; inspect responsibilities and upstream/downstream relationships. +- **探索:** 搜索定位、缩放和平移画布,查看组件职责与上下游关系。 -- **Verify:** inspect nodes and edges for source files, lines, symbols and explicitly marked uncertainty. +- **核验:** 从节点或连线查看详情,核对源码文件、行号、符号和明确标注的不确定性。 -- **Edit:** unlock the layout, change text and move elements; reset when needed. +- **编辑:** 解锁后修改文字、移动元素;不满意时一键重置。 -- **Share:** open offline HTML or export the complete diagram as SVG / PNG. +- **分享:** 打开离线 HTML,或将完整图导出为 SVG / PNG。 -The real-source [Jeepay corpus](examples/jeepay) contains all eleven views used by CI and the live demo. +基于真实源码的 [Jeepay 语料](examples/jeepay)包含 CI 和在线演示用到的全部九个视图。 -## Getting started +## 快速入门 -After installation, open your application project in the client and select the `q-flow` skill. These examples use Claude Code's `/q-flow`; in Codex, use the `$q-flow` or `$qgraphflow:q-flow` entry actually provided by your client. Not installed yet? Read the [installation guide](#installation-guide) first. +安装后,在客户端打开你的业务项目,选择 `q-flow` 技能。以下以 Claude Code 的 `/q-flow` 为例;Codex 中使用客户端实际提供的 `$q-flow` 或 `$qgraphflow:q-flow` 入口。还未安装?先看[安装指南](#安装指南)。 -### 1. Empty input: Not sure where to start +### 1. 空白输入:不知道从哪里开始 -Invoke the skill without adding a request: +只调用技能,不附加需求: ```text /q-flow ``` -The skill guides you to choose the part to analyze and the question the diagram should answer. Drawing starts once the necessary information is clear. +技能会引导你选择要分析的部分,以及希望图回答的问题;必要信息明确后开始绘图。 -### 2. Ask about capabilities: Learn what it can draw +### 2. 询问能力:先了解能画什么 ```text -/q-flow What types of diagrams can you draw? What questions does each type answer? I have just taken over a project; introduce your capabilities and suggest a starting point. +/q-flow 你能绘制哪些类型的图?每类图适合回答什么问题?我刚接手一个项目,请先介绍能力并建议一个起点。 ``` -Learn what the eleven diagram types are for, then decide whether to explore project structure, call order, data relationships or something else. +先了解九类图的用途,再决定看项目结构、调用顺序、数据关系还是其他内容。 -### 3. Vague input: Only a general goal +### 3. 模糊输入:只有一个大致目标 ```text -/q-flow Help me draw this project. I want to understand it as quickly as possible. +/q-flow 帮我画一下这个项目,我想尽快看懂它。 ``` -You do not need to specify a diagram type first. The skill selects a suitable view based on the project and your goal, and asks follow-up questions when necessary information is missing. +不用先指定图类型。技能会根据项目和你的目标确定合适的视图,缺少必要信息时再追问。 -### 4. Precise input: Define the scope and request drawing details +### 4. 精准输入:明确范围并要求绘制细节 -Replace the business names and steps below with flows that actually exist in your project: +将下面的业务名称和步骤替换成项目中实际存在的流程: ```text -/q-flow Analyze the order creation flow in the current project and generate a sequence diagram in Chinese. -Cover the request entry point, pricing, stock reservation, payment authorization and order persistence. -Retain the synchronous calls, asynchronous messages, paired returns, activation bars, conditional branches, retries and failure compensation that actually exist in the source. Do not omit details for brevity. -Mark the source files and line numbers for components and calls, and save the result to docs/qgraphflow/order-sequence/. +/q-flow 分析当前项目的订单创建流程,生成中文时序图。 +覆盖请求入口、价格计算、库存预占、支付授权和订单落库。 +保留源码中实际存在的同步调用、异步消息、成对返回、激活条、条件分支、重试和失败补偿,不要为了简洁省略细节。 +标明组件与调用的源码文件和行号,将结果保存到 docs/qgraphflow/order-sequence/。 ``` -State the subject, question, level of detail and output location clearly to start directly. The diagram retains only facts supported by evidence. +把对象、问题、详细程度和输出位置说清楚,就能直接开始;图中只保留有证据支持的事实。 -### 5. Refine further: Expand part of the previous diagram +### 5. 继续细化:展开上一张图的局部 -After the result is generated, continue in the same conversation: +在生成结果后,于同一对话中继续: ```text -/q-flow Expand the stock reservation step in the previous sequence diagram into a separate flowchart in Chinese. -Show all branches for stock validation, successful reservation, retryable failures, the retry limit and stock release. Follow the source code and add no steps absent from it. +/q-flow 展开上一张时序图中的库存预占步骤,单独生成中文流程图。 +完整展示库存校验、预占成功、可重试失败、重试上限和释放库存的分支,以源码为准,不添加代码中没有的步骤。 ``` -Start with the overall picture, then explore one step in depth. You can also request more detail in an existing diagram or verify its relationships. +先看整体,再深入一个步骤;也可以继续要求补充已有图的细节或核验其中的关系。 -## Installation guide +## 安装指南 -You need Node.js 22 or later and a plugin-capable client with model access configured. +准备 Node.js 22 及以上版本,以及已配置好模型访问、支持插件功能的客户端。 -### Quick install +### 快速安装 ```bash npx skills add supermax92/qgraphflow ``` -Tested with `skills` 1.7.0 for Claude Code, Codex, Cursor and Qoder. It asks which clients to install to; `-a claude-code` names one, and `-g` installs for your user instead of the current project. The skill installs as `q-flow`, without the `qgraphflow:` prefix of the plugin installations below. +已用 `skills` 1.7.0 在 Claude Code、Codex、Cursor 和 Qoder 上实测。命令会询问装到哪些客户端;`-a claude-code` 可直接指定,`-g` 改为装到当前用户而不是当前项目。这样装上的技能名是 `q-flow`,不带下文插件安装方式里的 `qgraphflow:` 前缀。 -To install it as a plugin instead, follow the steps below. [Qoder Desktop](#qoder-desktop) users can install from the marketplace and skip step 1. +如需以插件方式安装,按以下步骤操作。[Qoder Desktop](#qoder-desktop) 可直接从插件商城安装,跳过第 1 步。 -### 1. Download the plugin +### 1. 下载插件 -Get the plugin from npmjs.com; no account, login or token is needed. Create a separate directory outside your application project: +从 npmjs.com 获取插件,无需账号、登录或令牌。在业务项目之外创建独立目录: ```bash mkdir qgraphflow-install @@ -125,22 +125,22 @@ npm install qgraphflow --ignore-scripts cd node_modules/qgraphflow ``` -You are now in the plugin root. **Downloading through npm does not automatically install the plugin in your client;** continue with step 2. The package also provides the `qgraphflow` command used in [Keep diagrams in sync with code](#keep-diagrams-in-sync-with-code). +此时已进入插件根目录。**npm 下载不会自动完成客户端安装**,请继续第 2 步。这个包还提供 `qgraphflow` 命令,[让图和代码保持同步](#让图和代码保持同步)一节会用到。 -Run the following terminal commands from **the plugin root containing `skills/`**. +以下终端命令均在**包含 `skills/` 的插件根目录**执行。 -### 2. Install in your client +### 2. 选择客户端安装 #### Codex App / CLI -Codex CLI must be installed and available in your terminal: +终端需已安装 Codex CLI: ```bash codex plugin marketplace add . codex plugin add qgraphflow@supermax92 ``` -Start a new session, type `$`, and select `qgraphflow:q-flow`. +新建会话,输入 `$`,选择 `qgraphflow:q-flow`。 #### Claude Code @@ -149,7 +149,7 @@ claude plugin marketplace add ./ claude plugin install qgraphflow@supermax92 --scope user ``` -Start a new session and enter `/q-flow` (or the fully qualified `/qgraphflow:q-flow`). +新建会话,输入 `/q-flow`(或完整名称 `/qgraphflow:q-flow`)。 #### Qoder CLI @@ -157,70 +157,70 @@ Start a new session and enter `/q-flow` (or the fully qualified `/qgraphflow:q-f qodercli plugins install . ``` -Start a new session and select `q-flow`. +新建会话,选择 `q-flow`。 #### Qoder Desktop -**Recommended:** Open **Settings → Plugins → Marketplace**, search for **QGraphFlow** or **代码图谱可视化**, and install the plugin. Start a new session and select `q-flow`. +**推荐:**打开 **Settings → Plugins → Marketplace**,搜索 **QGraphFlow** 或 **代码图谱可视化**,安装插件。新建会话,选择 `q-flow`。 -For local installation, complete step 1, then open **Settings → Plugins → Custom → Import** and import the complete plugin root directory. Start a new session and select `q-flow`. +如需本地安装,先完成第 1 步,再打开 **Settings → Plugins → Custom → Import**,导入完整的插件根目录。新建会话,选择 `q-flow`。 #### Cursor -Copy everything in the plugin root, including hidden files, into: +将插件根目录中的全部内容(含隐藏文件)复制到: ```text ~/.cursor/plugins/local/qgraphflow/ ``` -Confirm that `.cursor-plugin/plugin.json` exists there, reload the window, and find `q-flow` in **Customize**. Back up any previous version first; do not mix old and new files. +确认其中存在 `.cursor-plugin/plugin.json`,重新加载窗口,在 **Customize** 中找到 `q-flow`。若已有旧版本,先备份,勿混合新旧文件。 -### 3. Start using it +### 3. 开始使用 -Open your application project in the client, start a new session and select the skill. Describe your request using the [Getting started](#getting-started) examples. Open the generated HTML in your browser. +在客户端打开你的业务项目,新建会话并选择技能,按[快速入门](#快速入门)中的示例描述需求。生成后,用浏览器打开输出的 HTML。 -Building it yourself? See the [source build instructions](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). +需要自行构建?参见[源码构建说明](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)。 -## Quick usage +## 快速使用 -These examples use `$qgraphflow:q-flow` in Codex. If your client shows `$q-flow`, select that entry instead. For other clients, use the skill entry described above. +以下以 Codex 的 `$qgraphflow:q-flow` 入口为例;如果客户端显示 `$q-flow`,请选择它实际提供的入口。其他客户端使用上方对应的技能入口。 -**Not sure where to begin?** Invoke the skill and choose the subject and question when prompted. +**不知道从哪里开始?** 直接调用,按提示选择要分析的部分和想了解的问题。 ```text $qgraphflow:q-flow ``` -**Already have a goal?** Say which part to draw and what you want to understand. You do not need to choose a diagram type first. +**目标已经明确?** 一句话说明“画哪个部分+想看什么”,无需先选择图类型。 -### Example 1: Understand the architecture +### 示例一:看懂项目架构 ```text -$qgraphflow:q-flow Analyze the current project and generate an architecture diagram in Chinese, showing the responsibilities of the main modules, dependencies and system boundaries. +$qgraphflow:q-flow 分析当前项目,生成中文架构图,展示主要模块的职责、依赖关系和系统边界。 ``` -Useful when joining a project and learning its overall structure. +适合初次接触项目,先了解整体结构。 -### Example 2: Trace a business flow +### 示例二:追踪业务调用 ```text -$qgraphflow:q-flow Analyze order creation and generate a sequence diagram in Chinese, showing the call order for pricing, stock reservation, payment and order persistence, and mark failure branches. +$qgraphflow:q-flow 分析订单创建流程,生成中文时序图,展示价格计算、库存预占、支付和订单落库的调用顺序,并标明失败分支。 ``` -Replace order creation and its steps with your project's actual flow. Continue in the same conversation: +将“订单创建”及相关步骤替换成项目中的实际业务流程。看完后,在同一对话中继续追问: ```text -$qgraphflow:q-flow Expand the stock reservation step in the previous diagram into a separate flowchart in Chinese, showing success and failure handling. +$qgraphflow:q-flow 展开上一张图中的库存预占步骤,单独生成中文流程图,展示成功与失败的处理流程。 ``` -Results go under `docs/qgraphflow/` by default. Open `index.html` to explore, edit and export; `graph.json` retains the graph data. Each view is also written as an SVG (`diagram.svg`, or `diagram--.svg` for several views) that you can embed as an image in a README, pull request or wiki. +结果默认保存在 `docs/qgraphflow/` 下:打开 `index.html` 即可交互查看、编辑和导出,`graph.json` 保留图数据。每个视图还会写出一份 SVG(`diagram.svg`,多视图时为 `diagram--.svg`),可以直接作为图片嵌进 README、PR 或 Wiki。 -After editing in the page, **More → Save changes** in Chrome or Edge rewrites the page, `graph.json` and the SVGs in place once you pick the diagram's folder. Other browsers save `graph.json` only: put it in the folder and regenerate the page and SVGs with `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. +在页面里编辑后,用 Chrome 或 Edge 执行「更多 → 保存修改」并选一次图所在的文件夹,即可原地重写页面、`graph.json` 和 SVG。其他浏览器只能保存 `graph.json`:把它放回该文件夹,再用 `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` 重新生成页面和 SVG。
-Run the eleven-view Jeepay source example +运行基于 Jeepay 源码的九视图示例 -Select your Jeepay source checkout to verify the evidence: +指定本机的 Jeepay 源码目录来核验证据: ```bash export JEEPAY_REPO_ROOT="" @@ -228,13 +228,13 @@ node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.j node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" ``` -Open `output/jeepay/index.html`; its eleven SVGs are in the same directory. See the [corpus README](examples/jeepay) for the source revision and refresh procedure. +打开 `output/jeepay/index.html`,九个 SVG 在同一目录。源码版本和刷新步骤见[语料 README](examples/jeepay)。
-## Keep diagrams in sync with code +## 让图和代码保持同步 -A diagram generated with a repository root records where each component is defined, the line behind each code-backed relationship (a call, a foreign key) and a fingerprint of every file it points into. Validating it with `--repo-root` lets lines that only moved pass and fails when the code behind the diagram changed: a recorded line was rewritten, a call was removed, new code touches a drawn component that no relationship covers, or a name the diagram uses is gone. The error shows the old and new code and names the elements and text to update. Add this job to your CI; it needs no build, login or token, and full history (`fetch-depth: 0`) lets it compare against those fingerprints: +带仓库根目录生成的图会记下每个组件定义在哪里、每条有代码支撑的关系所在的那一行(调用、外键等),以及它指向的每个文件的内容指纹。用 `--repo-root` 校验时,只是挪了位置的行会自动对上、照常通过;只有图背后的代码真的变了才会失败:记录的那一行被改写、某个调用被删掉、新代码碰到了图里画的组件却没有对应的关系,或者图里用到的名字已经不存在。错误里会给出改动前后的代码,并指出要更新的元素和文字。把下面这个任务加进 CI,不需要构建、登录或令牌;拉取完整历史(`fetch-depth: 0`)才能和这些指纹比对: ```yaml name: Diagrams @@ -256,37 +256,35 @@ jobs: exit ${failed:-0} ``` -To see the impact on the pull request, add `--changes changes.md` to the validate line and post the file when it fails, for example `gh pr comment "$PR" --body-file changes.md` (needs `pull-requests: write`). It lists, per view, the elements each change touches, the file and line, and the old and new code. The page regenerated after `--fix` also marks those elements and lists the changes beside the key points. +想在 PR 里直接看到受影响的地方,就在 validate 那一行加上 `--changes changes.md`,失败时把这个文件贴成评论,例如 `gh pr comment "$PR" --body-file changes.md`(需要 `pull-requests: write` 权限)。它按视图列出每处改动碰到的元素、文件和行号,以及改动前后的代码。执行 `--fix` 后重新生成的页面也会标出这些元素,并在要点旁列出这些改动。 -When it fails, ask the skill to refresh that diagram: +失败后,让技能刷新这张图: ```text -$qgraphflow:q-flow CI says docs/qgraphflow/order-sequence is out of date. Refresh it. +$qgraphflow:q-flow CI 提示 docs/qgraphflow/order-sequence 的图过时了,刷新一下。 ``` -The skill realigns every anchor, lists each change in the graph's `meta.sourceDrift`, updates only the elements those items name and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. +技能会把所有锚点对齐到当前代码,把每处改动列进图的 `meta.sourceDrift`,只更新这些条目指出的元素,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 -Add `--compare HEAD` when regenerating to see what a refresh changed: the page colors added and changed elements, lists removed ones beside the key points, and leaves `graph.json` untouched. +重新生成时加上 `--compare HEAD`,就能看出这次刷新改了什么:页面把新增和改动的元素着色,在要点旁列出删掉的元素,`graph.json` 不受影响。 -## What each of the eleven diagram types answers +## 九类图各自回答什么 -| View · PNG | Main question | Example scope | +| 视图 · PNG | 主要问题 | 本示例范围 | | --- | --- | --- | -| Platform capability architecture | What capabilities does the platform provide? | Capability zones and matrices | -| Engineering layer architecture | How is the engineering code organized? | Engineering layers and shared support | -| Component relationship architecture | Which responsibility boundaries collaborate in the system? | Channels, transaction orchestration, pricing, risk, stock, payment, orders, events and fulfillment | -| Flowchart | How does each decision point branch and converge? | Stock shortage, risk rejection, compensation for payment failure and successful commit | -| Sequence | In what order does a request make calls and receive returns? | Successful checkout main flow and asynchronous OrderPaid | -| ER | How does core data relate? | Cart, orders, items, payments, stock reservations and parcels | -| Deployment | Where are runtime units placed and how are they connected? | Edge, Kubernetes, data services, payment and warehouse/logistics networks | -| Class | How do domain objects and code contracts depend on each other? | Checkout application service, Order and four ports | -| State | Which events and guards advance an order? | Payment, fulfillment, cancellation, refund and closure | -| Use case | What capabilities does each actor have? | Buyer, merchant, warehouse and customer support | -| Data flow | What transformations and stores do data assets pass through? | Cart, transaction decisions, order events, warehouse/logistics and delivery receipts | - -This is a concept model demonstrating QGraphFlow, not a particular e-commerce repository. The example `graph.json` invents no source paths and marks relationship evidence as `inference`. Real project diagrams need traceable source, DDL, configuration, tests and accepted requirements. - -## Develop and contribute +| 组件关系架构图 | 系统由哪些责任边界协作? | 渠道、交易编排、价格、风控、库存、支付、订单、事件与履约 | +| 流程图 | 每个决策点如何分支和收敛? | 缺货、风控拒绝、支付失败补偿与成功提交 | +| 时序图 | 一次请求按什么顺序调用和返回? | 成功结算主链及异步 OrderPaid | +| ER 图 | 核心数据如何关联? | 购物车、订单、明细、支付、库存预占和包裹 | +| 部署图 | 运行单元放在哪里、怎样连接? | 边缘、Kubernetes、数据服务、支付和仓配网络 | +| 类图 | 领域对象和代码契约怎样依赖? | Checkout 应用服务、Order 与四个端口 | +| 状态图 | 订单受哪些事件和守卫条件推进? | 支付、履约、取消、退款和关闭 | +| 用例图 | 每类参与者拥有哪些能力? | 买家、商家、仓库与客服 | +| 数据流图 | 数据资产经过哪些变换和存储? | 购物车、交易决策、订单事件、仓配和物流回执 | + +这是用于展示 QGraphFlow 能力的概念模型,不对应某个电商仓库。`graph.json` 不伪造源码路径,关系证据统一标记为 `inference`;对真实项目绘图时,应改用源码、DDL、配置、测试和已接受需求中的可追溯证据。 + +## 开发与参与 ```bash npm ci --prefix skills/q-flow/assets/viewer @@ -294,24 +292,12 @@ npm run build --prefix skills/q-flow/assets/viewer node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs ``` -Development needs Node.js 22 or later, npm, tar, zip and unzip. Include a minimal redacted graph, client/browser versions and reproduction steps in issue reports. - -Reference documentation (English): [Evidence sources](skills/q-flow/references/evidence-sources.md) · [Graph data format](skills/q-flow/references/graph-schema.md) · [Guided intake](skills/q-flow/references/guided-intake.md) · [Viewer development and acceptance](skills/q-flow/references/viewer-development.md) · [Visual conventions](skills/q-flow/references/visual-contract.md) - -## License and attribution +开发需要 Node.js 22 及以上版本、npm、tar、zip 和 unzip。反馈问题时,请附最小脱敏图数据、客户端和浏览器版本,以及复现步骤。 -[MIT](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md) +参考文档(英文):[证据来源](skills/q-flow/references/evidence-sources.md) · [图数据格式](skills/q-flow/references/graph-schema.md) · [需求引导](skills/q-flow/references/guided-intake.md) · [Viewer 开发与验收](skills/q-flow/references/viewer-development.md) · [图形表达约定](skills/q-flow/references/visual-contract.md) -QGraphFlow is an independent MIT-licensed project. The scenarios in this document are conceptual examples and do not represent any real company's production architecture. +## 许可证与归属 -## Architecture overviews - -Architecture now includes component relations, platform capabilities and engineering layers. Describe the subject and question; the skill chooses the template. Requested collections can contain multiple architecture views with independent edits. - -```text -$qgraphflow:q-flow Analyze this project's platform capabilities and business integration methods, and generate a platform capability overview in Chinese. -$qgraphflow:q-flow Analyze the organization and component layers of the current project, and generate Chinese overviews of the whole project and a cross-section of one component. -$qgraphflow:q-flow Generate an English platform capability overview of this project and show how application modules integrate. -``` +[MIT](LICENSE) · [第三方声明](THIRD_PARTY_NOTICES.md) -See [examples/jeepay](examples/jeepay) for real-source platform, engineering and component relationship architecture views. Unlock an overview to reorder cards within a layer or edit text. Save keeps all views; reset restores only the current one. +QGraphFlow 是采用 MIT 许可证的独立项目。本文场景为概念示例,不代表任何真实公司的生产架构。 diff --git a/docs/clients.de.md b/docs/clients.de.md deleted file mode 100644 index 8524f03..0000000 --- a/docs/clients.de.md +++ /dev/null @@ -1,74 +0,0 @@ -# Installationsanleitung - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Zurück zur README](readme/README.de.md) - -Qoder Desktop kann das Plugin aus dem Marketplace installieren; dann entfällt Schritt 1 (siehe den Abschnitt unten). Die übrigen Clients installieren das Plugin-Paket von npmjs.com. - -Du benötigst Node.js 22 oder neuer (mit npm) und einen Client mit eingerichtetem Modellzugriff. - -## Schnellinstallation - -```bash -npx skills add supermax92/qgraphflow -``` - -Installiert den Skill `q-flow` für Claude Code, Codex, Cursor und Qoder (getestet mit `skills` 1.7.0) und fragt, in welche Clients installiert werden soll. Für die Installation als Plugin den folgenden Schritten folgen. - -## 1. Plugin über npm herunterladen - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Lege das Verzeichnis außerhalb deines Anwendungsprojekts an; Konto, Anmeldung oder Token sind nicht nötig. Danach befindest du dich im Plugin-Stammverzeichnis. Der Download über npm installiert das Plugin nicht im Client; fahre mit Schritt 2 fort. Um noch nicht veröffentlichten Code zu installieren, siehe die [Anleitung zum Bauen aus dem Quellcode](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Im Client installieren - -Führe die folgenden Befehle im Plugin-Stammverzeichnis aus Schritt 1 (`qgraphflow-install/node_modules/qgraphflow`) aus, nicht im Verzeichnis deines eigenen Anwendungsprojekts. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Hier registriert `marketplace add` nur eine lokale Installationsquelle; eine Veröffentlichung im öffentlichen Marktplatz ist nicht erforderlich. Siehe die [offizielle OpenAI-Dokumentation](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Starte eine neue Sitzung, gib `$` ein und wähle `qgraphflow:q-flow` aus (verwende den tatsächlich im Client angezeigten Namen). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Starte eine neue Sitzung und gib `/q-flow` (oder den vollständigen Namen `/qgraphflow:q-flow`) ein. - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Starte eine neue Sitzung und wähle `q-flow` aus. - -### Qoder Desktop - -**Empfohlen:** Öffne **Settings → Plugins → Marketplace**, suche nach **QGraphFlow** oder **代码图谱可视化** und installiere das Plugin. Starte eine neue Sitzung und wähle `q-flow`. - -Für eine lokale Installation führe zuerst Schritt 1 aus. Öffne dann **Settings → Plugins → Custom → Import** und importiere das vollständige Plugin-Stammverzeichnis. Lade den Client neu und wähle `q-flow`. - -### Cursor - -Kopiere den gesamten Inhalt des Plugin-Stammverzeichnisses, einschließlich versteckter Dateien, nach `~/.cursor/plugins/local/qgraphflow/`. Sichere ein vorhandenes Verzeichnis zuerst; vermische keine alten und neuen Dateien. - -Prüfe, ob das Manifest unter `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json` liegt. Lade das Fenster neu und wähle unter Customize → Plugins / Skills den Skill `q-flow` aus. - -Diese lokale Methode wurde mit Cursor 3.19.13 getestet. Prüfe bei anderen Versionen, ob Plugin und Skill angezeigt werden. diff --git a/docs/clients.es.md b/docs/clients.es.md deleted file mode 100644 index a537a04..0000000 --- a/docs/clients.es.md +++ /dev/null @@ -1,74 +0,0 @@ -# Guía de instalación - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Volver al README](readme/README.es.md) - -Qoder Desktop permite instalar el complemento desde su Marketplace y omitir el paso 1 (consulta su sección más abajo). Los demás clientes instalan el paquete del complemento obtenido de npmjs.com. - -Necesitas Node.js 22 o posterior (con npm) y un cliente con acceso al modelo configurado. - -## Instalación rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Instala la habilidad `q-flow` en Claude Code, Codex, Cursor y Qoder (probado con `skills` 1.7.0) y pregunta en qué clientes instalar. Para instalar el complemento, sigue los pasos siguientes. - -## 1. Descargar el complemento con npm - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Crea el directorio fuera del proyecto de tu aplicación; no se necesita cuenta, inicio de sesión ni token. Ahora estás en la raíz del complemento. La descarga mediante npm no instala el complemento en el cliente; continúa con el paso 2. Para instalar código aún no publicado, consulta las [instrucciones de compilación desde el código fuente](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Instalar en el cliente - -Ejecuta los siguientes comandos desde la raíz del complemento a la que entraste en el paso 1 (`qgraphflow-install/node_modules/qgraphflow`), no desde el directorio de tu propio proyecto. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Aquí, `marketplace add` solo registra una fuente de instalación local; no requiere publicar el complemento en un marketplace público. Consulta la [documentación oficial de OpenAI](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Inicia una sesión nueva, escribe `$` y selecciona `qgraphflow:q-flow` (usa el nombre que muestre tu cliente). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Inicia una sesión nueva y escribe `/q-flow` (o el nombre completo `/qgraphflow:q-flow`). - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Inicia una sesión nueva y selecciona `q-flow`. - -### Qoder Desktop - -**Recomendado:** Abre **Settings → Plugins → Marketplace**, busca **QGraphFlow** o **代码图谱可视化** e instala el complemento. Inicia una sesión nueva y selecciona `q-flow`. - -Para una instalación local, completa primero el paso 1. Después abre **Settings → Plugins → Custom → Import** e importa el directorio raíz completo del complemento. Recarga el cliente y selecciona `q-flow`. - -### Cursor - -Copia todo el contenido de la raíz del complemento, incluidos los archivos ocultos, a `~/.cursor/plugins/local/qgraphflow/`. Si el directorio ya existe, haz una copia de seguridad antes; no mezcles archivos antiguos y nuevos. - -Comprueba que el manifiesto esté en `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json`. Recarga la ventana y selecciona `q-flow` en Customize → Plugins / Skills. - -Este método local se probó en Cursor 3.19.13. En otras versiones, comprueba que aparezcan tanto el complemento como la habilidad. diff --git a/docs/clients.ja.md b/docs/clients.ja.md deleted file mode 100644 index cff8b35..0000000 --- a/docs/clients.ja.md +++ /dev/null @@ -1,74 +0,0 @@ -# インストールガイド - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[README に戻る](readme/README.ja.md) - -Qoder Desktop ではマーケットプレイスからインストールでき、手順 1 は不要です(下記の該当項を参照)。その他のクライアントでは、npmjs.com から取得したプラグインパッケージをインストールします。 - -Node.js 22 以降(npm を含む)と、モデルへのアクセスを設定済みのクライアントが必要です。 - -## クイックインストール - -```bash -npx skills add supermax92/qgraphflow -``` - -Claude Code、Codex、Cursor、Qoder にスキル `q-flow` を導入します(`skills` 1.7.0 で実測済み)。導入先のクライアントを尋ねられます。プラグインとして導入する場合は、次の手順に従ってください。 - -## 1. npm からプラグインをダウンロード - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -ディレクトリは業務プロジェクトの外に作成します。アカウント、ログイン、トークンは不要です。これでプラグインのルートディレクトリに移動できました。npm でダウンロードしてもクライアントへのインストールは自動では行われないため、手順 2 に進んでください。未リリースのコードをインストールする場合は、[ソースからのビルド手順](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)を参照してください。 - -## 2. クライアントにインストール - -以下のコマンドは、自分の業務プロジェクトではなく、手順 1 で移動したプラグインのルートディレクトリ(`qgraphflow-install/node_modules/qgraphflow`)で実行します。 - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -ここでの `marketplace add` はローカルのインストール元を登録するだけで、公開マーケットプレイスへの掲載は不要です。[OpenAI 公式ドキュメント](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli)を参照してください。 - -新しいセッションを開始し、`$` を入力して `qgraphflow:q-flow` を選択します(クライアントに実際に表示される名前を使用してください)。 - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -新しいセッションを開始し、`/q-flow`(または完全名 `/qgraphflow:q-flow`)を入力します。 - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -新しいセッションを開始し、`q-flow` を選択します。 - -### Qoder Desktop - -**推奨:** **Settings → Plugins → Marketplace** を開き、**QGraphFlow** または **代码图谱可视化** を検索してインストールします。新しいセッションを開始し、`q-flow` を選択します。 - -ローカルインストールの場合は手順 1 を完了し、**Settings → Plugins → Custom → Import** を開いて、プラグインのルートディレクトリ全体をインポートします。再読み込み後、`q-flow` を選択します。 - -### Cursor - -プラグインのルートディレクトリの内容を隠しファイルも含めてすべて `~/.cursor/plugins/local/qgraphflow/` にコピーします。既存のディレクトリがある場合は先にバックアップし、新旧のファイルを混在させないでください。 - -マニフェストが `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json` にあることを確認します。ウィンドウを再読み込みし、Customize → Plugins / Skills で `q-flow` を選択します。 - -このローカル方式は Cursor 3.19.13 で検証済みです。他のバージョンでは、プラグインとスキルが表示されることを確認してください。 diff --git a/docs/clients.md b/docs/clients.md index 4308b01..3bee4ab 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -1,8 +1,8 @@ # Installation guide -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) +[English](clients.md) · [中文](clients.zh-CN.md) -[Back to README](../README.md) +[Back to README](../README.en.md) Qoder Desktop can install the plugin from its marketplace and skip step 1 (see its section below). The other clients install the plugin package from npmjs.com. diff --git a/docs/clients.pt.md b/docs/clients.pt.md deleted file mode 100644 index be22326..0000000 --- a/docs/clients.pt.md +++ /dev/null @@ -1,74 +0,0 @@ -# Guia de instalação - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Voltar ao README](readme/README.pt.md) - -O Qoder Desktop pode instalar o plugin pelo Marketplace e pular a etapa 1 (veja a seção correspondente abaixo). Os demais clientes instalam o pacote do plugin obtido no npmjs.com. - -Você precisa de Node.js 22 ou posterior (com npm) e de um cliente com acesso ao modelo configurado. - -## Instalação rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Instala a habilidade `q-flow` no Claude Code, Codex, Cursor e Qoder (testado com `skills` 1.7.0) e pergunta em quais clientes instalar. Para instalar o plugin, siga as etapas abaixo. - -## 1. Baixar o plugin pelo npm - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Crie o diretório fora do projeto da sua aplicação; não é preciso conta, login nem token. Agora você está na raiz do plugin. Baixar pelo npm não instala o plugin no cliente; continue na etapa 2. Para instalar código ainda não lançado, consulte as [instruções de compilação a partir do código-fonte](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Instalar no cliente - -Execute os comandos abaixo na raiz do plugin aberta na etapa 1 (`qgraphflow-install/node_modules/qgraphflow`), não no diretório do seu próprio projeto. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Aqui, `marketplace add` apenas registra uma fonte de instalação local; não exige publicação em um marketplace público. Consulte a [documentação oficial da OpenAI](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Inicie uma nova sessão, digite `$` e selecione `qgraphflow:q-flow` (use o nome exibido pelo seu cliente). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Inicie uma nova sessão e digite `/q-flow` (ou o nome completo `/qgraphflow:q-flow`). - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Inicie uma nova sessão e selecione `q-flow`. - -### Qoder Desktop - -**Recomendado:** Abra **Settings → Plugins → Marketplace**, pesquise **QGraphFlow** ou **代码图谱可视化** e instale o plugin. Inicie uma nova sessão e selecione `q-flow`. - -Para uma instalação local, conclua primeiro a etapa 1. Depois, abra **Settings → Plugins → Custom → Import** e importe o diretório raiz completo do plugin. Recarregue o cliente e selecione `q-flow`. - -### Cursor - -Copie todo o conteúdo da raiz do plugin, incluindo arquivos ocultos, para `~/.cursor/plugins/local/qgraphflow/`. Se o diretório já existir, faça um backup antes; não misture arquivos antigos e novos. - -Confirme que o manifesto está em `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json`. Recarregue a janela e selecione `q-flow` em Customize → Plugins / Skills. - -Esse método local foi testado no Cursor 3.19.13. Em outras versões, confirme que o plugin e a habilidade aparecem. diff --git a/docs/clients.ru.md b/docs/clients.ru.md deleted file mode 100644 index ade4691..0000000 --- a/docs/clients.ru.md +++ /dev/null @@ -1,74 +0,0 @@ -# Руководство по установке - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Вернуться к README](readme/README.ru.md) - -В Qoder Desktop плагин можно установить из Marketplace и пропустить шаг 1 (см. соответствующий раздел ниже). Остальные клиенты устанавливают пакет плагина с npmjs.com. - -Нужны Node.js 22 или новее (с npm) и клиент с настроенным доступом к модели. - -## Быстрая установка - -```bash -npx skills add supermax92/qgraphflow -``` - -Устанавливает навык `q-flow` для Claude Code, Codex, Cursor и Qoder (проверено с `skills` 1.7.0) и спрашивает, в какие клиенты устанавливать. Чтобы установить плагин, выполните шаги ниже. - -## 1. Скачать плагин из npm - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Создайте каталог вне своего рабочего проекта; учётная запись, вход и токен не нужны. Теперь вы в корневом каталоге плагина. Загрузка через npm не устанавливает плагин в клиент — перейдите к шагу 2. Чтобы установить ещё не выпущенный код, см. [инструкции по сборке из исходников](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Установить в клиент - -Выполняйте команды ниже из корневого каталога плагина, в который вы перешли на шаге 1 (`qgraphflow-install/node_modules/qgraphflow`), а не из каталога вашего приложения. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Здесь `marketplace add` только регистрирует локальный источник установки; публикация в маркетплейсе не требуется. См. [официальную документацию OpenAI](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Начните новый сеанс, введите `$` и выберите `qgraphflow:q-flow` (используйте имя, которое показывает ваш клиент). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Начните новый сеанс и введите `/q-flow` (или полное имя `/qgraphflow:q-flow`). - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Начните новый сеанс и выберите `q-flow`. - -### Qoder Desktop - -**Рекомендуется:** Откройте **Settings → Plugins → Marketplace**, найдите **QGraphFlow** или **代码图谱可视化** и установите плагин. Начните новый сеанс и выберите `q-flow`. - -Для локальной установки выполните шаг 1, затем откройте **Settings → Plugins → Custom → Import** и импортируйте весь корневой каталог плагина. Перезагрузите клиент и выберите `q-flow`. - -### Cursor - -Скопируйте всё содержимое корневого каталога плагина, включая скрытые файлы, в `~/.cursor/plugins/local/qgraphflow/`. Если каталог уже существует, сначала сделайте резервную копию; не смешивайте старые и новые файлы. - -Убедитесь, что манифест находится по адресу `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json`. Перезагрузите окно и выберите `q-flow` в Customize → Plugins / Skills. - -Этот способ локальной установки проверялся в Cursor 3.19.13. В других версиях убедитесь, что плагин и навык отображаются. diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 5f2290e..607e648 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -1,8 +1,8 @@ # 安装指南 -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) +[English](clients.md) · [中文](clients.zh-CN.md) -[返回 README](readme/README.zh-CN.md) +[返回 README](../README.md) Qoder Desktop 可从插件商城安装,跳过第 1 步(见下方对应小节)。其他客户端安装从 npmjs.com 下载的插件包。 diff --git a/docs/distribution.md b/docs/distribution.md index 9773e8a..dc0b003 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -42,7 +42,7 @@ Track marketplace releases separately from GitHub Releases and npm packages. For ## Online demo -`.github/workflows/pages.yml` checks out the Jeepay revision recorded in `examples/jeepay/source.json`, builds all eleven coordinate-free views with the committed prebuilt Viewer and verifies their source anchors with `--repo-root`. It serves `site/jeepay/zh-CN/` and uses `docs/pages/index.html` as the home page. The page folder also serves its `graph.json` and SVGs. +`.github/workflows/pages.yml` checks out the Jeepay revision recorded in `examples/jeepay/source.json`, builds all nine coordinate-free views with the committed prebuilt Viewer and verifies their source anchors with `--repo-root`. It serves `site/jeepay/zh-CN/` and uses `docs/pages/index.html` as the home page. The page folder also serves its `graph.json` and SVGs. Pull requests that touch the examples, the generator, the prebuilt Viewer, `docs/pages/` or the workflow run the build as a smoke test; pushes to `main` also deploy it. The site is uploaded as a Pages artifact and never enters a branch, and a failed build leaves the previous deployment online. Before the first deployment, set **Settings → Pages → Build and deployment → Source** to **GitHub Actions**. diff --git a/docs/pages/index.html b/docs/pages/index.html index d68d15d..8cf3ced 100644 --- a/docs/pages/index.html +++ b/docs/pages/index.html @@ -14,8 +14,8 @@

QGraphFlow

-

以 Jeepay 公开源码、Maven 配置、DDL 和 Compose 为依据,查看十一类可追溯的软件图形。

-打开 Jeepay 十一类图平台能力、工程分层、组件关系、流程、时序、ER、部署、类、状态、用例和数据流。可搜索、编辑、核验来源并导出。 +

以 Jeepay 公开源码、Maven 配置、DDL 和 Compose 为依据,查看九类可追溯的软件图形。

+打开 Jeepay 九类图组件关系、流程、时序、ER、部署、类、状态、用例和数据流。可搜索、编辑、核验来源并导出。

这些图展示源码和配置声明;容器运行及支付渠道接入状态未作验证。

项目源码与安装说明 diff --git a/docs/readme/README.de.md b/docs/readme/README.de.md deleted file mode 100644 index 3c905bc..0000000 --- a/docs/readme/README.de.md +++ /dev/null @@ -1,317 +0,0 @@ -
- -

QGraphFlow

- -### Aus komplexem Code werden Diagramme zum Erkunden. - -Pfade verfolgen. Belege prüfen. Eine Offline-Datei teilen. - -💡 Inspiriert von Cocoon-AI/architecture-diagram-generator – vielen Dank für die Anregung. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Online-Demo](https://supermax92.github.io/qgraphflow/) · [Erste Schritte](#erste-schritte) · [Client-Installation](#installationsanleitung) · [Problem melden](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Elf Diagrammarten: Plattformfähigkeitsarchitektur, Architektur der Engineering-Schichten, Komponentenbeziehungsarchitektur, Flussdiagramm, Sequenz, ER, Bereitstellung, Klasse, Zustand, Anwendungsfall und Datenfluss.* - -QGraphFlow erzeugt interaktive Softwarediagramme aus Quellcode, Datenstrukturen, Konfiguration und Anforderungen. Beziehungen bleiben überprüfbar; das Ergebnis lässt sich als Offline-HTML teilen. - -**Was es auszeichnet:** elf Diagrammarten in einem Skill, eine Belegart für jede Beziehung und die Quellzeile hinter jeder durch Code gestützten, automatisches Layout, Bearbeiten direkt auf der Seite und keine Netzwerkanfragen von den Plugin-Skripten oder dem Viewer selbst. - -![Interaktive Jeepay-Demo mit mehreren Ansichten: Komponentenbeziehungsarchitektur, Sequenz- und ER-Diagramme](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Wechsle anhand des echten Jeepay-Quellcodes zwischen Komponentenbeziehungsarchitektur, Sequenz- und ER-Diagrammen, um Komponenten und Aufrufbeziehungen zu erkunden. [GIF in Originalgröße ansehen](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Präsentation eines komplexen Sequenzdiagramms** - -![Schrittweises Zeichnen eines komplexen Sequenzdiagramms: Teilnehmer, Lebenslinien, Nachrichten, Aktivierungsbalken und verschachtelte kombinierte Fragmente](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Ein fiktives E-Commerce-Szenario enthält 9 Teilnehmer, 29 Nachrichten und 6 kombinierte Fragmente mit Bestandswiederholungen, verschachtelten Zweigen, paralleler Verarbeitung, Fehlerkompensation und asynchronen Rückrufen. Die Animation zeigt das erzeugte Diagramm schrittweise und macht seine Struktur und Details sichtbar. [GIF in Originalgröße ansehen](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Ein Befehl installiert den Skill für Claude Code, Codex, Cursor und Qoder; die Installation als Plugin und weitere Clients beschreibt die [Installationsanleitung](#installationsanleitung). - -- **Erkunden:** suchen, zoomen und verschieben; Verantwortlichkeiten sowie ein- und ausgehende Beziehungen verstehen. - -- **Prüfen:** Dateien, Zeilen, Symbole und ausdrücklich gekennzeichnete Unsicherheiten an Knoten und Kanten untersuchen. - -- **Bearbeiten:** Layout entsperren, Texte ändern und Elemente verschieben; bei Bedarf zurücksetzen. - -- **Teilen:** Offline-HTML öffnen oder das vollständige Diagramm als SVG / PNG exportieren. - -Der auf echtem Quellcode beruhende [Jeepay-Korpus](../../examples/jeepay) enthält alle elf Ansichten, die CI und die Online-Demo verwenden. - -## Erste Schritte - -Öffne nach der Installation dein Geschäftsprojekt im Client und wähle den Skill `q-flow`. Die Beispiele verwenden `/q-flow` in Claude Code; in Codex verwendest du den Eintrag `$q-flow` oder `$qgraphflow:q-flow`, den dein Client tatsächlich anbietet. Noch nicht installiert? Lies zuerst die [Installationsanleitung](#installationsanleitung). - -### 1. Leere Eingabe: Du weißt nicht, wo du anfangen sollst - -Rufe den Skill ohne zusätzliche Anforderungen auf: - -```text -/q-flow -``` - -Der Skill hilft dir, den zu analysierenden Teil und die Frage auszuwählen, die das Diagramm beantworten soll. Sobald die nötigen Informationen geklärt sind, beginnt das Zeichnen. - -### 2. Nach Fähigkeiten fragen: Erfahren, was er zeichnen kann - -```text -/q-flow Welche Diagrammarten kannst du zeichnen? Welche Fragen beantwortet jede Art? Ich habe gerade ein Projekt übernommen; stelle deine Fähigkeiten vor und schlage einen Einstieg vor. -``` - -Lerne zuerst die Einsatzgebiete der elf Diagrammarten kennen. Entscheide dann, ob du Projektstruktur, Aufrufreihenfolge, Datenbeziehungen oder etwas anderes betrachten möchtest. - -### 3. Vage Eingabe: Nur ein grobes Ziel - -```text -/q-flow Hilf mir, dieses Projekt zu zeichnen. Ich möchte es möglichst schnell verstehen. -``` - -Du musst vorher keine Diagrammart angeben. Der Skill bestimmt anhand des Projekts und deines Ziels eine passende Ansicht und fragt nach, wenn notwendige Informationen fehlen. - -### 4. Präzise Eingabe: Umfang festlegen und Zeichnungsdetails anfordern - -Ersetze die folgenden Geschäftsbegriffe und Schritte durch Abläufe, die tatsächlich in deinem Projekt vorkommen: - -```text -/q-flow Analysiere die Bestellerstellung im aktuellen Projekt und erzeuge ein Sequenzdiagramm auf Chinesisch. -Berücksichtige den Anfrageeingang, die Preisberechnung, Bestandsreservierung, Zahlungsautorisierung und Speicherung der Bestellung. -Erhalte die synchronen Aufrufe, asynchronen Nachrichten, gepaarten Rückgaben, Aktivierungsbalken, bedingten Zweige, Wiederholungen und Fehlerkompensationen, die tatsächlich im Quellcode vorkommen. Lasse keine Details zugunsten der Kürze weg. -Kennzeichne Quelldateien und Zeilennummern der Komponenten und Aufrufe und speichere das Ergebnis unter docs/qgraphflow/order-sequence/. -``` - -Benenne Gegenstand, Frage, Detailgrad und Ausgabeort klar, damit es direkt losgehen kann. Das Diagramm enthält nur durch Belege gestützte Fakten. - -### 5. Weiter verfeinern: Einen Teil des letzten Diagramms vertiefen - -Fahre nach der Erzeugung des Ergebnisses im selben Gespräch fort: - -```text -/q-flow Vertiefe die Bestandsreservierung aus dem letzten Sequenzdiagramm als separates Flussdiagramm auf Chinesisch. -Zeige sämtliche Zweige für Bestandsprüfung, erfolgreiche Reservierung, wiederholbare Fehler, Wiederholungslimit und Bestandsfreigabe. Halte dich an den Quellcode und füge keine dort fehlenden Schritte hinzu. -``` - -Betrachte zuerst das Ganze und vertiefe dann einen Schritt. Du kannst auch weitere Details für ein vorhandenes Diagramm anfordern oder seine Beziehungen prüfen. - -## Installationsanleitung - -Benötigt werden Node.js 22 oder neuer und ein Client mit Plugin-Unterstützung und eingerichtetem Modellzugriff. - -### Schnellinstallation - -```bash -npx skills add supermax92/qgraphflow -``` - -Getestet mit `skills` 1.7.0 für Claude Code, Codex, Cursor und Qoder. Der Befehl fragt, in welche Clients installiert werden soll; `-a claude-code` gibt einen direkt an, `-g` installiert für den eigenen Benutzer statt für das aktuelle Projekt. Der Skill heißt danach `q-flow`, ohne das Präfix `qgraphflow:` der Plugin-Installationen unten. - -Für die Installation als Plugin den folgenden Schritten folgen. [Qoder Desktop](#qoder-desktop) kann das Plugin direkt aus dem Marketplace installieren; Schritt 1 entfällt. - -### 1. Plugin herunterladen - -Das Plugin von npmjs.com beziehen, ohne Konto, Anmeldung oder Token. Ein eigenes Verzeichnis außerhalb des Anwendungsprojekts erstellen: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Nun befindet man sich im Plugin-Stammverzeichnis. **Der Download über npm installiert das Plugin nicht automatisch im Client;** mit Schritt 2 fortfahren. Das Paket stellt außerdem den Befehl `qgraphflow` bereit, den [Diagramme mit dem Code synchron halten](#diagramme-mit-dem-code-synchron-halten) verwendet. - -Alle folgenden Terminalbefehle im **Plugin-Stammverzeichnis mit `skills/`** ausführen. - -### 2. Im gewünschten Client installieren - -#### Codex App / CLI - -Codex CLI muss installiert und im Terminal verfügbar sein: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Eine neue Sitzung starten, `$` eingeben und `qgraphflow:q-flow` auswählen. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Eine neue Sitzung starten und `/q-flow` (oder den vollständigen Namen `/qgraphflow:q-flow`) eingeben. - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Eine neue Sitzung starten und `q-flow` auswählen. - -#### Qoder Desktop - -**Empfohlen:** Öffne **Settings → Plugins → Marketplace**, suche nach **QGraphFlow** oder **代码图谱可视化** und installiere das Plugin. Starte eine neue Sitzung und wähle `q-flow`. - -Für eine lokale Installation führe zuerst Schritt 1 aus. Öffne dann **Settings → Plugins → Custom → Import** und importiere das vollständige Plugin-Stammverzeichnis. Starte eine neue Sitzung und wähle `q-flow`. - -#### Cursor - -Den gesamten Inhalt des Plugin-Stammverzeichnisses einschließlich versteckter Dateien hierhin kopieren: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Prüfen, ob dort `.cursor-plugin/plugin.json` vorhanden ist, das Fenster neu laden und `q-flow` unter **Customize** suchen. Eine vorhandene ältere Version zuerst sichern; alte und neue Dateien nicht vermischen. - -### 3. Loslegen - -Öffne dein Geschäftsprojekt im Client, starte eine neue Sitzung und wähle den Skill. Beschreibe deine Anforderungen anhand der Beispiele unter [Erste Schritte](#erste-schritte). Öffne das erzeugte HTML im Browser. - -Selbst bauen? Siehe [Anleitung zum Bauen aus dem Quellcode](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Schnell verwenden - -Die Beispiele verwenden `$qgraphflow:q-flow` in Codex. Zeigt der Client `$q-flow`, diesen Eintrag wählen. In anderen Clients den oben beschriebenen Skill-Aufruf verwenden. - -**Noch kein Ausgangspunkt?** Den Skill aufrufen und auf Nachfrage Gegenstand und Fragestellung auswählen. - -```text -$qgraphflow:q-flow -``` - -**Das Ziel steht fest?** Beschreiben, welchen Teil das Diagramm zeigen und welche Frage es beantworten soll. Die Diagrammart muss nicht vorab gewählt werden. - -### Beispiel 1: Projektarchitektur verstehen - -```text -$qgraphflow:q-flow Analysiere dieses Projekt und erstelle ein chinesisches Architekturdiagramm mit Verantwortlichkeiten der Module, Abhängigkeiten und Systemgrenzen. -``` - -Geeignet, um sich erstmals einen Überblick über ein Projekt zu verschaffen. - -### Beispiel 2: Einen Geschäftsablauf verfolgen - -```text -$qgraphflow:q-flow Analysiere die Bestellerstellung und erstelle ein chinesisches Sequenzdiagramm für Preisberechnung, Bestandsreservierung, Zahlung und Speicherung der Bestellung, einschließlich Fehlerzweigen. -``` - -Bestellerstellung und Schritte durch den tatsächlichen Projektablauf ersetzen. Im selben Gespräch weiterfragen: - -```text -$qgraphflow:q-flow Vertiefe die Bestandsreservierung aus dem letzten Diagramm als separates chinesisches Flussdiagramm mit Erfolgs- und Fehlerbehandlung. -``` - -Ergebnisse landen standardmäßig unter `docs/qgraphflow/`. `index.html` zum Erkunden, Bearbeiten und Exportieren öffnen; `graph.json` enthält die Diagrammdaten. Jede Ansicht wird außerdem als SVG geschrieben (`diagram.svg`, bei mehreren Ansichten `diagram--.svg`), das sich als Bild in eine README, einen Pull Request oder ein Wiki einbinden lässt. - -Nach Änderungen auf der Seite schreibt **Mehr → Änderungen speichern** in Chrome oder Edge Seite, `graph.json` und SVGs direkt zurück, sobald der Diagrammordner einmal gewählt ist. Andere Browser speichern nur `graph.json`: die Datei in den Ordner legen und Seite und SVGs mit `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` neu erzeugen. - -
-Das Jeepay-Quellcodebeispiel mit elf Ansichten ausführen - -Wähle deine lokale Jeepay-Quellcodekopie, um die Belege zu prüfen: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Öffne `output/jeepay/index.html`; die elf SVGs liegen im selben Verzeichnis. Die Quellcoderevision und das Aktualisierungsverfahren stehen in der [Korpus-README](../../examples/jeepay). - -
- -## Diagramme mit dem Code synchron halten - -Ein mit Repository-Wurzel erzeugtes Diagramm hält fest, wo jede Komponente definiert ist, die Zeile hinter jeder durch Code gestützten Beziehung (ein Aufruf, ein Fremdschlüssel) und einen Fingerabdruck jeder Datei, auf die es verweist. Die Prüfung mit `--repo-root` lässt Zeilen, die nur verschoben wurden, passieren und schlägt fehl, wenn sich der Code hinter dem Diagramm geändert hat: Eine erfasste Zeile wurde umgeschrieben, ein Aufruf entfernt, neuer Code berührt eine gezeichnete Komponente ohne passende Beziehung, oder ein im Diagramm verwendeter Name ist verschwunden. Die Meldung zeigt alten und neuen Code und nennt die Elemente und Texte, die anzupassen sind. Diesen Job in die CI aufnehmen; er braucht keinen Build, keine Anmeldung und kein Token, und die vollständige Historie (`fetch-depth: 0`) erlaubt den Vergleich mit diesen Fingerabdrücken: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Um die Auswirkungen im Pull Request zu sehen, ergänzen Sie die validate-Zeile um `--changes changes.md` und posten die Datei bei einem Fehler als Kommentar, etwa mit `gh pr comment "$PR" --body-file changes.md` (benötigt `pull-requests: write`). Sie listet je Ansicht die Elemente, die jede Änderung berührt, Datei und Zeile sowie alten und neuen Code. Die nach `--fix` neu erzeugte Seite markiert diese Elemente ebenfalls und listet die Änderungen neben den Kernaussagen. - -Schlägt er fehl, den Skill bitten, dieses Diagramm zu aktualisieren: - -```text -$qgraphflow:q-flow Laut CI ist docs/qgraphflow/order-sequence veraltet. Bitte aktualisieren. -``` - -Der Skill richtet alle Anker am aktuellen Code aus, listet jede Änderung in `meta.sourceDrift` des Graphen, aktualisiert nur die dort genannten Elemente und erzeugt Seite und SVGs neu, wobei bearbeitete Positionen und Texte erhalten bleiben. Er zeichnet das Diagramm nicht neu. - -Mit `--compare HEAD` beim Neuerzeugen sehen Sie, was eine Aktualisierung geändert hat: Die Seite färbt hinzugefügte und geänderte Elemente, listet entfernte neben den Kernaussagen und lässt `graph.json` unverändert. - -## Welche Fragen die elf Diagrammarten beantworten - -| Ansicht · PNG | Hauptfrage | Umfang des Beispiels | -| --- | --- | --- | -| Plattformfähigkeitsarchitektur | Welche Fähigkeiten bietet die Plattform? | Fähigkeitsbereiche und Matrizen | -| Architektur der Engineering-Schichten | Wie ist der Projektcode organisiert? | Engineering-Schichten und gemeinsame Unterstützung | -| Komponentenbeziehungsarchitektur | Welche Verantwortungsgrenzen arbeiten im System zusammen? | Kanäle, Transaktionsorchestrierung, Preise, Risiko, Bestand, Zahlung, Bestellungen, Ereignisse und Auftragsabwicklung | -| Flussdiagramm | Wie verzweigt und vereinigt sich jeder Entscheidungspunkt? | Fehlbestand, Risikoablehnung, Kompensation bei Zahlungsfehlern und erfolgreicher Commit | -| Sequenz | In welcher Reihenfolge führt eine Anfrage Aufrufe aus und erhält Rückgaben? | Hauptpfad eines erfolgreichen Kaufabschlusses und asynchrones OrderPaid | -| ER | Wie hängen die Kerndaten zusammen? | Warenkorb, Bestellungen, Positionen, Zahlungen, Bestandsreservierungen und Pakete | -| Bereitstellung | Wo werden Laufzeiteinheiten platziert und wie sind sie verbunden? | Randnetz, Kubernetes, Datendienste, Zahlung und Lager-/Logistiknetze | -| Klasse | Wie hängen Domänenobjekte und Codeverträge voneinander ab? | Checkout-Anwendungsdienst, Order und vier Ports | -| Zustand | Welche Ereignisse und Wächterbedingungen treiben eine Bestellung voran? | Zahlung, Auftragsabwicklung, Stornierung, Erstattung und Abschluss | -| Anwendungsfall | Welche Fähigkeiten besitzt jeder Akteur? | Käufer, Händler, Lager und Kundendienst | -| Datenfluss | Welche Transformationen und Speicher durchlaufen Datenbestände? | Warenkorb, Transaktionsentscheidungen, Bestellereignisse, Lager/Logistik und Lieferbelege | - -Dies ist ein Konzeptmodell zur Demonstration von QGraphFlow, kein konkretes E-Commerce-Repository. Die Beispieldatei `graph.json` erfindet keine Quellpfade und kennzeichnet Beziehungen mit `inference`. Echte Projektdiagramme benötigen nachvollziehbaren Quellcode, DDL, Konfiguration, Tests und akzeptierte Anforderungen. - -## Entwickeln und beitragen - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -Erforderlich sind Node.js 22 oder neuer, npm, tar, zip und unzip. Fehlerberichte sollten ein minimales anonymisiertes Diagramm, Client- und Browserversion sowie Reproduktionsschritte enthalten. - -Referenzdokumentation (Englisch): [Belegquellen](../../skills/q-flow/references/evidence-sources.md) · [Diagrammformat](../../skills/q-flow/references/graph-schema.md) · [Geführte Bedarfsklärung](../../skills/q-flow/references/guided-intake.md) · [Viewer-Entwicklung und Abnahme](../../skills/q-flow/references/viewer-development.md) · [Diagrammgestaltung](../../skills/q-flow/references/visual-contract.md) - -## Lizenz und Zuordnung - -[MIT](../../LICENSE) · [Drittanbieterhinweise](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow ist ein unabhängiges Projekt unter MIT-Lizenz. Die Szenarien in diesem Dokument sind konzeptionelle Beispiele und stellen keine Produktionsarchitektur eines realen Unternehmens dar. - -## Architekturübersichten - -Architektur umfasst jetzt Komponentenbeziehungen, Plattformfähigkeiten und Engineering-Schichten. Beschreibe den Gegenstand und die Frage; der Skill wählt die Vorlage. Angeforderte Sammlungen können mehrere Architekturansichten mit unabhängigen Bearbeitungen enthalten. - -```text -$qgraphflow:q-flow Analysiere die Plattformfähigkeiten und die geschäftlichen Integrationswege des aktuellen Projekts und erzeuge eine Übersicht der Plattformfähigkeiten auf Chinesisch. -$qgraphflow:q-flow Analysiere die Organisation des aktuellen Projekts und seine Komponentenschichten und erzeuge chinesische Übersichten des Gesamtprojekts und eines Komponentenquerschnitts. -$qgraphflow:q-flow Erzeuge eine englische Übersicht der Plattformfähigkeiten dieses Projekts und zeige, wie sich Anwendungsmodule integrieren. -``` - -Siehe [examples/jeepay](../../examples/jeepay) für quellenbasierte Architekturansichten zu Plattform, Engineering und Komponentenbeziehungen. Entsperre eine Übersicht, um Karten innerhalb einer Schicht neu anzuordnen oder Texte zu bearbeiten. Speichern erhält alle Ansichten; Zurücksetzen stellt nur die aktuelle wieder her. diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md deleted file mode 100644 index 6df4e71..0000000 --- a/docs/readme/README.es.md +++ /dev/null @@ -1,317 +0,0 @@ -
- -

QGraphFlow

- -### Convierte código complejo en diagramas que puedes explorar. - -Sigue el recorrido. Comprueba las evidencias. Comparte un archivo sin conexión. - -💡 Inspirado en Cocoon-AI/architecture-diagram-generator; gracias por la idea. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Demo en línea](https://supermax92.github.io/qgraphflow/) · [Primeros pasos](#primeros-pasos) · [Instalación por cliente](#guía-de-instalación) · [Informar de un problema](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Once tipos de diagramas: arquitectura de capacidades de la plataforma, arquitectura por capas de ingeniería, arquitectura de relaciones entre componentes, diagrama de flujo, secuencia, ER, despliegue, clases, estados, casos de uso y flujo de datos.* - -QGraphFlow genera diagramas de software interactivos a partir del código, los esquemas, la configuración y los requisitos. Permite comprobar las relaciones y compartir el resultado como HTML sin conexión. - -**Qué lo distingue:** once tipos de diagrama en una sola habilidad, un tipo de evidencia en cada relación y la línea de código detrás de cada una respaldada por código, diseño automático, edición en la propia página y ninguna solicitud de red de los scripts del complemento ni del propio Viewer. - -![Demostración interactiva de varias vistas de Jeepay: arquitectura de relaciones entre componentes, secuencia y ER](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Con el código fuente real de Jeepay, alterna entre diagramas de arquitectura de relaciones entre componentes, secuencia y ER para explorar componentes y relaciones de llamadas. [Ver GIF a tamaño original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Presentación de un diagrama de secuencia complejo** - -![Dibujo gradual de un diagrama de secuencia complejo: participantes, líneas de vida, mensajes, barras de activación y fragmentos combinados anidados](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Un escenario ficticio de comercio electrónico contiene 9 participantes, 29 mensajes y 6 fragmentos combinados, con reintentos de inventario, ramas anidadas, procesamiento paralelo, compensación de fallos y callbacks asíncronos. La animación muestra gradualmente el diagrama generado para presentar su estructura y sus detalles. [Ver GIF a tamaño original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Un solo comando instala la habilidad para Claude Code, Codex, Cursor y Qoder; la instalación como complemento y los demás clientes están en la [guía de instalación](#guía-de-instalación). - -- **Explorar:** buscar, ampliar y desplazar el lienzo; consultar responsabilidades y relaciones entrantes y salientes. - -- **Verificar:** inspeccionar nodos y conexiones para revisar archivos, líneas, símbolos e incertidumbres explícitas. - -- **Editar:** desbloquear el diseño, cambiar textos y mover elementos; restablecer cuando sea necesario. - -- **Compartir:** abrir el HTML sin conexión o exportar el diagrama completo a SVG / PNG. - -El [corpus de Jeepay](../../examples/jeepay), basado en código fuente real, contiene las once vistas utilizadas por CI y la demostración online. - -## Primeros pasos - -Tras la instalación, abre tu proyecto de negocio en el cliente y selecciona la habilidad `q-flow`. Los ejemplos usan `/q-flow` de Claude Code; en Codex, usa la entrada `$q-flow` o `$qgraphflow:q-flow` que ofrezca tu cliente. ¿Todavía no lo has instalado? Consulta primero la [guía de instalación](#guía-de-instalación). - -### 1. Entrada vacía: No sabes por dónde empezar - -Invoca la habilidad sin añadir una petición: - -```text -/q-flow -``` - -La habilidad te guía para elegir la parte que analizar y la pregunta que debe responder el diagrama. Empieza a dibujar cuando la información necesaria está clara. - -### 2. Preguntar por las capacidades: Saber qué puede dibujar - -```text -/q-flow ¿Qué tipos de diagramas puedes dibujar? ¿Qué preguntas responde cada tipo? Acabo de hacerme cargo de un proyecto; presenta tus capacidades y sugiere un punto de partida. -``` - -Conoce primero los usos de los once tipos de diagramas y decide después si quieres ver la estructura del proyecto, el orden de llamadas, las relaciones de datos u otro contenido. - -### 3. Entrada vaga: Solo tienes un objetivo general - -```text -/q-flow Ayúdame a dibujar este proyecto. Quiero entenderlo lo antes posible. -``` - -No necesitas indicar primero el tipo de diagrama. La habilidad determina una vista adecuada según el proyecto y tu objetivo, y pregunta cuando falta información necesaria. - -### 4. Entrada precisa: Definir el alcance y pedir detalles del dibujo - -Sustituye los nombres de negocio y los pasos siguientes por procesos que existan realmente en tu proyecto: - -```text -/q-flow Analiza el proceso de creación de pedidos del proyecto actual y genera un diagrama de secuencia en chino. -Incluye la entrada de solicitudes, el cálculo de precios, la reserva de inventario, la autorización de pago y la persistencia del pedido. -Conserva las llamadas síncronas, mensajes asíncronos, retornos emparejados, barras de activación, ramas condicionales, reintentos y compensaciones de fallos que existan realmente en el código. No omitas detalles por brevedad. -Indica los archivos y números de línea del código de los componentes y llamadas, y guarda el resultado en docs/qgraphflow/order-sequence/. -``` - -Define claramente el objeto, la pregunta, el nivel de detalle y la ubicación de salida para empezar directamente. El diagrama conserva solo hechos respaldados por evidencia. - -### 5. Seguir refinando: Ampliar una parte del diagrama anterior - -Una vez generado el resultado, continúa en la misma conversación: - -```text -/q-flow Amplía el paso de reserva de inventario del diagrama de secuencia anterior en un diagrama de flujo independiente en chino. -Muestra todas las ramas de validación de inventario, reserva exitosa, fallos reintentables, límite de reintentos y liberación de inventario. Sigue el código fuente y no añadas pasos que no existan en él. -``` - -Mira primero el conjunto y profundiza después en un paso. También puedes pedir más detalles de un diagrama existente o verificar sus relaciones. - -## Guía de instalación - -Se necesitan Node.js 22 o posterior y un cliente compatible con complementos que tenga configurado el acceso al modelo. - -### Instalación rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Probado con `skills` 1.7.0 en Claude Code, Codex, Cursor y Qoder. El comando pregunta en qué clientes instalar; `-a claude-code` indica uno directamente y `-g` instala para el usuario en lugar del proyecto actual. La habilidad queda instalada como `q-flow`, sin el prefijo `qgraphflow:` de las instalaciones como complemento de más abajo. - -Para instalarla como complemento, seguir los pasos siguientes. En [Qoder Desktop](#qoder-desktop), puedes instalar desde el Marketplace y omitir el paso 1. - -### 1. Descargar el complemento - -Obtener el complemento desde npmjs.com, sin cuenta, inicio de sesión ni token. Crear un directorio independiente fuera del proyecto de la aplicación: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Ahora se está en la raíz del complemento. **La descarga mediante npm no instala automáticamente el complemento en el cliente**; continuar con el paso 2. El paquete también ofrece el comando `qgraphflow`, que se usa en [Mantener los diagramas sincronizados con el código](#mantener-los-diagramas-sincronizados-con-el-código). - -Ejecutar los comandos siguientes desde **la raíz del complemento, que contiene `skills/`**. - -### 2. Instalar en el cliente - -#### Codex App / CLI - -Codex CLI debe estar instalado y disponible en la terminal: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Iniciar una sesión nueva, escribir `$` y seleccionar `qgraphflow:q-flow`. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Iniciar una sesión nueva y escribir `/q-flow` (o el nombre completo `/qgraphflow:q-flow`). - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Iniciar una sesión nueva y seleccionar `q-flow`. - -#### Qoder Desktop - -**Recomendado:** Abre **Settings → Plugins → Marketplace**, busca **QGraphFlow** o **代码图谱可视化** e instala el complemento. Inicia una sesión nueva y selecciona `q-flow`. - -Para una instalación local, completa primero el paso 1. Después abre **Settings → Plugins → Custom → Import** e importa el directorio raíz completo del complemento. Inicia una sesión nueva y selecciona `q-flow`. - -#### Cursor - -Copiar todo el contenido de la raíz del complemento, incluidos los archivos ocultos, a: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Comprobar que allí existe `.cursor-plugin/plugin.json`, recargar la ventana y buscar `q-flow` en **Customize**. Si hay una versión anterior, hacer una copia de seguridad antes; no mezclar archivos antiguos y nuevos. - -### 3. Empezar a usarlo - -Abre tu proyecto de negocio en el cliente, inicia una sesión nueva y selecciona la habilidad. Describe tu petición siguiendo los ejemplos de [Primeros pasos](#primeros-pasos). Abre el HTML generado en el navegador. - -¿Prefieres compilarlo? Consulta las [instrucciones de compilación desde el código fuente](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Uso rápido - -Estos ejemplos usan `$qgraphflow:q-flow` en Codex. Si el cliente muestra `$q-flow`, seleccionar esa entrada. En los demás clientes, usar la forma de invocación indicada arriba. - -**¿No sabes por dónde empezar?** Invocar la habilidad y elegir el tema y la pregunta cuando lo solicite. - -```text -$qgraphflow:q-flow -``` - -**¿Ya tienes un objetivo?** Indicar qué parte quieres dibujar y qué quieres entender. No hace falta elegir antes el tipo de diagrama. - -### Ejemplo 1: Entender la arquitectura - -```text -$qgraphflow:q-flow Analiza este proyecto y crea un diagrama de arquitectura en chino que muestre responsabilidades de los módulos, dependencias y límites del sistema. -``` - -Útil para conocer la estructura general al llegar a un proyecto. - -### Ejemplo 2: Seguir un flujo de negocio - -```text -$qgraphflow:q-flow Analiza la creación de pedidos y genera un diagrama de secuencia en chino con cálculo de precios, reserva de inventario, pago y persistencia del pedido, incluidas las ramas de fallo. -``` - -Sustituir la creación de pedidos y sus pasos por el flujo real del proyecto. Continuar en la misma conversación: - -```text -$qgraphflow:q-flow Amplía la reserva de inventario del diagrama anterior en un diagrama de flujo independiente en chino, con el tratamiento de éxitos y fallos. -``` - -Los resultados se guardan bajo `docs/qgraphflow/` de forma predeterminada. Abrir `index.html` para explorar, editar y exportar; `graph.json` conserva los datos. Cada vista también se escribe como SVG (`diagram.svg`, o `diagram--.svg` cuando hay varias), que puede incrustarse como imagen en un README, una pull request o una wiki. - -Después de editar en la página, **Más → Guardar cambios** en Chrome o Edge reescribe en su sitio la página, `graph.json` y los SVG, tras elegir una vez la carpeta del diagrama. Otros navegadores solo guardan `graph.json`: colocarlo en la carpeta y volver a generar la página y los SVG con `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. - -
-Ejecutar el ejemplo de Jeepay con once vistas basado en código fuente - -Selecciona tu copia local del código fuente de Jeepay para verificar la evidencia: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Abre `output/jeepay/index.html`; sus once SVG están en el mismo directorio. Consulta el [README del corpus](../../examples/jeepay) para conocer la revisión del código fuente y el procedimiento de actualización. - -
- -## Mantener los diagramas sincronizados con el código - -Un diagrama generado con la raíz del repositorio registra dónde se define cada componente, la línea detrás de cada relación respaldada por código (una llamada, una clave foránea) y una huella de cada archivo al que apunta. La validación con `--repo-root` deja pasar las líneas que solo se desplazaron y falla cuando cambió el código detrás del diagrama: se reescribió una línea registrada, se eliminó una llamada, código nuevo toca un componente dibujado sin una relación que lo cubra, o desapareció un nombre que usa el diagrama. El error muestra el código anterior y el nuevo e indica los elementos y textos que hay que actualizar. Añadir este trabajo a la CI; no necesita compilación, inicio de sesión ni token, y el historial completo (`fetch-depth: 0`) permite compararlo con esas huellas: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Para ver el impacto en la pull request, añade `--changes changes.md` a la línea de validate y, si falla, publica el archivo como comentario, por ejemplo con `gh pr comment "$PR" --body-file changes.md` (requiere `pull-requests: write`). Enumera, por vista, los elementos que toca cada cambio, el archivo y la línea, y el código anterior y el nuevo. La página regenerada después de `--fix` también marca esos elementos y enumera los cambios junto a los puntos clave. - -Si falla, pedir a la habilidad que actualice ese diagrama: - -```text -$qgraphflow:q-flow La CI dice que docs/qgraphflow/order-sequence está desactualizado. Actualízalo. -``` - -La habilidad realinea todos los anclajes, enumera cada cambio en `meta.sourceDrift` del grafo, actualiza solo lo que esas entradas señalan y vuelve a generar la página y los SVG conservando las posiciones y los textos editados. No redibuja el diagrama. - -Añade `--compare HEAD` al regenerar para ver qué cambió una actualización: la página colorea los elementos añadidos y modificados, enumera los eliminados junto a los puntos clave y no toca `graph.json`. - -## Qué responde cada uno de los once tipos de diagramas - -| Vista · PNG | Pregunta principal | Alcance del ejemplo | -| --- | --- | --- | -| Arquitectura de capacidades de la plataforma | ¿Qué capacidades ofrece la plataforma? | Zonas de capacidades y matrices | -| Arquitectura por capas de ingeniería | ¿Cómo se organiza el código del proyecto? | Capas de ingeniería y soporte compartido | -| Arquitectura de relaciones entre componentes | ¿Qué límites de responsabilidad colaboran en el sistema? | Canales, orquestación de transacciones, precios, riesgo, inventario, pago, pedidos, eventos y ejecución de pedidos | -| Diagrama de flujo | ¿Cómo se bifurca y converge cada decisión? | Falta de inventario, rechazo de riesgo, compensación de fallos de pago y confirmación exitosa | -| Secuencia | ¿En qué orden hace llamadas y recibe retornos una solicitud? | Flujo principal de compra exitosa y OrderPaid asíncrono | -| ER | ¿Cómo se relacionan los datos principales? | Carrito, pedidos, líneas, pagos, reservas de inventario y paquetes | -| Despliegue | ¿Dónde se ubican las unidades de ejecución y cómo se conectan? | Borde, Kubernetes, servicios de datos, pago y redes de almacén y logística | -| Clases | ¿Cómo dependen los objetos de dominio y los contratos del código? | Servicio de aplicación Checkout, Order y cuatro puertos | -| Estados | ¿Qué eventos y condiciones de guarda hacen avanzar un pedido? | Pago, ejecución del pedido, cancelación, reembolso y cierre | -| Casos de uso | ¿Qué capacidades tiene cada actor? | Comprador, comercio, almacén y atención al cliente | -| Flujo de datos | ¿Por qué transformaciones y almacenes pasan los activos de datos? | Carrito, decisiones de transacción, eventos de pedidos, almacén y logística y comprobantes de entrega | - -Este modelo conceptual demuestra QGraphFlow y no corresponde a un repositorio de comercio concreto. El ejemplo `graph.json` no inventa rutas de código y marca las evidencias de las relaciones como `inference`. Los diagramas reales necesitan código, DDL, configuración, pruebas y requisitos aceptados que se puedan rastrear. - -## Desarrollo y contribuciones - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -Se necesitan Node.js 22 o posterior, npm, tar, zip y unzip. Al informar de un problema, incluir un gráfico mínimo sin datos sensibles, versiones del cliente y navegador y pasos de reproducción. - -Documentación de referencia (en inglés): [Fuentes de evidencia](../../skills/q-flow/references/evidence-sources.md) · [Formato de gráficos](../../skills/q-flow/references/graph-schema.md) · [Consulta guiada](../../skills/q-flow/references/guided-intake.md) · [Desarrollo y aceptación del Viewer](../../skills/q-flow/references/viewer-development.md) · [Composición de diagramas](../../skills/q-flow/references/visual-contract.md) - -## Licencia y atribución - -[MIT](../../LICENSE) · [Avisos de terceros](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow es un proyecto independiente con licencia MIT. Los escenarios de este documento son ejemplos conceptuales y no representan la arquitectura de producción de ninguna empresa real. - -## Vistas generales de arquitectura - -La arquitectura incluye ahora relaciones entre componentes, capacidades de la plataforma y capas de ingeniería. Describe el objeto y la pregunta; la habilidad elige la plantilla. Las colecciones solicitadas pueden contener varias vistas de arquitectura con ediciones independientes. - -```text -$qgraphflow:q-flow Analiza las capacidades de la plataforma y las formas de integración de negocio del proyecto actual, y genera una vista general de capacidades de la plataforma en chino. -$qgraphflow:q-flow Analiza la organización del proyecto actual y sus capas de componentes, y genera vistas generales en chino del proyecto completo y de una sección de un componente. -$qgraphflow:q-flow Genera una vista general en inglés de las capacidades de la plataforma de este proyecto y muestra cómo se integran los módulos de aplicación. -``` - -Consulta [examples/jeepay](../../examples/jeepay) para ver las vistas de arquitectura de plataforma, ingeniería y relaciones entre componentes basadas en código fuente real. Desbloquea una vista general para reordenar tarjetas dentro de una capa o editar texto. Guardar conserva todas las vistas; restablecer restaura solo la actual. diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md deleted file mode 100644 index e17dd3f..0000000 --- a/docs/readme/README.ja.md +++ /dev/null @@ -1,317 +0,0 @@ -
- -

QGraphFlow

- -### 複雑なコードを、探索できる図へ。 - -経路をたどり、根拠を確認し、ひとつのオフラインファイルで共有。 - -💡 Cocoon-AI/architecture-diagram-generator に着想を得ました。原作者に感謝します。 - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[オンラインデモ](https://supermax92.github.io/qgraphflow/) · [はじめに](#はじめに) · [クライアントへの導入](#インストールガイド) · [問題を報告](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*11 種類の図に対応:プラットフォーム機能アーキテクチャ図、エンジニアリング層アーキテクチャ図、コンポーネント関係アーキテクチャ図、フローチャート、シーケンス図、ER 図、配置図、クラス図、状態図、ユースケース図、データフロー図。* - -QGraphFlow はソースコード、データ構造、設定、要件から対話型のソフトウェア図を生成します。関係の根拠を確認し、共有可能なオフライン HTML として届けます。 - -**ここが違う:** 1 つのスキルで 11 種類の図、すべての関係に根拠の種別、コードで裏付けられた関係にはその根拠となるソース行、自動レイアウト、ページ上での編集。プラグインのスクリプトと Viewer 自体はネットワーク通信を一切行いません。 - -![Jeepay の複数ビュー操作デモ:コンポーネント関係アーキテクチャ図、シーケンス図、ER 図](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Jeepay の実際のソースを例に、コンポーネント関係アーキテクチャ図、シーケンス図、ER 図を切り替えて、コンポーネントと呼び出し関係を探索します。 [原寸の GIF を見る](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**複雑なシーケンス図の紹介** - -![複雑なシーケンス図の段階的な描画:参加者、ライフライン、メッセージ、活性区間、入れ子の結合フラグメント](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -架空の EC シナリオに 9 人の参加者、29 件のメッセージ、6 個の結合フラグメントを含め、在庫の再試行、入れ子の分岐、並行処理、失敗時の補償、非同期コールバックを扱います。生成済みの図をアニメーションで段階的に表示し、複雑なシーケンス図の構造と詳細を紹介します。 [原寸の GIF を見る](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -1 つのコマンドで Claude Code、Codex、Cursor、Qoder にスキルを導入できます。プラグインとしての導入やほかのクライアントは[インストールガイド](#インストールガイド)を参照してください。 - -- **探索:** 検索・拡大縮小・パンで、責務と上流・下流の関係を確認。 - -- **検証:** ノードや接続線からファイル、行番号、シンボル、明示された不確実性を確認。 - -- **編集:** ロック解除後に文字や位置を変更。必要に応じてリセット。 - -- **共有:** オフライン HTML を開くか、図全体を SVG / PNG に出力。 - -実際のソースに基づく [Jeepay コーパス](../../examples/jeepay)には、CI とオンラインデモで使う 11 種類のビューがすべて含まれます。 - -## はじめに - -インストール後、クライアントで業務プロジェクトを開き、`q-flow` スキルを選択します。以下は Claude Code の `/q-flow` を使う例です。Codex ではクライアントが実際に提供する `$q-flow` または `$qgraphflow:q-flow` を使ってください。まだインストールしていない場合は、先に[インストールガイド](#インストールガイド)を参照してください。 - -### 1. 空の入力:どこから始めるか分からない - -要件を付けずにスキルだけを呼び出します。 - -```text -/q-flow -``` - -スキルが、分析する部分と図で答えてほしい問いの選択を案内します。必要な情報が明確になったら描画を始めます。 - -### 2. 機能を尋ねる:何を描けるか知る - -```text -/q-flow どの種類の図を描けますか?各種類はどのような問いに答えるのに適していますか?プロジェクトを引き継いだばかりなので、まず機能を紹介し、始める場所を提案してください。 -``` - -まず 11 種類の図の用途を知り、それからプロジェクト構造、呼び出し順序、データ関係など、何を見るかを決めます。 - -### 3. 曖昧な入力:大まかな目的だけがある - -```text -/q-flow このプロジェクトを図にしてください。できるだけ早く理解したいです。 -``` - -先に図の種類を指定する必要はありません。スキルがプロジェクトと目的に応じて適したビューを決め、必要な情報が不足している場合に質問します。 - -### 4. 正確な入力:範囲を明示して描画の詳細を求める - -次の業務名と手順を、プロジェクトに実際に存在するフローに置き換えてください。 - -```text -/q-flow 現在のプロジェクトの注文作成フローを分析し、中国語のシーケンス図を生成してください。 -リクエスト入口、価格計算、在庫引当、支払い承認、注文の永続化を含めてください。 -ソースに実際に存在する同期呼び出し、非同期メッセージ、対応する戻り、活性区間、条件分岐、再試行、失敗時の補償を残し、簡潔さのために詳細を省略しないでください。 -コンポーネントと呼び出しのソースファイルと行番号を示し、結果を docs/qgraphflow/order-sequence/ に保存してください。 -``` - -対象、問い、詳細度、出力先を明確に伝えると、そのまま開始できます。図には根拠のある事実だけを残します。 - -### 5. さらに詳しく:前の図の一部分を展開する - -結果の生成後、同じ会話で続けます。 - -```text -/q-flow 前のシーケンス図の在庫引当ステップを展開し、独立した中国語のフローチャートを生成してください。 -在庫確認、引当成功、再試行可能な失敗、再試行上限、在庫解放の分岐をすべて示してください。ソースコードに従い、コードにない手順は追加しないでください。 -``` - -まず全体を見てから、ひとつの手順を掘り下げます。既存の図の詳細追加や、関係の検証を続けて依頼することもできます。 - -## インストールガイド - -Node.js 22 以降と、プラグインに対応しモデルへのアクセスを設定済みのクライアントを用意してください。 - -### クイックインストール - -```bash -npx skills add supermax92/qgraphflow -``` - -`skills` 1.7.0 で Claude Code、Codex、Cursor、Qoder への導入を実測済みです。導入先のクライアントを尋ねられます。`-a claude-code` で直接指定でき、`-g` を付けると現在のプロジェクトではなくユーザー単位で導入します。この方法で導入したスキル名は `q-flow` で、下のプラグイン導入で付く `qgraphflow:` という接頭辞は付きません。 - -プラグインとして導入する場合は、次の手順に従ってください。[Qoder Desktop](#qoder-desktop) ではマーケットプレイスから直接インストールできるため、手順 1 は不要です。 - -### 1. プラグインをダウンロード - -npmjs.com からプラグインを取得します。アカウント、ログイン、トークンは不要です。業務プロジェクトの外に専用ディレクトリを作成します。 - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -これでプラグインのルートディレクトリに移動できました。**npm でダウンロードしても、クライアントへのインストールは自動では行われません。** 手順 2 に進んでください。このパッケージには `qgraphflow` コマンドも含まれ、[図とコードを同期させる](#図とコードを同期させる)で使います。 - -以下のコマンドはすべて、**`skills/` を含むプラグインのルートディレクトリ**で実行してください。 - -### 2. クライアントにインストール - -#### Codex App / CLI - -ターミナルで Codex CLI を使用できるよう、あらかじめインストールしてください。 - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -新しいセッションを開始し、`$` を入力して `qgraphflow:q-flow` を選択します。 - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -新しいセッションを開始し、`/q-flow`(または完全名 `/qgraphflow:q-flow`)を入力します。 - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -新しいセッションを開始し、`q-flow` を選択します。 - -#### Qoder Desktop - -**推奨:** **Settings → Plugins → Marketplace** を開き、**QGraphFlow** または **代码图谱可视化** を検索してインストールします。新しいセッションを開始し、`q-flow` を選択します。 - -ローカルインストールの場合は手順 1 を完了し、**Settings → Plugins → Custom → Import** を開いて、プラグインのルートディレクトリ全体をインポートします。新しいセッションで `q-flow` を選択します。 - -#### Cursor - -プラグインのルートディレクトリ内のすべてのファイル(隠しファイルを含む)を、次の場所にコピーします。 - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -その中に `.cursor-plugin/plugin.json` があることを確認し、ウィンドウを再読み込みして **Customize** で `q-flow` を探します。旧バージョンがある場合は先にバックアップし、新旧のファイルを混在させないでください。 - -### 3. 使い始める - -クライアントで業務プロジェクトを開き、新しいセッションでスキルを選択します。[はじめに](#はじめに)の例を参考に要件を伝えてください。生成後、出力された HTML をブラウザで開きます。 - -自分でビルドする場合は、[ソースからのビルド手順](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)を参照してください。 - -## すぐに使う - -以下は Codex の `$qgraphflow:q-flow` を使う例です。クライアントに `$q-flow` と表示される場合は、その入口を選択してください。他のクライアントでは、上記の対応するスキルの呼び出し方を使います。 - -**どこから始めるか迷ったら:** スキルを呼び出し、案内に従って対象と知りたいことを選びます。 - -```text -$qgraphflow:q-flow -``` - -**目的が決まっているなら:** 「どの部分を描くか+何を知りたいか」を伝えます。先に図の種類を選ぶ必要はありません。 - -### 例1:プロジェクト構造を理解する - -```text -$qgraphflow:q-flow 現在のプロジェクトを分析し、主要モジュールの責務、依存関係、システム境界を示す中国語のアーキテクチャ図を作成してください。 -``` - -初めて触れるプロジェクトの全体像をつかむのに適しています。 - -### 例2:業務の呼び出しを追う - -```text -$qgraphflow:q-flow 注文作成フローを分析し、価格計算、在庫引当、支払い、注文保存の呼び出し順と失敗分岐を示す中国語のシーケンス図を作成してください。 -``` - -「注文作成」と各手順を実際の業務フローに置き換えてください。同じ会話で続けて依頼できます。 - -```text -$qgraphflow:q-flow 前の図の在庫引当を掘り下げ、成功時と失敗時の処理を示す中国語のフローチャートを別に作成してください。 -``` - -既定の保存先は `docs/qgraphflow/` 配下です。`index.html` を開いて探索・編集・出力でき、`graph.json` に図データが残ります。各ビューは SVG(`diagram.svg`、複数ビューでは `diagram--.svg`)としても書き出され、README、プルリクエスト、Wiki に画像として埋め込めます。 - -ページで編集したあと、Chrome または Edge で「その他 → 変更を保存」を実行し、図のフォルダーを一度選ぶと、ページ、`graph.json`、SVG がその場で書き換わります。ほかのブラウザーは `graph.json` だけを保存します。そのフォルダーに置いてから `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` でページと SVG を再生成してください。 - -
-Jeepay のソースに基づく 11 ビューの例を実行する - -根拠を検証するため、ローカルの Jeepay ソースチェックアウトを指定してください。 - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -`output/jeepay/index.html` を開いてください。11 個の SVG も同じディレクトリにあります。ソースのリビジョンと更新手順は[コーパスの README](../../examples/jeepay)を参照してください。 - -
- -## 図とコードを同期させる - -リポジトリのルートを指定して生成した図には、各コンポーネントの定義位置、コードで裏付けられた各関係を成立させている行(呼び出し、外部キーなど)、そして参照している各ファイルの内容の指紋が記録されます。`--repo-root` 付きで検証すると、位置が移動しただけの行は自動で追従して通過し、図の裏にあるコードが実際に変わったときだけ失敗します。記録した行が書き換えられた、呼び出しが削除された、図に描かれたコンポーネントに触れる新しいコードに対応する関係がない、図で使っている名前がなくなった、のいずれかです。エラーには変更前後のコードと、更新すべき要素と文字が示されます。次のジョブを CI に追加してください。ビルド、ログイン、トークンは不要です。指紋と比較するため、完全な履歴(`fetch-depth: 0`)を取得します。 - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -影響箇所をプルリクエストで確認したい場合は、validate の行に `--changes changes.md` を追加し、失敗したときにそのファイルをコメントとして投稿します(例:`gh pr comment "$PR" --body-file changes.md`、`pull-requests: write` 権限が必要)。ビューごとに、各変更が触れる要素、ファイルと行、変更前後のコードが一覧になります。`--fix` の後に再生成したページでも、それらの要素に印が付き、要点の横に変更が一覧表示されます。 - -失敗したら、スキルにその図の更新を頼みます。 - -```text -$qgraphflow:q-flow CI で docs/qgraphflow/order-sequence の図が古いと出ました。更新してください。 -``` - -スキルはすべてのアンカーを現在のコードに合わせ、各変更をグラフの `meta.sourceDrift` に列挙し、その項目が示す要素だけを更新して、編集した位置と文字を保ったままページと SVG を再生成します。図を描き直すことはしません。 - -再生成時に `--compare HEAD` を付けると、今回の更新で何が変わったかが分かります。追加・変更された要素に色が付き、削除された要素は要点の横に一覧表示されます。`graph.json` は変わりません。 - -## 11 種類の図がそれぞれ答えること - -| ビュー · PNG | 主な問い | 本サンプルの範囲 | -| --- | --- | --- | -| プラットフォーム機能アーキテクチャ図 | プラットフォームにはどんな機能があるか? | 機能の区分とマトリクス | -| エンジニアリング層アーキテクチャ図 | プロジェクトのコードはどう構成されているか? | エンジニアリング層と共通の支援機能 | -| コンポーネント関係アーキテクチャ図 | システムのどの責務境界が協調するか? | チャネル、取引のオーケストレーション、価格、リスク、在庫、支払い、注文、イベント、注文履行 | -| フローチャート | 各判断点はどう分岐・合流するか? | 欠品、リスク拒否、支払い失敗時の補償、正常コミット | -| シーケンス図 | ひとつのリクエストはどの順序で呼び出しと戻りを行うか? | 決済成功の主経路と非同期 OrderPaid | -| ER 図 | 主要データはどう関連するか? | カート、注文、明細、支払い、在庫引当、荷物 | -| 配置図 | 実行単位をどこに置き、どう接続するか? | エッジ、Kubernetes、データサービス、支払い、倉庫配送ネットワーク | -| クラス図 | ドメインオブジェクトとコードの契約はどう依存するか? | Checkout アプリケーションサービス、Order、4 つのポート | -| 状態図 | どのイベントとガード条件が注文を進めるか? | 支払い、注文履行、取消、返金、終了 | -| ユースケース図 | 各参加者にはどんな機能があるか? | 購入者、店舗、倉庫、カスタマーサポート | -| データフロー図 | データ資産はどの変換と保存を経るか? | カート、取引判断、注文イベント、倉庫配送、配送受領記録 | - -これは QGraphFlow の機能を示す概念モデルで、特定の EC リポジトリに対応しません。サンプルの `graph.json` に架空のソースパスは入れず、関係の証拠を `inference` に統一しています。実際のプロジェクトでは、追跡可能なソース、DDL、設定、テスト、合意済み要件を使ってください。 - -## 開発と参加 - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -開発には Node.js 22 以降、npm、tar、zip、unzip が必要です。問題報告には、機密情報を除いた最小限の図データ、クライアントとブラウザーのバージョン、再現手順を添えてください。 - -リファレンス(英語):[証拠の出典](../../skills/q-flow/references/evidence-sources.md) · [図データ形式](../../skills/q-flow/references/graph-schema.md) · [対話による要件確認](../../skills/q-flow/references/guided-intake.md) · [Viewer の開発と受け入れ検証](../../skills/q-flow/references/viewer-development.md) · [図の構成](../../skills/q-flow/references/visual-contract.md) - -## ライセンスと帰属 - -[MIT](../../LICENSE) · [第三者の表示](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow は MIT ライセンスを採用する独立したプロジェクトです。本文のシナリオは概念例で、実在する企業の本番アーキテクチャを表しません。 - -## アーキテクチャの全体像 - -アーキテクチャには、コンポーネント関係、プラットフォーム機能、エンジニアリング層が含まれます。対象と問いを伝えると、スキルがテンプレートを選びます。依頼したコレクションには、個別に編集できる複数のアーキテクチャビューを含められます。 - -```text -$qgraphflow:q-flow 現在のプロジェクトのプラットフォーム機能と業務の接続方法を分析し、中国語のプラットフォーム機能全体図を生成してください。 -$qgraphflow:q-flow 現在のプロジェクト構成とコンポーネントの階層を分析し、プロジェクト全体とひとつのコンポーネント断面の中国語の全体図を生成してください。 -$qgraphflow:q-flow このプロジェクトのプラットフォーム機能の全体図を英語で生成し、アプリケーションモジュールがどのように統合されるかを示してください。 -``` - -実際のソースに基づくプラットフォーム、エンジニアリング、コンポーネント関係のアーキテクチャビューは [examples/jeepay](../../examples/jeepay)を参照してください。全体図のロックを解除すると、同じ層のカードの並べ替えや文字の編集ができます。保存は全ビューを保持し、リセットは現在のビューだけを戻します。 diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md deleted file mode 100644 index 09a7b28..0000000 --- a/docs/readme/README.pt.md +++ /dev/null @@ -1,317 +0,0 @@ -
- -

QGraphFlow

- -### Transforme código complexo em diagramas que você pode explorar. - -Siga o caminho. Confira as evidências. Compartilhe um arquivo offline. - -💡 Inspirado em Cocoon-AI/architecture-diagram-generator — agradecemos pela ideia. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Demonstração online](https://supermax92.github.io/qgraphflow/) · [Primeiros passos](#primeiros-passos) · [Instalação por cliente](#guia-de-instalação) · [Relatar problema](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Onze tipos de diagrama: arquitetura de capacidades da plataforma, arquitetura em camadas de engenharia, arquitetura de relações entre componentes, fluxograma, sequência, ER, implantação, classes, estados, casos de uso e fluxo de dados.* - -QGraphFlow gera diagramas de software interativos a partir de código, esquemas, configuração e requisitos. As relações podem ser verificadas e o resultado é um HTML offline compartilhável. - -**O que o diferencia:** onze tipos de diagrama em uma só habilidade, o tipo de evidência de cada relação e a linha de código por trás de cada uma que o código sustenta, layout automático, edição na própria página e nenhuma requisição de rede dos scripts do plugin nem do próprio Viewer. - -![Demonstração interativa de várias vistas do Jeepay: arquitetura de relações entre componentes, sequência e ER](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Com o código-fonte real do Jeepay, alterne entre diagramas de arquitetura de relações entre componentes, sequência e ER para explorar componentes e relações de chamadas. [Ver GIF no tamanho original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Apresentação de um diagrama de sequência complexo** - -![Desenho gradual de um diagrama de sequência complexo: participantes, linhas de vida, mensagens, barras de ativação e fragmentos combinados aninhados](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Um cenário fictício de comércio eletrônico contém 9 participantes, 29 mensagens e 6 fragmentos combinados, com novas tentativas de estoque, ramos aninhados, processamento paralelo, compensação de falhas e callbacks assíncronos. A animação revela gradualmente o diagrama gerado para mostrar sua estrutura e seus detalhes. [Ver GIF no tamanho original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Um só comando instala a habilidade para Claude Code, Codex, Cursor e Qoder; a instalação como plugin e os demais clientes estão no [guia de instalação](#guia-de-instalação). - -- **Explorar:** pesquisar, ampliar e deslocar a tela; entender responsabilidades e relações de entrada e saída. - -- **Verificar:** inspecionar nós e conexões para conferir arquivos, linhas, símbolos e incertezas explícitas. - -- **Editar:** desbloquear o layout, alterar textos e mover elementos; redefinir quando necessário. - -- **Compartilhar:** abrir o HTML offline ou exportar o diagrama completo em SVG / PNG. - -O [corpus do Jeepay](../../examples/jeepay), baseado em código-fonte real, contém as onze vistas usadas pelo CI e pela demonstração online. - -## Primeiros passos - -Após a instalação, abra seu projeto de negócio no cliente e selecione a habilidade `q-flow`. Os exemplos usam `/q-flow` do Claude Code; no Codex, use a entrada `$q-flow` ou `$qgraphflow:q-flow` que seu cliente realmente oferece. Ainda não instalou? Consulte primeiro o [guia de instalação](#guia-de-instalação). - -### 1. Entrada vazia: Não sabe por onde começar - -Invoque a habilidade sem acrescentar uma solicitação: - -```text -/q-flow -``` - -A habilidade orienta você a escolher a parte a analisar e a pergunta que o diagrama deve responder. O desenho começa quando as informações necessárias estão claras. - -### 2. Perguntar sobre capacidades: Saber o que pode desenhar - -```text -/q-flow Quais tipos de diagrama você pode desenhar? Que perguntas cada tipo responde? Acabei de assumir um projeto; apresente suas capacidades e sugira um ponto de partida. -``` - -Conheça primeiro os usos dos onze tipos de diagrama e depois decida se quer explorar a estrutura do projeto, a ordem das chamadas, as relações de dados ou outro conteúdo. - -### 3. Entrada vaga: Apenas um objetivo geral - -```text -/q-flow Ajude-me a desenhar este projeto. Quero entendê-lo o mais rápido possível. -``` - -Não é necessário indicar primeiro o tipo de diagrama. A habilidade determina uma vista adequada com base no projeto e no seu objetivo, e pergunta quando faltam informações necessárias. - -### 4. Entrada precisa: Definir o escopo e pedir detalhes do desenho - -Substitua os nomes de negócio e os passos abaixo por fluxos que realmente existam no seu projeto: - -```text -/q-flow Analise o fluxo de criação de pedidos do projeto atual e gere um diagrama de sequência em chinês. -Inclua a entrada da solicitação, o cálculo de preços, a reserva de estoque, a autorização de pagamento e a persistência do pedido. -Mantenha as chamadas síncronas, mensagens assíncronas, retornos emparelhados, barras de ativação, ramificações condicionais, tentativas e compensações de falha que realmente existam no código. Não omita detalhes por brevidade. -Indique os arquivos e números de linha do código dos componentes e chamadas, e salve o resultado em docs/qgraphflow/order-sequence/. -``` - -Defina claramente o objeto, a pergunta, o nível de detalhe e o local de saída para começar diretamente. O diagrama mantém apenas fatos sustentados por evidências. - -### 5. Refinar mais: Expandir parte do diagrama anterior - -Após a geração do resultado, continue na mesma conversa: - -```text -/q-flow Expanda a etapa de reserva de estoque do diagrama de sequência anterior em um fluxograma separado em chinês. -Mostre todos os ramos de validação do estoque, reserva bem-sucedida, falhas que permitem nova tentativa, limite de tentativas e liberação de estoque. Siga o código-fonte e não adicione etapas ausentes dele. -``` - -Veja primeiro o todo e depois aprofunde uma etapa. Você também pode pedir mais detalhes de um diagrama existente ou verificar suas relações. - -## Guia de instalação - -Você precisa do Node.js 22 ou posterior e de um cliente com suporte a plugins e acesso ao modelo configurado. - -### Instalação rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Testado com `skills` 1.7.0 no Claude Code, Codex, Cursor e Qoder. O comando pergunta em quais clientes instalar; `-a claude-code` indica um diretamente e `-g` instala para o seu usuário em vez do projeto atual. A habilidade é instalada como `q-flow`, sem o prefixo `qgraphflow:` das instalações como plugin abaixo. - -Para instalar como plugin, siga as etapas abaixo. No [Qoder Desktop](#qoder-desktop), você pode instalar pelo Marketplace e pular a etapa 1. - -### 1. Baixe o plugin - -Obtenha o plugin no npmjs.com, sem conta, login nem token. Crie um diretório separado, fora do projeto da sua aplicação: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Agora você está na raiz do plugin. **Baixar pelo npm não instala automaticamente o plugin no cliente**; continue na etapa 2. O pacote também oferece o comando `qgraphflow`, usado em [Mantenha os diagramas em sincronia com o código](#mantenha-os-diagramas-em-sincronia-com-o-código). - -Execute os comandos abaixo na **raiz do plugin, que contém `skills/`**. - -### 2. Instale no seu cliente - -#### Codex App / CLI - -O Codex CLI precisa estar instalado e disponível no terminal: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Inicie uma nova sessão, digite `$` e selecione `qgraphflow:q-flow`. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Inicie uma nova sessão e digite `/q-flow` (ou o nome completo `/qgraphflow:q-flow`). - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Inicie uma nova sessão e selecione `q-flow`. - -#### Qoder Desktop - -**Recomendado:** Abra **Settings → Plugins → Marketplace**, pesquise **QGraphFlow** ou **代码图谱可视化** e instale o plugin. Inicie uma nova sessão e selecione `q-flow`. - -Para uma instalação local, conclua primeiro a etapa 1. Depois, abra **Settings → Plugins → Custom → Import** e importe o diretório raiz completo do plugin. Inicie uma nova sessão e selecione `q-flow`. - -#### Cursor - -Copie todo o conteúdo da raiz do plugin, incluindo os arquivos ocultos, para: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Confirme que `.cursor-plugin/plugin.json` existe nesse local, recarregue a janela e encontre `q-flow` em **Customize**. Se houver uma versão anterior, faça backup primeiro; não misture arquivos antigos e novos. - -### 3. Comece a usar - -Abra seu projeto de negócio no cliente, inicie uma nova sessão e selecione a habilidade. Descreva sua solicitação seguindo os exemplos de [Primeiros passos](#primeiros-passos). Abra o HTML gerado no navegador. - -Quer compilar por conta própria? Consulte as [instruções de compilação do código-fonte](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Uso rápido - -Os exemplos usam `$qgraphflow:q-flow` no Codex. Se o cliente mostrar `$q-flow`, selecione essa entrada. Nos demais clientes, use a forma de chamada da habilidade indicada acima. - -**Sem saber por onde começar?** Chame a habilidade e escolha o assunto e a pergunta quando solicitado. - -```text -$qgraphflow:q-flow -``` - -**Já tem um objetivo?** Diga qual parte deseja desenhar e o que quer entender. Não é preciso escolher o tipo de diagrama antes. - -### Exemplo 1: Entender a arquitetura - -```text -$qgraphflow:q-flow Analise este projeto e crie um diagrama de arquitetura em chinês com responsabilidades dos módulos, dependências e limites do sistema. -``` - -Útil para conhecer a estrutura geral ao entrar em um projeto. - -### Exemplo 2: Acompanhar um fluxo de negócio - -```text -$qgraphflow:q-flow Analise a criação de pedidos e gere um diagrama de sequência em chinês com cálculo de preços, reserva de estoque, pagamento e persistência do pedido, incluindo os ramos de falha. -``` - -Substitua a criação de pedidos e suas etapas pelo fluxo real do projeto. Continue na mesma conversa: - -```text -$qgraphflow:q-flow Expanda a reserva de estoque do diagrama anterior em um fluxograma separado em chinês, mostrando o tratamento de sucesso e falha. -``` - -Os resultados ficam em `docs/qgraphflow/` por padrão. Abra `index.html` para explorar, editar e exportar; `graph.json` mantém os dados do grafo. Cada vista também é gravada como SVG (`diagram.svg`, ou `diagram--.svg` quando há várias vistas), que pode ser incorporado como imagem em um README, pull request ou wiki. - -Depois de editar na página, **Mais → Salvar alterações** no Chrome ou no Edge regrava a página, o `graph.json` e os SVG no lugar, depois que você escolhe a pasta do diagrama uma vez. Outros navegadores salvam só o `graph.json`: coloque-o na pasta e gere de novo a página e os SVG com `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. - -
-Executar o exemplo do Jeepay com onze vistas baseado em código-fonte - -Selecione sua cópia local do código-fonte do Jeepay para verificar as evidências: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Abra `output/jeepay/index.html`; os onze SVG estão no mesmo diretório. Consulte o [README do corpus](../../examples/jeepay) para conhecer a revisão do código-fonte e o procedimento de atualização. - -
- -## Mantenha os diagramas em sincronia com o código - -Um diagrama gerado com a raiz do repositório registra onde cada componente é definido, a linha por trás de cada relação sustentada pelo código (uma chamada, uma chave estrangeira) e uma impressão digital de cada arquivo para o qual aponta. A validação com `--repo-root` deixa passar as linhas que apenas mudaram de lugar e falha quando o código por trás do diagrama mudou: uma linha registrada foi reescrita, uma chamada foi removida, código novo toca um componente desenhado sem relação que o cubra, ou um nome usado pelo diagrama desapareceu. O erro mostra o código antigo e o novo e indica os elementos e textos a atualizar. Adicione este job ao seu CI; ele não precisa de build, login nem token, e o histórico completo (`fetch-depth: 0`) permite comparar com essas impressões digitais: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Para ver o impacto no pull request, adicione `--changes changes.md` à linha de validate e, quando falhar, publique o arquivo como comentário, por exemplo com `gh pr comment "$PR" --body-file changes.md` (requer `pull-requests: write`). Ele lista, por visão, os elementos que cada mudança toca, o arquivo e a linha, e o código antigo e o novo. A página regenerada após `--fix` também marca esses elementos e lista as mudanças ao lado dos pontos-chave. - -Quando falhar, peça à habilidade para atualizar o diagrama: - -```text -$qgraphflow:q-flow O CI diz que docs/qgraphflow/order-sequence está desatualizado. Atualize-o. -``` - -A habilidade realinha todas as âncoras, lista cada mudança em `meta.sourceDrift` do grafo, atualiza apenas os elementos que esses itens indicam e gera de novo a página e os SVG, mantendo as posições e os textos que você editou. Ela não redesenha o diagrama. - -Adicione `--compare HEAD` ao regenerar para ver o que uma atualização mudou: a página colore os elementos adicionados e alterados, lista os removidos ao lado dos pontos-chave e não altera `graph.json`. - -## O que cada um dos onze tipos de diagrama responde - -| Vista · PNG | Pergunta principal | Escopo do exemplo | -| --- | --- | --- | -| Arquitetura de capacidades da plataforma | Quais capacidades a plataforma oferece? | Zonas de capacidades e matrizes | -| Arquitetura em camadas de engenharia | Como o código do projeto é organizado? | Camadas de engenharia e suporte compartilhado | -| Arquitetura de relações entre componentes | Quais limites de responsabilidade colaboram no sistema? | Canais, orquestração de transações, preços, risco, estoque, pagamento, pedidos, eventos e execução de pedidos | -| Fluxograma | Como cada decisão se ramifica e converge? | Falta de estoque, recusa de risco, compensação de falha de pagamento e confirmação bem-sucedida | -| Sequência | Em que ordem uma solicitação faz chamadas e recebe retornos? | Fluxo principal de compra bem-sucedida e OrderPaid assíncrono | -| ER | Como os dados centrais se relacionam? | Carrinho, pedidos, itens, pagamentos, reservas de estoque e pacotes | -| Implantação | Onde ficam as unidades de execução e como se conectam? | Borda, Kubernetes, serviços de dados, pagamento e redes de armazém e logística | -| Classes | Como objetos de domínio e contratos do código dependem entre si? | Serviço de aplicação Checkout, Order e quatro portas | -| Estados | Quais eventos e condições de guarda fazem um pedido avançar? | Pagamento, execução do pedido, cancelamento, reembolso e encerramento | -| Casos de uso | Quais capacidades cada ator possui? | Comprador, lojista, depósito e atendimento | -| Fluxo de dados | Por quais transformações e armazenamentos os ativos de dados passam? | Carrinho, decisões de transação, eventos de pedidos, armazém e logística e comprovantes de entrega | - -Este modelo conceitual demonstra o QGraphFlow e não corresponde a um repositório de comércio específico. O exemplo `graph.json` não inventa caminhos de código e marca as evidências das relações como `inference`. Diagramas reais precisam de código, DDL, configuração, testes e requisitos aceitos rastreáveis. - -## Desenvolvimento e contribuição - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -São necessários Node.js 22 ou posterior, npm, tar, zip e unzip. Ao relatar problemas, inclua um grafo mínimo sem informações sensíveis, versões do cliente e navegador e passos de reprodução. - -Documentação de referência (em inglês): [Fontes de evidência](../../skills/q-flow/references/evidence-sources.md) · [Formato dos grafos](../../skills/q-flow/references/graph-schema.md) · [Consulta guiada](../../skills/q-flow/references/guided-intake.md) · [Desenvolvimento e aceitação do Viewer](../../skills/q-flow/references/viewer-development.md) · [Composição de diagramas](../../skills/q-flow/references/visual-contract.md) - -## Licença e atribuição - -[MIT](../../LICENSE) · [Avisos de terceiros](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow é um projeto independente sob a licença MIT. Os cenários deste documento são exemplos conceituais e não representam a arquitetura de produção de nenhuma empresa real. - -## Visões gerais de arquitetura - -A arquitetura agora inclui relações entre componentes, capacidades da plataforma e camadas de engenharia. Descreva o objeto e a pergunta; a habilidade escolhe o modelo. As coleções solicitadas podem conter várias vistas de arquitetura com edições independentes. - -```text -$qgraphflow:q-flow Analise as capacidades da plataforma e as formas de integração de negócio do projeto atual e gere uma visão geral de capacidades da plataforma em chinês. -$qgraphflow:q-flow Analise a organização do projeto atual e suas camadas de componentes e gere visões gerais em chinês do projeto inteiro e de uma seção de um componente. -$qgraphflow:q-flow Gere uma visão geral em inglês das capacidades da plataforma deste projeto e mostre como os módulos de aplicação se integram. -``` - -Consulte [examples/jeepay](../../examples/jeepay) para ver as vistas de arquitetura de plataforma, engenharia e relações entre componentes baseadas em código-fonte real. Desbloqueie uma visão geral para reordenar cartões dentro de uma camada ou editar textos. Salvar mantém todas as vistas; redefinir restaura apenas a atual. diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md deleted file mode 100644 index 50b41bf..0000000 --- a/docs/readme/README.ru.md +++ /dev/null @@ -1,317 +0,0 @@ -
- -

QGraphFlow

- -### Превратите сложный код в диаграммы для исследования. - -Проследите путь. Проверьте основания. Поделитесь одним автономным файлом. - -💡 Вдохновлено проектом Cocoon-AI/architecture-diagram-generator — спасибо за идею. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Онлайн-демо](https://supermax92.github.io/qgraphflow/) · [Первые шаги](#первые-шаги) · [Установка для клиентов](#установка) · [Сообщить о проблеме](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Поддерживаются одиннадцать типов диаграмм: архитектура возможностей платформы, архитектура инженерных слоёв, архитектура связей компонентов, блок-схема, последовательность, ER, развёртывание, классы, состояния, варианты использования и поток данных.* - -QGraphFlow создаёт интерактивные диаграммы программных систем из кода, схем данных, конфигурации и требований. Основания связей можно проверить, а результат — передать как автономный HTML. - -**Чем отличается:** одиннадцать типов диаграмм в одном навыке, тип доказательства для каждой связи и строка кода за каждой связью, подтверждённой кодом, автоматическая раскладка, редактирование прямо на странице и никаких сетевых запросов ни от скриптов плагина, ни от самого Viewer. - -![Интерактивная демонстрация нескольких видов Jeepay: архитектура связей компонентов, последовательность и ER](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -На примере реального исходного кода Jeepay переключайтесь между архитектурой связей компонентов, диаграммой последовательности и ER, изучая компоненты и связи вызовов. [Посмотреть GIF в исходном размере](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Демонстрация сложной диаграммы последовательности** - -![Пошаговое рисование сложной диаграммы последовательности: участники, линии жизни, сообщения, полосы активации и вложенные комбинированные фрагменты](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Вымышленный сценарий электронной торговли содержит 9 участников, 29 сообщений и 6 комбинированных фрагментов: повторные попытки резервирования, вложенные ветви, параллельную обработку, компенсацию сбоев и асинхронные обратные вызовы. Анимация постепенно показывает готовую диаграмму, раскрывая её структуру и детали. [Посмотреть GIF в исходном размере](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Одна команда устанавливает навык для Claude Code, Codex, Cursor и Qoder; установка в виде плагина и другие клиенты описаны в разделе [Установка](#установка). - -- **Исследование:** поиск, масштабирование и перемещение холста; назначение компонентов, входящие и исходящие связи. - -- **Проверка:** файлы, строки, символы и явно обозначенная неопределённость в узлах и связях. - -- **Редактирование:** разблокировка расположения, изменение текста и перемещение элементов; сброс при необходимости. - -- **Обмен:** автономный HTML или экспорт всей диаграммы в SVG / PNG. - -Основанный на реальном коде [корпус Jeepay](../../examples/jeepay) содержит все одиннадцать видов, используемых CI и онлайн-демонстрацией. - -## Первые шаги - -После установки откройте свой рабочий проект в клиенте и выберите навык `q-flow`. Примеры используют `/q-flow` в Claude Code; в Codex используйте пункт `$q-flow` или `$qgraphflow:q-flow`, который действительно предлагает ваш клиент. Ещё не установили? Сначала прочитайте раздел [Установка](#установка). - -### 1. Пустой ввод: Не знаете, с чего начать - -Вызовите навык без дополнительных требований: - -```text -/q-flow -``` - -Навык поможет выбрать часть для анализа и вопрос, на который должна ответить диаграмма. Рисование начнётся, когда необходимая информация будет ясна. - -### 2. Вопрос о возможностях: Узнать, что можно нарисовать - -```text -/q-flow Какие типы диаграмм ты можешь рисовать? На какие вопросы отвечает каждый тип? Я только что принял проект; сначала расскажи о своих возможностях и предложи, с чего начать. -``` - -Сначала узнайте назначение одиннадцати типов диаграмм, затем решите, что изучать: структуру проекта, порядок вызовов, связи данных или что-то другое. - -### 3. Неопределённый ввод: Есть только общая цель - -```text -/q-flow Помоги нарисовать этот проект. Я хочу как можно быстрее его понять. -``` - -Не нужно заранее указывать тип диаграммы. Навык определит подходящий вид по проекту и вашей цели и задаст вопросы, если необходимой информации не хватает. - -### 4. Точный ввод: Задать границы и запросить детали рисунка - -Замените названия и шаги ниже процессами, которые действительно есть в вашем проекте: - -```text -/q-flow Проанализируй создание заказа в текущем проекте и создай диаграмму последовательности на китайском языке. -Включи точку входа запроса, расчёт цены, резервирование запасов, авторизацию платежа и сохранение заказа. -Сохрани синхронные вызовы, асинхронные сообщения, парные возвраты, полосы активации, условные ветви, повторные попытки и компенсацию сбоев, которые действительно есть в исходниках. Не опускай детали ради краткости. -Укажи исходные файлы и номера строк компонентов и вызовов и сохрани результат в docs/qgraphflow/order-sequence/. -``` - -Чётко задайте предмет, вопрос, уровень детализации и место вывода, чтобы начать сразу. Диаграмма сохраняет только факты, подтверждённые доказательствами. - -### 5. Дальнейшее уточнение: Раскрыть часть предыдущей диаграммы - -После получения результата продолжите в том же разговоре: - -```text -/q-flow Раскрой резервирование запасов из предыдущей диаграммы последовательности отдельной блок-схемой на китайском языке. -Покажи все ветви проверки запасов, успешного резервирования, повторяемых сбоев, предела повторных попыток и освобождения запасов. Следуй исходному коду и не добавляй отсутствующих в нём шагов. -``` - -Сначала рассмотрите целое, затем углубитесь в один шаг. Можно также запросить дополнительные детали существующей диаграммы или проверить её связи. - -## Установка - -Нужны Node.js 22 или новее и клиент с поддержкой плагинов и настроенным доступом к модели. - -### Быстрая установка - -```bash -npx skills add supermax92/qgraphflow -``` - -Проверено с `skills` 1.7.0 для Claude Code, Codex, Cursor и Qoder. Команда спросит, в какие клиенты устанавливать; `-a claude-code` задаёт клиент сразу, а `-g` устанавливает навык для пользователя, а не для текущего проекта. Навык устанавливается как `q-flow`, без префикса `qgraphflow:`, который дают способы установки плагина ниже. - -Чтобы установить его как плагин, выполните шаги ниже. В [Qoder Desktop](#qoder-desktop) можно установить плагин из Marketplace и пропустить шаг 1. - -### 1. Скачайте плагин - -Получите плагин с npmjs.com — без учётной записи, входа и токена. Создайте отдельный каталог вне своего рабочего проекта: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Теперь вы в корневом каталоге плагина. **Загрузка через npm не устанавливает плагин в клиент автоматически** — перейдите к шагу 2. Пакет также даёт команду `qgraphflow`, которая используется в разделе [Синхронизация диаграмм с кодом](#синхронизация-диаграмм-с-кодом). - -Все команды ниже выполняйте из **корневого каталога плагина, содержащего `skills/`**. - -### 2. Установите в свой клиент - -#### Codex App / CLI - -В терминале должен быть доступен установленный Codex CLI: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Начните новую сессию, введите `$` и выберите `qgraphflow:q-flow`. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Начните новую сессию и введите `/q-flow` (или полное имя `/qgraphflow:q-flow`). - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Начните новую сессию и выберите `q-flow`. - -#### Qoder Desktop - -**Рекомендуется:** Откройте **Settings → Plugins → Marketplace**, найдите **QGraphFlow** или **代码图谱可视化** и установите плагин. Начните новый сеанс и выберите `q-flow`. - -Для локальной установки выполните шаг 1, затем откройте **Settings → Plugins → Custom → Import** и импортируйте весь корневой каталог плагина. Начните новый сеанс и выберите `q-flow`. - -#### Cursor - -Скопируйте всё содержимое корневого каталога плагина, включая скрытые файлы, в: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Убедитесь, что там есть `.cursor-plugin/plugin.json`, перезагрузите окно и найдите `q-flow` в **Customize**. Если уже установлена старая версия, сначала сделайте резервную копию; не смешивайте старые и новые файлы. - -### 3. Начните работу - -Откройте свой рабочий проект в клиенте, начните новую сессию и выберите навык. Опишите требования по примерам в разделе [Первые шаги](#первые-шаги). После генерации откройте выходной HTML в браузере. - -Хотите собрать самостоятельно? См. [инструкции по сборке из исходников](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Быстрое использование - -Примеры используют `$qgraphflow:q-flow` в Codex. Если клиент показывает `$q-flow`, выберите этот пункт. Для других клиентов используйте способ вызова навыка, указанный выше. - -**Не знаете, с чего начать?** Вызовите навык, затем выберите предмет и вопрос по подсказке. - -```text -$qgraphflow:q-flow -``` - -**Цель уже ясна?** Укажите, какую часть нарисовать и что требуется понять. Тип диаграммы заранее выбирать не нужно. - -### Пример 1: Понять архитектуру проекта - -```text -$qgraphflow:q-flow Проанализируй текущий проект и создай диаграмму архитектуры на китайском языке: обязанности модулей, зависимости и границы системы. -``` - -Подходит для первого знакомства с общей структурой проекта. - -### Пример 2: Проследить бизнес-процесс - -```text -$qgraphflow:q-flow Проанализируй создание заказа и создай диаграмму последовательности на китайском языке: расчёт цены, резерв запасов, оплата и сохранение заказа, включая ветки сбоев. -``` - -Замените создание заказа и его шаги реальным процессом проекта. Продолжите в том же разговоре: - -```text -$qgraphflow:q-flow Подробно раскрой резерв запасов из предыдущей диаграммы отдельной блок-схемой на китайском языке с обработкой успеха и сбоев. -``` - -По умолчанию результаты находятся в `docs/qgraphflow/`. Откройте `index.html` для исследования, редактирования и экспорта; `graph.json` хранит данные графа. Каждый вид также записывается как SVG (`diagram.svg`, а для нескольких видов — `diagram--.svg`), который можно встроить как изображение в README, pull request или вики. - -После правок на странице команда **Ещё → Сохранить изменения** в Chrome или Edge перезаписывает страницу, `graph.json` и SVG на месте, когда вы один раз выберете каталог диаграммы. Другие браузеры сохраняют только `graph.json`: положите его в этот каталог и пересоздайте страницу и SVG командой `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. - -
-Запустить пример Jeepay с одиннадцатью видами на основе исходного кода - -Выберите локальную копию исходников Jeepay для проверки доказательств: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Откройте `output/jeepay/index.html`; одиннадцать SVG находятся в том же каталоге. Версия исходников и процедура обновления описаны в [README корпуса](../../examples/jeepay). - -
- -## Синхронизация диаграмм с кодом - -Диаграмма, созданная с указанием корня репозитория, запоминает, где определён каждый компонент, строку за каждой связью, подтверждённой кодом (вызов, внешний ключ), и отпечаток каждого файла, на который она ссылается. Проверка с `--repo-root` пропускает строки, которые только сдвинулись, и завершается ошибкой, когда изменился сам код за диаграммой: записанная строка переписана, вызов удалён, новый код затрагивает нарисованный компонент, но не покрыт ни одной связью, или имя, которое использует диаграмма, исчезло. В сообщении показаны старый и новый код и названы элементы и тексты, которые нужно обновить. Добавьте эту задачу в CI — ей не нужны сборка, вход или токен; полная история (`fetch-depth: 0`) нужна, чтобы сравнить код с отпечатками: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Чтобы увидеть затронутые места прямо в pull request, добавьте `--changes changes.md` в строку validate и при ошибке опубликуйте файл комментарием, например `gh pr comment "$PR" --body-file changes.md` (нужно разрешение `pull-requests: write`). В нём по каждому представлению перечислены элементы, которых касается изменение, файл и строка, а также старый и новый код. Страница, заново созданная после `--fix`, тоже отмечает эти элементы и перечисляет изменения рядом с ключевыми выводами. - -Если проверка не прошла, попросите навык обновить диаграмму: - -```text -$qgraphflow:q-flow CI сообщает, что диаграмма docs/qgraphflow/order-sequence устарела. Обнови её. -``` - -Навык выравнивает все якоря по текущему коду, записывает каждое изменение в `meta.sourceDrift` графа, обновляет только названные там элементы и пересоздаёт страницу и SVG, сохраняя ваши позиции и тексты. Заново диаграмму он не рисует. - -Добавьте `--compare HEAD` при повторной генерации, чтобы увидеть, что изменило обновление: страница выделяет цветом добавленные и изменённые элементы, перечисляет удалённые рядом с ключевыми выводами и не трогает `graph.json`. - -## На какие вопросы отвечает каждый из одиннадцати типов диаграмм - -| Вид · PNG | Главный вопрос | Область примера | -| --- | --- | --- | -| Архитектура возможностей платформы | Какие возможности есть у платформы? | Зоны возможностей и матрицы | -| Архитектура инженерных слоёв | Как организован код проекта? | Инженерные слои и общая поддержка | -| Архитектура связей компонентов | Какие границы ответственности взаимодействуют в системе? | Каналы, оркестрация транзакций, цены, риски, запасы, платежи, заказы, события и исполнение заказов | -| Блок-схема | Как ветвится и сходится каждая точка решения? | Нехватка запасов, отказ по риску, компенсация сбоя оплаты и успешная фиксация | -| Последовательность | В каком порядке запрос выполняет вызовы и получает возвраты? | Основной путь успешной покупки и асинхронный OrderPaid | -| ER | Как связаны основные данные? | Корзина, заказы, позиции, платежи, резервы запасов и посылки | -| Развёртывание | Где размещены единицы исполнения и как они соединены? | Периметр, Kubernetes, сервисы данных, платежи и складские/логистические сети | -| Классы | Как зависят объекты домена и контракты кода? | Прикладной сервис Checkout, Order и четыре порта | -| Состояния | Какие события и охранные условия продвигают заказ? | Оплата, исполнение, отмена, возврат денег и закрытие | -| Варианты использования | Какие возможности есть у каждого участника? | Покупатель, продавец, склад и поддержка клиентов | -| Поток данных | Через какие преобразования и хранилища проходят данные? | Корзина, решения по транзакциям, события заказов, склад/логистика и подтверждения доставки | - -Это концептуальная демонстрация QGraphFlow, а не модель конкретного торгового репозитория. Пример `graph.json` не выдумывает пути к коду и обозначает основания связей как `inference`. Диаграммы реальных проектов требуют прослеживаемых исходников, DDL, конфигурации, тестов и согласованных требований. - -## Разработка и участие - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -Нужны Node.js 22 или новее, npm, tar, zip и unzip. В сообщении о проблеме приложите минимальный граф без конфиденциальных данных, версии клиента и браузера и шаги воспроизведения. - -Справочная документация (на английском): [Источники оснований](../../skills/q-flow/references/evidence-sources.md) · [Формат графов](../../skills/q-flow/references/graph-schema.md) · [Уточнение запроса](../../skills/q-flow/references/guided-intake.md) · [Разработка и приёмка Viewer](../../skills/q-flow/references/viewer-development.md) · [Композиция диаграмм](../../skills/q-flow/references/visual-contract.md) - -## Лицензия и принадлежность - -[MIT](../../LICENSE) · [Уведомления третьих сторон](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow — независимый проект под лицензией MIT. Сценарии в этом документе являются концептуальными примерами и не представляют производственную архитектуру какой-либо реальной компании. - -## Обзоры архитектуры - -Архитектура теперь включает связи компонентов, возможности платформы и инженерные слои. Опишите предмет и вопрос; навык выберет шаблон. Запрошенные коллекции могут содержать несколько архитектурных видов с независимыми правками. - -```text -$qgraphflow:q-flow Проанализируй возможности платформы и способы бизнес-интеграции текущего проекта и создай обзор возможностей платформы на китайском языке. -$qgraphflow:q-flow Проанализируй организацию текущего проекта и слои компонентов и создай китайские обзоры всего проекта и среза одного компонента. -$qgraphflow:q-flow Создай обзор возможностей платформы этого проекта на английском языке и покажи, как интегрируются прикладные модули. -``` - -См. [examples/jeepay](../../examples/jeepay) для архитектурных видов платформы, инженерной организации и связей компонентов на основе реального кода. Разблокируйте обзор, чтобы менять порядок карточек в слое или редактировать текст. Сохранение удерживает все виды; сброс восстанавливает только текущий. diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md deleted file mode 100644 index 972d1c2..0000000 --- a/docs/readme/README.zh-CN.md +++ /dev/null @@ -1,317 +0,0 @@ -
- -

QGraphFlow

- -### 把复杂代码,变成可以探索的图。 - -跟随路径,查看证据,用一个离线文件分享。 - -💡 灵感来自 Cocoon-AI/architecture-diagram-generator,感谢原作者的启发。 - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[在线演示](https://supermax92.github.io/qgraphflow/) · [快速入门](#快速入门) · [客户端安装](#安装指南) · [反馈问题](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*支持十一类图:【平台能力架构图、工程分层架构图、组件关系架构图、流程图、时序图、ER 图、部署图、类图、状态图、用例图、数据流图】* - -QGraphFlow 从源码、数据结构、配置和需求生成交互式软件图,让关系有据可查,并将结果交付为可分享的离线 HTML。 - -**差异在哪:** 一个技能覆盖十一类图,每条关系都标明证据类别,有代码支撑的关系还记录对应的源码行,自动布局,能直接在页面里编辑,插件脚本和 Viewer 本身不发任何网络请求。 - -![Jeepay 多视图交互演示:组件关系架构图、时序图与 ER 图](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.zh-CN.hero.gif) - -以 Jeepay 真实源码为例,在组件关系架构图、时序图与 ER 图之间切换,探索组件与调用关系。[查看原尺寸 GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.zh-CN.hero.gif) - -**复杂时序图展示** - -![复杂时序图逐步绘制:参与者、生命线、消息、激活条与嵌套组合片段](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.zh-CN.sequence-drawing.gif) - -虚构电商场景包含 9 个参与者、29 条消息和 6 个组合片段,覆盖库存重试、嵌套分支、并行处理、失败补偿与异步回调。动画逐步呈现已生成的图形,展示复杂时序图的结构与细节。[查看原尺寸 GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.zh-CN.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -一条命令即可为 Claude Code、Codex、Cursor 和 Qoder 装好技能;以插件方式安装和其他客户端见[安装指南](#安装指南)。 - -- **探索:** 搜索定位、缩放和平移画布,查看组件职责与上下游关系。 - -- **核验:** 从节点或连线查看详情,核对源码文件、行号、符号和明确标注的不确定性。 - -- **编辑:** 解锁后修改文字、移动元素;不满意时一键重置。 - -- **分享:** 打开离线 HTML,或将完整图导出为 SVG / PNG。 - -The real-source [Jeepay corpus](../../examples/jeepay) contains all eleven views used by CI and the live demo. - -## 快速入门 - -安装后,在客户端打开你的业务项目,选择 `q-flow` 技能。以下以 Claude Code 的 `/q-flow` 为例;Codex 中使用客户端实际提供的 `$q-flow` 或 `$qgraphflow:q-flow` 入口。还未安装?先看[安装指南](#安装指南)。 - -### 1. 空白输入:不知道从哪里开始 - -只调用技能,不附加需求: - -```text -/q-flow -``` - -技能会引导你选择要分析的部分,以及希望图回答的问题;必要信息明确后开始绘图。 - -### 2. 询问能力:先了解能画什么 - -```text -/q-flow 你能绘制哪些类型的图?每类图适合回答什么问题?我刚接手一个项目,请先介绍能力并建议一个起点。 -``` - -先了解十一类图的用途,再决定看项目结构、调用顺序、数据关系还是其他内容。 - -### 3. 模糊输入:只有一个大致目标 - -```text -/q-flow 帮我画一下这个项目,我想尽快看懂它。 -``` - -不用先指定图类型。技能会根据项目和你的目标确定合适的视图,缺少必要信息时再追问。 - -### 4. 精准输入:明确范围并要求绘制细节 - -将下面的业务名称和步骤替换成项目中实际存在的流程: - -```text -/q-flow 分析当前项目的订单创建流程,生成中文时序图。 -覆盖请求入口、价格计算、库存预占、支付授权和订单落库。 -保留源码中实际存在的同步调用、异步消息、成对返回、激活条、条件分支、重试和失败补偿,不要为了简洁省略细节。 -标明组件与调用的源码文件和行号,将结果保存到 docs/qgraphflow/order-sequence/。 -``` - -把对象、问题、详细程度和输出位置说清楚,就能直接开始;图中只保留有证据支持的事实。 - -### 5. 继续细化:展开上一张图的局部 - -在生成结果后,于同一对话中继续: - -```text -/q-flow 展开上一张时序图中的库存预占步骤,单独生成中文流程图。 -完整展示库存校验、预占成功、可重试失败、重试上限和释放库存的分支,以源码为准,不添加代码中没有的步骤。 -``` - -先看整体,再深入一个步骤;也可以继续要求补充已有图的细节或核验其中的关系。 - -## 安装指南 - -准备 Node.js 22 及以上版本,以及已配置好模型访问、支持插件功能的客户端。 - -### 快速安装 - -```bash -npx skills add supermax92/qgraphflow -``` - -已用 `skills` 1.7.0 在 Claude Code、Codex、Cursor 和 Qoder 上实测。命令会询问装到哪些客户端;`-a claude-code` 可直接指定,`-g` 改为装到当前用户而不是当前项目。这样装上的技能名是 `q-flow`,不带下文插件安装方式里的 `qgraphflow:` 前缀。 - -如需以插件方式安装,按以下步骤操作。[Qoder Desktop](#qoder-desktop) 可直接从插件商城安装,跳过第 1 步。 - -### 1. 下载插件 - -从 npmjs.com 获取插件,无需账号、登录或令牌。在业务项目之外创建独立目录: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -此时已进入插件根目录。**npm 下载不会自动完成客户端安装**,请继续第 2 步。这个包还提供 `qgraphflow` 命令,[让图和代码保持同步](#让图和代码保持同步)一节会用到。 - -以下终端命令均在**包含 `skills/` 的插件根目录**执行。 - -### 2. 选择客户端安装 - -#### Codex App / CLI - -终端需已安装 Codex CLI: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -新建会话,输入 `$`,选择 `qgraphflow:q-flow`。 - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -新建会话,输入 `/q-flow`(或完整名称 `/qgraphflow:q-flow`)。 - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -新建会话,选择 `q-flow`。 - -#### Qoder Desktop - -**推荐:**打开 **Settings → Plugins → Marketplace**,搜索 **QGraphFlow** 或 **代码图谱可视化**,安装插件。新建会话,选择 `q-flow`。 - -如需本地安装,先完成第 1 步,再打开 **Settings → Plugins → Custom → Import**,导入完整的插件根目录。新建会话,选择 `q-flow`。 - -#### Cursor - -将插件根目录中的全部内容(含隐藏文件)复制到: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -确认其中存在 `.cursor-plugin/plugin.json`,重新加载窗口,在 **Customize** 中找到 `q-flow`。若已有旧版本,先备份,勿混合新旧文件。 - -### 3. 开始使用 - -在客户端打开你的业务项目,新建会话并选择技能,按[快速入门](#快速入门)中的示例描述需求。生成后,用浏览器打开输出的 HTML。 - -需要自行构建?参见[源码构建说明](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)。 - -## 快速使用 - -以下以 Codex 的 `$qgraphflow:q-flow` 入口为例;如果客户端显示 `$q-flow`,请选择它实际提供的入口。其他客户端使用上方对应的技能入口。 - -**不知道从哪里开始?** 直接调用,按提示选择要分析的部分和想了解的问题。 - -```text -$qgraphflow:q-flow -``` - -**目标已经明确?** 一句话说明“画哪个部分+想看什么”,无需先选择图类型。 - -### 示例一:看懂项目架构 - -```text -$qgraphflow:q-flow 分析当前项目,生成中文架构图,展示主要模块的职责、依赖关系和系统边界。 -``` - -适合初次接触项目,先了解整体结构。 - -### 示例二:追踪业务调用 - -```text -$qgraphflow:q-flow 分析订单创建流程,生成中文时序图,展示价格计算、库存预占、支付和订单落库的调用顺序,并标明失败分支。 -``` - -将“订单创建”及相关步骤替换成项目中的实际业务流程。看完后,在同一对话中继续追问: - -```text -$qgraphflow:q-flow 展开上一张图中的库存预占步骤,单独生成中文流程图,展示成功与失败的处理流程。 -``` - -结果默认保存在 `docs/qgraphflow/` 下:打开 `index.html` 即可交互查看、编辑和导出,`graph.json` 保留图数据。每个视图还会写出一份 SVG(`diagram.svg`,多视图时为 `diagram--.svg`),可以直接作为图片嵌进 README、PR 或 Wiki。 - -在页面里编辑后,用 Chrome 或 Edge 执行「更多 → 保存修改」并选一次图所在的文件夹,即可原地重写页面、`graph.json` 和 SVG。其他浏览器只能保存 `graph.json`:把它放回该文件夹,再用 `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` 重新生成页面和 SVG。 - -
-Run the eleven-view Jeepay source example - -Select your Jeepay source checkout to verify the evidence: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Open `output/jeepay/index.html`; its eleven SVGs are in the same directory. See the [corpus README](../../examples/jeepay) for the source revision and refresh procedure. - -
- -## 让图和代码保持同步 - -带仓库根目录生成的图会记下每个组件定义在哪里、每条有代码支撑的关系所在的那一行(调用、外键等),以及它指向的每个文件的内容指纹。用 `--repo-root` 校验时,只是挪了位置的行会自动对上、照常通过;只有图背后的代码真的变了才会失败:记录的那一行被改写、某个调用被删掉、新代码碰到了图里画的组件却没有对应的关系,或者图里用到的名字已经不存在。错误里会给出改动前后的代码,并指出要更新的元素和文字。把下面这个任务加进 CI,不需要构建、登录或令牌;拉取完整历史(`fetch-depth: 0`)才能和这些指纹比对: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -想在 PR 里直接看到受影响的地方,就在 validate 那一行加上 `--changes changes.md`,失败时把这个文件贴成评论,例如 `gh pr comment "$PR" --body-file changes.md`(需要 `pull-requests: write` 权限)。它按视图列出每处改动碰到的元素、文件和行号,以及改动前后的代码。执行 `--fix` 后重新生成的页面也会标出这些元素,并在要点旁列出这些改动。 - -失败后,让技能刷新这张图: - -```text -$qgraphflow:q-flow CI 提示 docs/qgraphflow/order-sequence 的图过时了,刷新一下。 -``` - -技能会把所有锚点对齐到当前代码,把每处改动列进图的 `meta.sourceDrift`,只更新这些条目指出的元素,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 - -重新生成时加上 `--compare HEAD`,就能看出这次刷新改了什么:页面把新增和改动的元素着色,在要点旁列出删掉的元素,`graph.json` 不受影响。 - -## 十一类图各自回答什么 - -| 视图 · PNG | 主要问题 | 本示例范围 | -| --- | --- | --- | -| 平台能力架构图 | 平台具备哪些能力? | 能力分区与矩阵 | -| 工程分层架构图 | 工程代码怎样组织? | 工程层级与共享支撑 | -| 组件关系架构图 | 系统由哪些责任边界协作? | 渠道、交易编排、价格、风控、库存、支付、订单、事件与履约 | -| 流程图 | 每个决策点如何分支和收敛? | 缺货、风控拒绝、支付失败补偿与成功提交 | -| 时序图 | 一次请求按什么顺序调用和返回? | 成功结算主链及异步 OrderPaid | -| ER 图 | 核心数据如何关联? | 购物车、订单、明细、支付、库存预占和包裹 | -| 部署图 | 运行单元放在哪里、怎样连接? | 边缘、Kubernetes、数据服务、支付和仓配网络 | -| 类图 | 领域对象和代码契约怎样依赖? | Checkout 应用服务、Order 与四个端口 | -| 状态图 | 订单受哪些事件和守卫条件推进? | 支付、履约、取消、退款和关闭 | -| 用例图 | 每类参与者拥有哪些能力? | 买家、商家、仓库与客服 | -| 数据流图 | 数据资产经过哪些变换和存储? | 购物车、交易决策、订单事件、仓配和物流回执 | - -这是用于展示 QGraphFlow 能力的概念模型,不对应某个电商仓库。`graph.json` 不伪造源码路径,关系证据统一标记为 `inference`;对真实项目绘图时,应改用源码、DDL、配置、测试和已接受需求中的可追溯证据。 - -## 开发与参与 - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -开发需要 Node.js 22 及以上版本、npm、tar、zip 和 unzip。反馈问题时,请附最小脱敏图数据、客户端和浏览器版本,以及复现步骤。 - -参考文档(英文):[证据来源](../../skills/q-flow/references/evidence-sources.md) · [图数据格式](../../skills/q-flow/references/graph-schema.md) · [需求引导](../../skills/q-flow/references/guided-intake.md) · [Viewer 开发与验收](../../skills/q-flow/references/viewer-development.md) · [图形表达约定](../../skills/q-flow/references/visual-contract.md) - -## 许可证与归属 - -[MIT](../../LICENSE) · [第三方声明](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow 是采用 MIT 许可证的独立项目。本文场景为概念示例,不代表任何真实公司的生产架构。 - -## Architecture overviews / 架构总览 - -Architecture now includes component relations, platform capabilities and engineering layers. Describe the subject and question; the skill chooses the template. Requested collections can contain multiple architecture views with independent edits. - -```text -$qgraphflow:q-flow 分析当前项目的平台能力和业务接入方式,生成中文平台能力总览。 -$qgraphflow:q-flow 分析当前工程组织和组件分层,生成工程整体与一个组件剖面的中文总览。 -$qgraphflow:q-flow Generate an English platform capability overview of this project and show how application modules integrate. -``` - -See [examples/jeepay](../../examples/jeepay) for real-source platform, engineering and component relationship architecture views. Unlock an overview to reorder cards within a layer or edit text. Save keeps all views; reset restores only the current one. diff --git a/examples/jeepay/README.md b/examples/jeepay/README.md index b3d2b77..7a72acf 100644 --- a/examples/jeepay/README.md +++ b/examples/jeepay/README.md @@ -2,7 +2,7 @@ The only business dataset used by CI, Pages and package smoke tests is the public [Jeepay repository](https://github.com/jeequan/jeepay). `source.json` records the exact revision and SHA-256 of every referenced source file. No Java source, credentials or developer machine paths are distributed here. -The collection contains eleven views: platform capabilities, engineering layers, component relationships, unified-order flowchart and sequence, payment ER, Compose deployment, payment classes, order states, API use cases and unified-order data flow. All inputs contain facts and source anchors; generated coordinates and routing snapshots are deliberately excluded. +The collection contains nine views: component relationships, unified-order flowchart and sequence, payment ER, Compose deployment, payment classes, order states, API use cases and unified-order data flow. All inputs contain facts and source anchors; generated coordinates and routing snapshots are deliberately excluded. CI checks out the revision declared in `source.json`, verifies every node source and relationship site, and computes fresh layouts. Assertions cover preserved facts, valid notation and geometry, export, saving, cancellation and selected-view isolation. They do not lock a particular diagram's dimensions, node count, crossing count, candidate count or solver strategy. @@ -14,7 +14,7 @@ node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" ``` -To refresh the corpus after reviewing updated Jeepay source and updating its eleven diagrams under `docs/qgraphflow/`, run: +To refresh the corpus after reviewing updated Jeepay source and updating its nine diagrams under `docs/qgraphflow/`, run: ```bash node scripts/refresh-jeepay-fixtures.mjs "$JEEPAY_REPO_ROOT" diff --git a/examples/jeepay/capabilities.graph.json b/examples/jeepay/capabilities.graph.json deleted file mode 100644 index 94a696d..0000000 --- a/examples/jeepay/capabilities.graph.json +++ /dev/null @@ -1,270 +0,0 @@ -{ - "meta": { - "title": "Jeepay 平台能力架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "项目核心支付能力", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "能力卡片以源码中的控制器和服务为准;退款、转账和分账是独立入口。", - "本图呈现能力与关键支撑,不代表所有能力均在同一请求链路中。" - ], - "architectureView": "capabilities", - "viewId": "jeepay-capabilities" - }, - "nodes": [ - { - "id": "unified", - "label": "UnifiedOrderController", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/UnifiedOrderController.java", - "lineStart": 44, - "lineEnd": 44, - "kind": "source" - }, - "subtitle": "统一下单入口", - "tags": [ - "core" - ], - "overviewText": [ - "校验商户签名后选择支付方式,生成支付订单。" - ] - }, - { - "id": "refund", - "label": "RefundOrderController", - "kind": "business", - "module": "refund", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/refund/RefundOrderController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "退款订单入口", - "overviewText": [ - "面向已支付订单发起渠道退款。" - ] - }, - { - "id": "transfer", - "label": "TransferOrderController", - "kind": "business", - "module": "transfer", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/transfer/TransferOrderController.java", - "lineStart": 55, - "lineEnd": 55, - "kind": "source" - }, - "subtitle": "转账订单入口", - "overviewText": [ - "向渠道发起转账。" - ] - }, - { - "id": "division", - "label": "PayOrderDivisionExecController", - "kind": "business", - "module": "division", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/division/PayOrderDivisionExecController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "分账执行入口", - "overviewText": [ - "按商户请求执行支付订单分账。" - ] - }, - { - "id": "process", - "label": "PayOrderProcessService", - "kind": "component", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 40, - "lineEnd": 40, - "kind": "source" - }, - "subtitle": "支付成功后的订单处理", - "overviewText": [ - "确认支付成功后处理订单业务。" - ] - }, - { - "id": "notify", - "label": "PayMchNotifyService", - "kind": "component", - "module": "notification", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayMchNotifyService.java", - "lineStart": 45, - "lineEnd": 45, - "kind": "source" - }, - "subtitle": "保存并推送商户通知", - "overviewText": [ - "保存通知记录并推送消息。" - ] - }, - { - "id": "channel", - "label": "IPaymentService", - "kind": "component", - "module": "channel", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/channel/IPaymentService.java", - "lineStart": 30, - "lineEnd": 30, - "kind": "source" - }, - "subtitle": "渠道支付接口契约", - "overviewText": [ - "定义渠道支付检查与支付调用。" - ] - }, - { - "id": "orderdb", - "label": "PayOrderService", - "kind": "data", - "module": "payment", - "source": { - "file": "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderService.java", - "lineStart": 49, - "lineEnd": 49, - "kind": "source" - }, - "subtitle": "支付订单持久化与条件更新", - "overviewText": [ - "持久化并按原状态条件更新订单。" - ] - } - ], - "edges": [ - { - "id": "c1", - "source": "unified", - "target": "channel", - "kind": "call", - "label": "调起渠道支付", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 205, - "lineEnd": 205 - } - }, - { - "id": "c2", - "source": "unified", - "target": "orderdb", - "kind": "data", - "label": "保存支付订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 201, - "lineEnd": 201 - } - }, - { - "id": "c3", - "source": "unified", - "target": "process", - "kind": "call", - "label": "处理支付结果", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 383, - "lineEnd": 383 - } - }, - { - "id": "c4", - "source": "process", - "target": "notify", - "kind": "call", - "label": "通知商户", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 60, - "lineEnd": 60 - } - }, - { - "id": "c5", - "source": "process", - "target": "orderdb", - "kind": "data", - "label": "查询订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 51, - "lineEnd": 51 - } - } - ], - "layout": { - "sections": [ - { - "id": "entry", - "title": "业务能力入口", - "mode": "grid", - "columns": 4, - "tone": "blue", - "items": [ - { - "nodeId": "unified" - }, - { - "nodeId": "refund" - }, - { - "nodeId": "transfer" - }, - { - "nodeId": "division" - } - ] - }, - { - "id": "core", - "title": "支付处理", - "mode": "row", - "tone": "green", - "items": [ - { - "nodeId": "channel" - }, - { - "nodeId": "process" - } - ] - }, - { - "id": "support", - "title": "订单与通知支撑", - "mode": "row", - "tone": "subtle", - "items": [ - { - "nodeId": "orderdb" - }, - { - "nodeId": "notify" - } - ] - } - ], - "direction": "down" - } -} diff --git a/examples/jeepay/collection.graph.json b/examples/jeepay/collection.graph.json index de7ec21..c46452f 100644 --- a/examples/jeepay/collection.graph.json +++ b/examples/jeepay/collection.graph.json @@ -1,552 +1,5 @@ { "diagrams": [ - { - "meta": { - "title": "Jeepay 平台能力架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "项目核心支付能力", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "能力卡片以源码中的控制器和服务为准;退款、转账和分账是独立入口。", - "本图呈现能力与关键支撑,不代表所有能力均在同一请求链路中。" - ], - "architectureView": "capabilities", - "viewId": "jeepay-capabilities" - }, - "nodes": [ - { - "id": "unified", - "label": "UnifiedOrderController", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/UnifiedOrderController.java", - "lineStart": 44, - "lineEnd": 44, - "kind": "source" - }, - "subtitle": "统一下单入口", - "tags": [ - "core" - ], - "overviewText": [ - "校验商户签名后选择支付方式,生成支付订单。" - ] - }, - { - "id": "refund", - "label": "RefundOrderController", - "kind": "business", - "module": "refund", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/refund/RefundOrderController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "退款订单入口", - "overviewText": [ - "面向已支付订单发起渠道退款。" - ] - }, - { - "id": "transfer", - "label": "TransferOrderController", - "kind": "business", - "module": "transfer", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/transfer/TransferOrderController.java", - "lineStart": 55, - "lineEnd": 55, - "kind": "source" - }, - "subtitle": "转账订单入口", - "overviewText": [ - "向渠道发起转账。" - ] - }, - { - "id": "division", - "label": "PayOrderDivisionExecController", - "kind": "business", - "module": "division", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/division/PayOrderDivisionExecController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "分账执行入口", - "overviewText": [ - "按商户请求执行支付订单分账。" - ] - }, - { - "id": "process", - "label": "PayOrderProcessService", - "kind": "component", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 40, - "lineEnd": 40, - "kind": "source" - }, - "subtitle": "支付成功后的订单处理", - "overviewText": [ - "确认支付成功后处理订单业务。" - ] - }, - { - "id": "notify", - "label": "PayMchNotifyService", - "kind": "component", - "module": "notification", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayMchNotifyService.java", - "lineStart": 45, - "lineEnd": 45, - "kind": "source" - }, - "subtitle": "保存并推送商户通知", - "overviewText": [ - "保存通知记录并推送消息。" - ] - }, - { - "id": "channel", - "label": "IPaymentService", - "kind": "component", - "module": "channel", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/channel/IPaymentService.java", - "lineStart": 30, - "lineEnd": 30, - "kind": "source" - }, - "subtitle": "渠道支付接口契约", - "overviewText": [ - "定义渠道支付检查与支付调用。" - ] - }, - { - "id": "orderdb", - "label": "PayOrderService", - "kind": "data", - "module": "payment", - "source": { - "file": "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderService.java", - "lineStart": 49, - "lineEnd": 49, - "kind": "source" - }, - "subtitle": "支付订单持久化与条件更新", - "overviewText": [ - "持久化并按原状态条件更新订单。" - ] - } - ], - "edges": [ - { - "id": "c1", - "source": "unified", - "target": "channel", - "kind": "call", - "label": "调起渠道支付", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 205, - "lineEnd": 205 - } - }, - { - "id": "c2", - "source": "unified", - "target": "orderdb", - "kind": "data", - "label": "保存支付订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 201, - "lineEnd": 201 - } - }, - { - "id": "c3", - "source": "unified", - "target": "process", - "kind": "call", - "label": "处理支付结果", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 383, - "lineEnd": 383 - } - }, - { - "id": "c4", - "source": "process", - "target": "notify", - "kind": "call", - "label": "通知商户", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 60, - "lineEnd": 60 - } - }, - { - "id": "c5", - "source": "process", - "target": "orderdb", - "kind": "data", - "label": "查询订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 51, - "lineEnd": 51 - } - } - ], - "layout": { - "sections": [ - { - "id": "entry", - "title": "业务能力入口", - "mode": "grid", - "columns": 4, - "tone": "blue", - "items": [ - { - "nodeId": "unified" - }, - { - "nodeId": "refund" - }, - { - "nodeId": "transfer" - }, - { - "nodeId": "division" - } - ] - }, - { - "id": "core", - "title": "支付处理", - "mode": "row", - "tone": "green", - "items": [ - { - "nodeId": "channel" - }, - { - "nodeId": "process" - } - ] - }, - { - "id": "support", - "title": "订单与通知支撑", - "mode": "row", - "tone": "subtle", - "items": [ - { - "nodeId": "orderdb" - }, - { - "nodeId": "notify" - } - ] - } - ], - "direction": "down" - } - }, - { - "meta": { - "title": "Jeepay 工程分层架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "Maven 模块与编译期依赖", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "箭头表示 pom.xml 声明的模块依赖,不表示运行时 HTTP 调用。", - "jeepay-z-codegen 是独立代码生成模块,不在支付主干分层中。" - ], - "architectureView": "engineering", - "viewId": "jeepay-engineering" - }, - "nodes": [ - { - "id": "manager", - "label": "jeepay-manager", - "kind": "component", - "module": "manager", - "source": { - "file": "jeepay-manager/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "运营管理端应用模块" - ] - }, - { - "id": "merchant", - "label": "jeepay-merchant", - "kind": "component", - "module": "merchant", - "source": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "商户管理端应用模块" - ] - }, - { - "id": "payment", - "label": "jeepay-payment", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "tags": [ - "core" - ], - "overviewText": [ - "统一支付网关应用模块" - ] - }, - { - "id": "service", - "label": "jeepay-service", - "kind": "component", - "module": "service", - "source": { - "file": "jeepay-service/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "数据库服务与持久化访问模块" - ] - }, - { - "id": "core", - "label": "jeepay-core", - "kind": "component", - "module": "core", - "source": { - "file": "jeepay-core/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "公共实体、模型与工具模块" - ] - }, - { - "id": "mq", - "label": "jeepay-components-mq", - "kind": "component", - "module": "mq", - "source": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "消息队列抽象与实现模块" - ] - }, - { - "id": "oss", - "label": "jeepay-components-oss", - "kind": "component", - "module": "oss", - "source": { - "file": "jeepay-components/jeepay-components-oss/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "对象存储组件模块" - ] - } - ], - "edges": [ - { - "id": "e1", - "source": "manager", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-manager/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e2", - "source": "merchant", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e3", - "source": "payment", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 30, - "lineEnd": 30 - } - }, - { - "id": "e4", - "source": "payment", - "target": "mq", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 42, - "lineEnd": 42 - } - }, - { - "id": "e5", - "source": "payment", - "target": "oss", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 36, - "lineEnd": 36 - } - }, - { - "id": "e6", - "source": "service", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-service/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e7", - "source": "mq", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 25, - "lineEnd": 25 - } - } - ], - "layout": { - "sections": [ - { - "id": "app", - "title": "应用入口", - "mode": "grid", - "columns": 3, - "tone": "blue", - "items": [ - { - "nodeId": "manager" - }, - { - "nodeId": "merchant" - }, - { - "nodeId": "payment" - } - ] - }, - { - "id": "domain", - "title": "持久化与公共模型", - "mode": "stack", - "tone": "green", - "items": [ - { - "nodeId": "service" - }, - { - "nodeId": "core" - } - ] - }, - { - "id": "components", - "title": "可复用组件", - "mode": "row", - "tone": "lavender", - "items": [ - { - "nodeId": "mq" - }, - { - "nodeId": "oss" - } - ] - } - ], - "direction": "down" - } - }, { "meta": { "title": "Jeepay 支付组件关系架构", diff --git a/examples/jeepay/engineering.graph.json b/examples/jeepay/engineering.graph.json deleted file mode 100644 index 94f32a3..0000000 --- a/examples/jeepay/engineering.graph.json +++ /dev/null @@ -1,277 +0,0 @@ -{ - "meta": { - "title": "Jeepay 工程分层架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "Maven 模块与编译期依赖", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "箭头表示 pom.xml 声明的模块依赖,不表示运行时 HTTP 调用。", - "jeepay-z-codegen 是独立代码生成模块,不在支付主干分层中。" - ], - "architectureView": "engineering", - "viewId": "jeepay-engineering" - }, - "nodes": [ - { - "id": "manager", - "label": "jeepay-manager", - "kind": "component", - "module": "manager", - "source": { - "file": "jeepay-manager/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "运营管理端应用模块" - ] - }, - { - "id": "merchant", - "label": "jeepay-merchant", - "kind": "component", - "module": "merchant", - "source": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "商户管理端应用模块" - ] - }, - { - "id": "payment", - "label": "jeepay-payment", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "tags": [ - "core" - ], - "overviewText": [ - "统一支付网关应用模块" - ] - }, - { - "id": "service", - "label": "jeepay-service", - "kind": "component", - "module": "service", - "source": { - "file": "jeepay-service/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "数据库服务与持久化访问模块" - ] - }, - { - "id": "core", - "label": "jeepay-core", - "kind": "component", - "module": "core", - "source": { - "file": "jeepay-core/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "公共实体、模型与工具模块" - ] - }, - { - "id": "mq", - "label": "jeepay-components-mq", - "kind": "component", - "module": "mq", - "source": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "消息队列抽象与实现模块" - ] - }, - { - "id": "oss", - "label": "jeepay-components-oss", - "kind": "component", - "module": "oss", - "source": { - "file": "jeepay-components/jeepay-components-oss/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "对象存储组件模块" - ] - } - ], - "edges": [ - { - "id": "e1", - "source": "manager", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-manager/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e2", - "source": "merchant", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e3", - "source": "payment", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 30, - "lineEnd": 30 - } - }, - { - "id": "e4", - "source": "payment", - "target": "mq", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 42, - "lineEnd": 42 - } - }, - { - "id": "e5", - "source": "payment", - "target": "oss", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 36, - "lineEnd": 36 - } - }, - { - "id": "e6", - "source": "service", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-service/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e7", - "source": "mq", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 25, - "lineEnd": 25 - } - } - ], - "layout": { - "sections": [ - { - "id": "app", - "title": "应用入口", - "mode": "grid", - "columns": 3, - "tone": "blue", - "items": [ - { - "nodeId": "manager" - }, - { - "nodeId": "merchant" - }, - { - "nodeId": "payment" - } - ] - }, - { - "id": "domain", - "title": "持久化与公共模型", - "mode": "stack", - "tone": "green", - "items": [ - { - "nodeId": "service" - }, - { - "nodeId": "core" - } - ] - }, - { - "id": "components", - "title": "可复用组件", - "mode": "row", - "tone": "lavender", - "items": [ - { - "nodeId": "mq" - }, - { - "nodeId": "oss" - } - ] - } - ], - "direction": "down" - } -} diff --git a/examples/jeepay/source.json b/examples/jeepay/source.json index 08e068c..bbc4944 100644 --- a/examples/jeepay/source.json +++ b/examples/jeepay/source.json @@ -32,16 +32,6 @@ "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderService.java": "1efb0a56a8fc8df768c85ef4edc4cd2ef99ca09049beded87407175e2c21db67" }, "views": [ - { - "id": "jeepay-capabilities", - "type": "architecture", - "architectureView": "capabilities" - }, - { - "id": "jeepay-engineering", - "type": "architecture", - "architectureView": "engineering" - }, { "id": "jeepay-relations", "type": "architecture", diff --git a/package.json b/package.json index d0fd3c0..060f6eb 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "THIRD_PARTY_NOTICES.md", "README.md", "docs/clients*.md", - "docs/readme/", + "README.en.md", "skills/q-flow/scripts/compile-layout.mjs", "skills/q-flow/scripts/compile-sequence.mjs", "skills/q-flow/assets/layout-dist/", @@ -52,14 +52,12 @@ "skills/q-flow/assets/viewer/src/layout-spacing.js", "skills/q-flow/assets/viewer/src/session-graph.js", "skills/q-flow/assets/viewer/src/view-identity.js", - "skills/q-flow/assets/viewer/src/architecture-overview.js", "skills/q-flow/assets/viewer/src/layout-quality.js", "skills/q-flow/assets/viewer/src/layout-policy.js", "skills/q-flow/assets/viewer/src/layout-compaction.js", "skills/q-flow/assets/viewer/src/route-clearance.js", "skills/q-flow/assets/viewer/src/export-svg.js", "skills/q-flow/assets/viewer/src/node-svg.js", - "skills/q-flow/assets/viewer/src/architecture-overview-theme.js", "skills/q-flow/assets/viewer/src/orthogonal-routing.js", "skills/q-flow/assets/viewer/src/layout-refinement.js", "skills/q-flow/assets/viewer/src/layout-templates.js", diff --git a/scripts/refresh-jeepay-fixtures.mjs b/scripts/refresh-jeepay-fixtures.mjs index 237f788..783c282 100644 --- a/scripts/refresh-jeepay-fixtures.mjs +++ b/scripts/refresh-jeepay-fixtures.mjs @@ -9,8 +9,6 @@ const repo = process.argv[2]; if (!repo) throw new Error('Usage: node scripts/refresh-jeepay-fixtures.mjs '); const root = fs.realpathSync(repo), destination = path.resolve(import.meta.dirname, '../examples/jeepay'); const views = [ - ['capabilities', 'jeepay-platform-capability-architecture'], - ['engineering', 'jeepay-engineering-layer-architecture'], ['relations', 'jeepay-component-relation-architecture'], ['flowchart', 'jeepay-unified-order-flowchart'], ['sequence', 'jeepay-unified-order-sequence'], diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index ab1b190..5e81f61 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -25,9 +25,9 @@ For every ready request, apply [Granularity](references/graph-common.md#granular ## Author -Eleven templates: three architecture views (`meta.architectureView`: `capabilities`, `engineering`, `relations`) and eight other types below. +Nine templates, one per type: architecture is drawn as component relations, plus the eight other types below. -1. Choose `meta.diagramType` by intent: structure → `architecture`; decisions → `flowchart`; ordered calls → `sequence`; stored data → `er`; runtime placement → `deployment`; types → `class`; lifecycle → `state`; actors/capabilities → `usecase`; data movement → `dataflow`. Default to `architecture` when ambiguous. Architecture: platform capabilities / business integration → `capabilities`; engineering organization / component layers → `engineering`; component calls / dependencies → `relations`. Use one graph unless the user explicitly requests multiple views. +1. Choose `meta.diagramType` by intent: structure → `architecture`; decisions → `flowchart`; ordered calls → `sequence`; stored data → `er`; runtime placement → `deployment`; types → `class`; lifecycle → `state`; actors/capabilities → `usecase`; data movement → `dataflow`. Default to `architecture` when ambiguous. Use one graph unless the user explicitly requests multiple views. 2. Each view uses [graph-common.md](references/graph-common.md) and its matching page in [references/types/](references/types/) (`types/.md`); reuse loaded references across views. Do not read `graph-schema.md`, `visual-contract.md`, `examples/`, `scripts/`, `assets/` or tests to learn rules. Use the type skeleton and validator messages for fields. 3. Write the evidenced graph at the chosen granularity, without coordinates. Record level/coverage in `meta.scope` and check every user requirement before layout. Apply the common rules for names, evidence, ownership, order and business centre. Across views reuse the same non-empty `module` value for the same business module. Preserve ER keys/cardinalities, class members/multiplicities, sequence pairing/fragments/executions, state guards and architecture/deployment boundaries required at this level. Write once; correct only reported fields. 4. Templates measure text and preserve order; routes use feasible outlines and independent labels. Never remove facts. @@ -72,6 +72,6 @@ Between the two, work only what `--fix` left: update just the elements each `met ## Viewer maintenance -For Viewer changes or interaction audits, read [viewer-development.md](references/viewer-development.md), including its maintained visual/interaction contract. Changes to Viewer source, routing, schema behavior, or validation require the full eleven-view browser matrix described there. Graph-only delivery uses the single-page check in [acceptance.md](references/acceptance.md). +For Viewer changes or interaction audits, read [viewer-development.md](references/viewer-development.md), including its maintained visual/interaction contract. Changes to Viewer source, routing, schema behavior, or validation require the full nine-view browser matrix described there. Graph-only delivery uses the single-page check in [acceptance.md](references/acceptance.md). Publishing the plugin or creating a remote repository requires separate user authorization. diff --git a/skills/q-flow/agents/openai.yaml b/skills/q-flow/agents/openai.yaml index 7ea9145..85a861f 100644 --- a/skills/q-flow/agents/openai.yaml +++ b/skills/q-flow/agents/openai.yaml @@ -1,5 +1,5 @@ interface: display_name: "Q flow" - short_description: "Eleven kinds of interactive software diagrams from source, configuration and documents" + short_description: "Nine kinds of interactive software diagrams from source, configuration and documents" brand_color: "#203f35" default_prompt: "Use $q-flow to generate the right kind of interactive software diagram from the current evidence." diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index dba6104..7a14472 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -220,21 +220,21 @@ QGraphFlow - - ${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${S}${a===`sequence`?E+w:w+E}${C}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Um.join(`|`)}))?\\.svg$`);function vv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=Ff(n,Of.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${Gm(e)}.svg`:`diagram.svg`,svg:_v(e,`light`,r)}))}function yv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function bv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function xv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>_f(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=$_(await(await s.getFile()).text(),e),l;try{l=vv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(bv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Sv(e,t){t=xf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw a_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)},v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=wh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?gh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:bp(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Oh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(Zm(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Kh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw a_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:Gm(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Cv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));bv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function wv(e,t,n,r,i){e=structuredClone(e),i&&=If(i);let a=(t,n)=>_f(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=_v(e,t,i),s=`${yv(e.meta.title)}.${n}`;await Sv(o,e),n===`svg`?bv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Cv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Tv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Of[t],p=av(e,s,d,i),[m,h]=o,g=m&&!s,_=uv(d,()=>p.readGraph(p.currentGraph,0)),v=cv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=lv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await wv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>xv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:Gm(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:bf(e).some(t=>Jm(t,Gm(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Ev(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Dv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Wh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Kh(d,r):f?.labelBox;if(!p)return;let m=K_(p,W_(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:U_});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:U_})},[e,r,n,t,i,a,o])}var Ov={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function kv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Ov[e]})}function Av(e,t,n,r,i,a=()=>{}){let o=t??e,s=o?`${t?`edge`:`node`}:${o.id}`:null,c=(0,y.useRef)(0),[l,u]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,error:``}),d=(t=!1)=>u({editing:!1,pending:!1,label:o?.label??``,subtitle:e?.subtitle??``,error:``,returnFocus:t});(0,y.useEffect)(()=>{c.current++,a(),d()},[s]);let f=e=>u(t=>({...t,...e}));return{...l,set:f,cancel:()=>{c.current++,a(),d(!0)},begin:()=>f({editing:!0,returnFocus:!1,label:o?.label??``,subtitle:e?.subtitle??``,error:``}),save:async a=>{if(a.preventDefault(),l.pending)return;let o=l.label.trim();if(!o){f({error:_f(i,`Name is required`)});return}let s=++c.current;f({pending:!0});let u=await(t?r(t.id,o):n(e.id,o,l.subtitle.trim()));if(c.current===s){if(f({pending:!1}),u){f({error:u});return}f({editing:!1,error:``})}}}}function jv({editor:e,relation:t,locked:n,locale:r}){let i=e=>_f(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var Mv=292,Nv=232,Pv=14;function Fv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>_f(c,e,t),_=!!t,v=_?(Wh(d).get(t.id)?.label??Dh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(Nv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??Nv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Kh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=W_(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Pv,y:N.top},{side:`left`,x:N.left-Pv-Mv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Pv},{side:`above`,x:N.left,y:N.top-Pv-C}],F=e=>e.x>=P.left&&e.x+Mv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Kh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Wh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...oh(e)]),n=wh(d);for(let r of d.groups??[]){let i=gh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+Mv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-Mv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?Gf(e.source):_&&t.site?Gf(t.site):null,ae=_?Hf(t,r,o,s,n,vh(d).get(t.id)):Bf(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:Mv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(kv,{name:`close`})}),u.editing?(0,x.jsx)(jv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(Kf[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(Wf[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(kv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(jv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(kv,{name:`arrowRight`})]})]})]})]})}var Iv=[`system`,`light`,`dark`],Lv={system:`Follow system`,light:`Light`,dark:`Dark`};function Rv(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function zv({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>_f(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,layoutPending:ie,cancelLayout:ae,updateNodeText:oe,updateEdgeText:se,readGraph:ce,focusDiagram:le,nudgeLayout:ue,visibleNodes:de,visibleEdges:fe,reset:pe,exportDiagram:me,saveGraph:he,exportStatus:ge,layoutProblem:_e,layoutWarnings:ve,focusProblem:ye,boardRef:be,fullscreenButtonRef:xe,isFullscreen:Se,fullscreenPending:Ce,fullscreenSupported:we,toggleFullscreen:Te,toolbarOpen:Ee,drawerOpen:De,toolbarButtonRef:Oe,drawerButtonRef:ke,searchInputRef:Ae,inspectorRef:je,panelRef:Me,toggleToolbar:Ne,toggleDrawer:Pe,openDetails:Fe}=Tv(e,c,d,i,t,n,f),[Ie,Le]=Rv(Ee,v,Me),[Re,ze]=Rv(De,v,je),Be=(0,y.useRef)(null),Ve=Av(w,T,oe,se,e.meta.locale,ae),{open:He,toggle:Ue,close:We}=Ev(),Ge=e.meta.notes??[],Ke=rg(e),qe=cg(e),Je=lg(qe),Ye=Ge.length?{title:h(`Key points`),count:Ge.length,hide:h(`Hide key points`),show:h(`Show key points`)}:Ke.length?{title:h(`Source changes`),count:Ke.length,hide:h(`Hide source changes`),show:h(`Show source changes`)}:{title:h(`This update`),count:Je,hide:h(`Hide this update`),show:h(`Show this update`)},Xe=e=>{let t=L.nodes.find(t=>t.id===e),n=t?null:L.edges.find(t=>t.id===e);return t||n?(0,x.jsx)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>t?N(t):P(n,!0),children:ag(L,e)},e):(0,x.jsx)(`span`,{className:`update-group`,children:L.groups?.find(t=>t.id===e)?.label??e},e)},[Ze,Qe]=(0,y.useState)(!0),$e=Ye.count>0&&Ze&&!Re,et=De||$e&&!Se,tt=(0,y.useRef)(!1),nt=(0,y.useRef)(null);(0,y.useEffect)(()=>{tt.current&&nt.current?.focus({preventScroll:!0})},[Ze]);let rt=Dv(ne,z,L,g,v),[it,at]=(0,y.useState)(!1),[ot,st]=(0,y.useState)(``),[ct,lt]=(0,y.useState)(0);(0,y.useEffect)(()=>{(De||O===0)&<(O)},[De,O]);let ut=(0,y.useMemo)(()=>{let e=new Map(de.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:Sp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=eh(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,de]);(0,y.useEffect)(()=>{if(!ge)return;st(h(ge.message));let e=window.setTimeout(()=>st(``),4500);return()=>window.clearTimeout(e)},[ge]);let dt=O>0&&!De&&(g!==`sequence`||O!==ct)&&!z.some(e=>e.dragging),ft=dt?z.find(e=>e.id===E&&e.type===`diagram`):null,pt=dt?fe.find(e=>e.id===D):null,mt=pt?L.edges.find(e=>e.id===pt.id):null,ht=pt?{position:pt.data.route.labelPoint,size:{width:0,height:0}}:null,gt=mt?L.nodes.find(e=>e.id===mt.source):null,_t=mt?L.nodes.find(e=>e.id===mt.target):null,vt=T?L.nodes.find(e=>e.id===T.source):null,yt=T?L.nodes.find(e=>e.id===T.target):null,bt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(Kf[e.kind]??e.kind)})]},e.id),xt=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(kv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:Bf(w,_,i).stroke}}),h(Kf[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(Wf[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:Gf(e.source)})]},t))})]}),(e=>e.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Shared dependencies`)}),(0,x.jsx)(`ul`,{children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>P(e),children:[e.label??e.kind,` → `,L.nodes.find(t=>t.id===e.target)?.label]}),e.site&&(0,x.jsx)(`code`,{className:`source-path`,children:Gf(e.site)})]},e.id))})]}))(yf(L).filter(e=>e.source===w.id)),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(Wf[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:Gf(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:fe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Wh(L).get(T.id)?.label??Dh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[vt?.label,` → `,yt?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(Wf[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:Gf(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(kv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:Ve.editing?``:`card-actions`,children:(0,x.jsx)(jv,{editor:Ve,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return De&&(Be.current=xt),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:Oe,onClick:()=>{Ne(),Ee||rt(E,D,!0,et)},"aria-controls":`graph-tools`,"aria-expanded":Ee,"aria-pressed":Ee,"aria-label":h(Ee?`Hide graph navigation`:`Show graph navigation`),title:h(Ee?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(kv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(pf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>at(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||at(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(kv,{name:`search`}),(0,x.jsx)(`input`,{ref:Ae,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),it&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(Kf[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>Ue(`views`),"aria-haspopup":`menu`,"aria-expanded":He===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(kv,{name:`views`}),(0,x.jsx)(`span`,{children:h(pf(e))}),(0,x.jsx)(kv,{name:`chevron`})]}),He===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{Gm(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(kv,{name:`check`}):null}),`${h(pf(t))}${r.filter(e=>ff(e)===ff(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(kv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>Ue(`more`),"aria-haspopup":`menu`,"aria-expanded":He===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(kv,{name:`more`})}),He===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ie,onClick:()=>{me(`svg`),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ie,onClick:()=>{me(`png`),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ie,onClick:()=>{he(),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{pe(),We()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{ue(),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":Iv.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${Iv.indexOf(l)*100}%)`}}),Iv.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(Lv[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||rt(E,D,Ee,!0)},"aria-controls":`node-inspector`,"aria-expanded":De,"aria-pressed":De,title:h(De?`Hide details`:`Show details`),"aria-label":h(De?`Hide details`:`Show details`),children:(0,x.jsx)(kv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${Ee?`nav-open`:``} ${De?`drawer-open`:``}`,children:[Ie&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Me,tabIndex:-1,className:`sidebar nav${Le}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Ne,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(kv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(bt)})]}),(0,x.jsxs)(`figure`,{ref:be,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:zp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ie,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":Ee,"data-drawer-open":et,onKeyDownCapture:F,"aria-label":h(`Interactive {type}`,{type:h(pf(e))}),children:[(0,x.jsxs)(Sd,{nodeExtent:[[0,0],[1/0,1/0]],nodes:de,edges:fe,nodeTypes:gg,edgeTypes:_g,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),We()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>ce(L,0)),nodesDraggable:!I&&!ie,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:le,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(kv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:xe,onClick:Te,"aria-pressed":Se,"aria-busy":Ce,"aria-disabled":Ce||!we&&!Se,"aria-label":h(Se?`Exit fullscreen`:`Enter fullscreen`),title:h(!we&&!Se?`Fullscreen is not available in this browser or page`:Se?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(kv,{name:Se?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ut,nodeStrokeColor:e=>e.type===`boundary`?`none`:Bf(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:Bf(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>Ue(`legend`),"aria-expanded":He===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(kv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),He===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:Sg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:xg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Ye.count>0&&!Re&&($e?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":Ye.title,children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[Ye.title,` · `,Ye.count]}),(0,x.jsx)(`button`,{className:`side-close`,ref:nt,onClick:()=>{tt.current=!0,Qe(!1)},"aria-label":Ye.hide,title:Ye.hide,children:(0,x.jsx)(kv,{name:`close`})})]}),Ge.length>0&&(0,x.jsx)(`ul`,{children:Ge.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))}),Ke.length>0&&(0,x.jsxs)(x.Fragment,{children:[Ge.length>0&&(0,x.jsxs)(`p`,{className:`panel-title source-changes-title`,children:[h(`Source changes`),` · `,Ke.length]}),(0,x.jsx)(`ul`,{className:`source-changes`,children:Ke.map((e,t)=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`code`,{children:[String(e?.file??``).split(`/`).pop(),`:`,e?.line]}),` `,e?.change,(e?.elements??[]).map(Xe),(e?.removed?.length>0||e?.added?.length>0)&&(0,x.jsx)(`pre`,{children:[...(e.removed??[]).slice(0,3).map(e=>`- ${e}`),...(e.added??[]).slice(0,3).map(e=>`+ ${e}`)].join(` +`)})]},t))})]}),Je>0&&(0,x.jsxs)(x.Fragment,{children:[(Ge.length>0||Ke.length>0)&&(0,x.jsxs)(`p`,{className:`panel-title source-changes-title`,children:[h(`This update`),` · `,Je]}),(0,x.jsxs)(`ul`,{className:`graph-update`,children:[qe.added.length>0&&(0,x.jsxs)(`li`,{className:`update-added`,children:[h(`Added`),` · `,qe.added.length,qe.added.map(Xe)]}),qe.changed.length>0&&(0,x.jsxs)(`li`,{className:`update-changed`,children:[h(`Changed`),` · `,qe.changed.length,qe.changed.map(Xe)]}),qe.removed.length>0&&(0,x.jsxs)(`li`,{className:`update-removed`,children:[h(`Removed`),` · `,qe.removed.length,qe.removed.map(e=>(0,x.jsx)(`s`,{children:e.label},e.id))]}),qe.meta&&(0,x.jsx)(`li`,{children:h(`View notes updated`)})]})]})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:nt,"aria-expanded":`false`,onClick:()=>{tt.current=!0,Qe(!0),Se||rt(E,D,Ee,!0)},"aria-label":Ye.show,title:Ye.show,children:[(0,x.jsx)(kv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[Ye.title,` · `,Ye.count]})]})),ft&&(0,x.jsx)(Fv,{node:{...ft.data,position:ft.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:Ve,graph:L,isFullscreen:Se,onDetails:async()=>{Se&&!await Te()||(Fe(),rt(E,D,Ee,!0))},onClose:()=>ee()}),mt&&(0,x.jsx)(Fv,{node:ht,edge:{...mt,diagramType:g},source:gt,target:_t,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:Ve,graph:L,isFullscreen:Se,onDetails:async()=>{Se&&!await Te()||(Fe(),rt(E,D,Ee,!0))},onClose:()=>ee()}),!_e&&ve.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ve.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>ye(ve.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),_e&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:_e.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>ye(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:_e.message})]}),(0,x.jsx)(`div`,{className:`toast ${ot?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:ot})]})]}),Re&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:je,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${ze}`,"aria-label":h(`Details`),children:Be.current})]})]})}function Bv(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var Vv=JSON.parse(document.querySelector(`#graph-data`).textContent);sg(JSON.parse(document.querySelector(`#graph-compare`)?.textContent??`null`));var Hv=[...Array.isArray(Vv.diagrams)?Vv.diagrams:[Vv]].sort(mf),Uv=window.matchMedia(`(prefers-color-scheme: dark)`);function Wv(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(Uv.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return Uv.addEventListener(`change`,e),()=>Uv.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function Gv(){let[e,t]=(0,y.useState)(uf(Hv[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=Wv(),s=Bv(),c=Hv.find(t=>uf(t)===e)??Hv[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>ev(Vv,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=Ff(Hv,Of[o]);return f?e:Lf(e,Of[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(Uf(Of[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)(zv,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:Hv,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(Gv,{})); + diff --git a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx index 75b3812..0797c30 100644 --- a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx +++ b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx @@ -1,5 +1,4 @@ import { presentationGraph, visibleEdges } from './presentation-graph.js'; -import { overviewSections, sectionSvg } from './architecture-overview.js'; import React, { useId } from 'react'; import { BaseEdge, EdgeLabelRenderer, Handle, MarkerType, Position, useStore } from '@xyflow/react'; import SelectionOutline from './SelectionOutline.jsx'; @@ -89,10 +88,7 @@ function RoutedEdge({ id, markerEnd, style, data }) { ; } -function OverviewSection({ data }) { - return
; -} -export const nodeTypes = { diagram: DiagramNode, boundary: BoundaryNode, overview: OverviewSection }; +export const nodeTypes = { diagram: DiagramNode, boundary: BoundaryNode }; export const edgeTypes = { routed: RoutedEdge }; // generate-viewer --compare: 'added' or 'changed' for an element of this view, else undefined. @@ -114,7 +110,7 @@ export function initialNodes(graph, diagramType) { zIndex: -(graph.groups?.length ?? 0) + fragmentDepth(group, graph.groups ?? []) })); const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])), drifted = driftedElements(graph), diff = diffOf(graph); - return [...overviewSections(graph).map((section, index) => ({ id: section.id, type: 'overview', position: section.position, data: { ...section }, style: { width: section.size.width, height: section.size.height, pointerEvents: 'none' }, draggable: false, selectable: false, zIndex: -100 + index })), ...boundaries, ...graph.nodes.map(node => ({ + return [...boundaries, ...graph.nodes.map(node => ({ id: node.id, type: 'diagram', className: diagramType === 'sequence' ? 'sequence-column' : undefined, diff --git a/skills/q-flow/assets/viewer/src/TextEditor.jsx b/skills/q-flow/assets/viewer/src/TextEditor.jsx index 74879d1..1d2c704 100644 --- a/skills/q-flow/assets/viewer/src/TextEditor.jsx +++ b/skills/q-flow/assets/viewer/src/TextEditor.jsx @@ -2,22 +2,20 @@ import React, { useEffect, useRef, useState } from 'react'; import { evidenceLabels } from './visual-style.js'; import { translate } from './i18n.js'; -export function useTextEditor(node, edge, onSaveNode, onSaveEdge, locale, overviewView = false, onCancel = () => {}) { +export function useTextEditor(node, edge, onSaveNode, onSaveEdge, locale, onCancel = () => {}) { const object = edge ?? node, key = object ? `${edge ? 'edge' : 'node'}:${object.id}` : null; - const overview = Boolean(node && (overviewView || node.section || node.overviewText !== undefined)); const saveToken = useRef(0); - const [draft, setDraft] = useState({ editing: false, pending: false, label: '', subtitle: '', overviewText: '', badges: [], error: '' }); - const reset = (returnFocus = false) => setDraft({ editing: false, pending: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', overviewText: (node?.overviewText ?? []).join('\n'), badges: structuredClone(node?.badges ?? []), error: '', returnFocus }); + const [draft, setDraft] = useState({ editing: false, pending: false, label: '', subtitle: '', error: '' }); + const reset = (returnFocus = false) => setDraft({ editing: false, pending: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', error: '', returnFocus }); useEffect(() => { saveToken.current++; onCancel(); reset(); }, [key]); const set = patch => setDraft(current => ({ ...current, ...patch })); - return { ...draft, section: Boolean(node?.section), overview, set, cancel: () => { saveToken.current++; onCancel(); reset(true); }, begin: () => set({ editing: true, returnFocus: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', overviewText: (node?.overviewText ?? []).join('\n'), badges: structuredClone(node?.badges ?? []), error: '' }), save: async event => { + return { ...draft, set, cancel: () => { saveToken.current++; onCancel(); reset(true); }, begin: () => set({ editing: true, returnFocus: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', error: '' }), save: async event => { event.preventDefault(); if (draft.pending) return; const label = draft.label.trim(); if (!label) { set({ error: translate(locale, 'Name is required') }); return; } - if (draft.badges.some(badge => !badge.label.trim())) { set({ error: translate(locale, 'Name is required') }); return; } const token = ++saveToken.current; set({ pending: true }); - const error = await (edge ? onSaveEdge(edge.id, label) : onSaveNode(node.id, label, draft.subtitle.trim(), overview ? { overviewText: draft.overviewText.split(/\r?\n/).map(line => line.trim()).filter(Boolean), ...(node.section ? {} : { badges: draft.badges }) } : {})); + const error = await (edge ? onSaveEdge(edge.id, label) : onSaveNode(node.id, label, draft.subtitle.trim())); if (saveToken.current !== token) return; set({ pending: false }); if (error) { set({ error }); return; } @@ -36,9 +34,7 @@ export default function TextEditor({ editor, relation, locked, locale }) { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); editor.cancel(); } }}> - {!relation && !editor.section &&