Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

Add data-flow diagram renderer

tt-a1idcdc8d8fc955
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dbf70b73..affb263d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,9 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo
- **Sequence JSON Schema.** Added `archify/schemas/sequence.schema.json` to document and validate the sequence IR shape.
- **Sequence example.** Added a rendered cache-miss request sequence example at `examples/sequence-cache-miss-request.html`.
- **Sequence README preview.** Added a rendered sequence screenshot to the README preview flow.
+- **Data-flow diagram mode.** Added a renderer-backed data-flow diagram type for analytics pipelines, ETL/ELT, PII isolation, governance boundaries, data lineage, warehouse sync, and downstream consumers.
+- **Data-flow JSON Schema.** Added `archify/schemas/dataflow.schema.json` to document and validate the data-flow IR shape.
+- **Data-flow example.** Added a rendered product analytics data-flow example at `examples/dataflow-product-analytics.html`, plus a README preview screenshot.
### Changed
- **Template responsive polish.** The shared HTML template now handles narrow viewports better: the toolbar no longer overlaps the title, diagrams can scale down to the available width, and cards stack cleanly on mobile.
diff --git a/README.md b/README.md
index 32525934..65fb30d7 100644
--- a/README.md
+++ b/README.md
@@ -2,12 +2,12 @@
# Archify
-**聊两句就画出好看的架构图、技术流程图和调用时序图。深色 / 浅色一键切。导出 4× 清晰 PNG / JPEG / WebP / SVG,或直接复制到剪贴板。**
+**聊两句就画出好看的架构图、技术流程图、调用时序图和数据流图。深色 / 浅色一键切。导出 4× 清晰 PNG / JPEG / WebP / SVG,或直接复制到剪贴板。**
Archify 是一个 [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude):你用大白话描述自己的系统或流程,它就把你的描述变成一张做工精细的技术图 —— 一个单文件 HTML,在浏览器里打开就能切主题、复制到剪贴板、导出成各种图片格式。
- **不需要会画图** —— 把组件和连接关系说给 Claude 就行
-- **支持 workflow / sequence** —— 技术流程、审批链、工具调用、CI/CD、请求调用链都可以画
+- **支持 workflow / sequence / data flow** —— 技术流程、审批链、工具调用、CI/CD、请求调用链、数据管线、PII 边界都可以画
- **内置主题切换** —— 深色 / 浅色一键切,浏览器记住偏好
- **一键复制到剪贴板** —— 直接贴到 Slack、飞书、微信、Notion、GitHub issue
- **导出图片超清晰** —— PNG / JPEG / WebP 全部由浏览器在 4× 源分辨率下**原生光栅化**(不是位图放大,没有糊),或导出 SVG 做真矢量
@@ -38,13 +38,14 @@ Export 菜单 —— 复制到剪贴板 + 四种格式下载:
## 图表类型
-Archify 现在有三种主要输出:
+Archify 现在有四种主要输出:
| 类型 | 适合画什么 | 怎么用 |
|---|---|---|
| **Architecture** | 系统组件、云资源、数据库、缓存、服务边界、安全组 | 直接描述系统结构 |
| **Workflow** | 请求生命周期、审批流程、工具调用、CI/CD、运维 runbook、事故响应 | 说明参与方、步骤顺序、关键分支 |
| **Sequence** | API 调用链、请求生命周期、缓存回源、鉴权、异步 trace、服务交互 | 说明谁调用谁、先后顺序、返回路径 |
+| **Data Flow** | 数据管线、ETL/ELT、埋点、PII 隔离、仓库同步、数据血缘、下游消费 | 说明数据来源、处理阶段、存储位置、敏感边界和消费方 |
Workflow 不是通用流程图的替代品,它更偏“技术沟通图”:有泳道、有语义颜色、有主路径和异步/审批/观测路径。比如:
@@ -66,6 +67,18 @@ Sequence 用来解释更细的交互顺序,比如:
![Sequence 示例](examples/images/archify-sequence.png)
+Data Flow 适合解释“数据资产怎么走”,比如:
+
+```
+用 archify 画一个 data flow:
+Web 和 Mobile 上报埋点,Edge API 收集事件,Consent Gate 过滤 PII,Kafka 承接事件流,
+Warehouse 存分析表,Feature Store 做每日特征,Dashboard 和 ML Model 消费下游数据。
+```
+
+示例:[`examples/dataflow-product-analytics.html`](examples/dataflow-product-analytics.html)。
+
+![Data Flow 示例](examples/images/archify-dataflow.png)
+
## 版本演进
Archify 基于 [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) v1.0(只有深色主题的 HTML 输出)fork 重写。**2.0** 把模板重构成 CSS 变量驱动的可主题化系统,加入客户端导出流水线。**2.1** 加入剪贴板复制 + 键盘导航。**2.2** 加入打印样式 + 本地字体回退。**2.3** 修了一个存在已久的位图升采样 bug,所有光栅导出改为 4× 原生渲染(同时移除了 v2.1 引入的 1×/2×/4× 选择器 —— 那个选择器只是在诱导用户选出更糊的图)。**2.4** SVG 导出升级成双主题自持版 —— 同一个 `.svg` 文件贴在 GitHub README 里,读者切深浅色图会自己跟着切。
@@ -213,6 +226,18 @@ unzip archify.zip -d ./.claude/skills/
- K8s 做编排
```
+**数据流 / 埋点分析:**
+```
+用 archify 画一个 data flow:
+- Web App 和 Mobile SDK 产生 clickstream events
+- Edge API 收集事件
+- Consent Gate 过滤身份信息和 PII
+- Kafka/Event Stream 承接 accepted events
+- Warehouse 存 normalized facts
+- Feature Store 每日生成 feature vectors
+- Dashboards 和 ML Model 消费下游数据
+```
+
## 语义配色
| 类型 | 颜色 | 用途 |
diff --git a/README_EN.md b/README_EN.md
index 0eef3a6b..a7aa3be6 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -2,12 +2,12 @@
# Archify
-**Generate beautiful architecture, technical workflow, and sequence diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**
+**Generate beautiful architecture, technical workflow, sequence, and data-flow diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**
Archify is a [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude) that turns a plain-English description of your system or process into a polished, self-contained technical diagram — a single HTML file you can open, toggle themes on, copy to the clipboard, and export at maximum resolution.
- **No design skills needed** — describe your architecture in English, get a diagram
-- **Workflow and sequence diagrams too** — technical flows, approvals, tool calls, CI/CD, runbooks, and request call chains can be drawn
+- **Workflow, sequence, and data-flow diagrams too** — technical flows, approvals, tool calls, CI/CD, runbooks, request call chains, data pipelines, and PII boundaries can be drawn
- **Built-in theme toggle** — one click between dark and light, persists across sessions
- **Copy PNG to clipboard** — one click, paste straight into Slack / Notion / GitHub
- **Ultra-crisp image export** — PNG / JPEG / WebP rendered natively at 4× source resolution (no upsampling blur), or SVG for true vector
@@ -37,13 +37,14 @@ Live example: [`examples/web-app.html`](examples/web-app.html) — open in a bro
## Diagram types
-Archify now has three primary outputs:
+Archify now has four primary outputs:
| Type | Good for | How to ask |
|---|---|---|
| **Architecture** | System components, cloud resources, databases, caches, services, boundaries, security groups | Describe the system structure |
| **Workflow** | Request lifecycles, approval flows, tool calls, CI/CD, runbooks, incident response | Describe participants, step order, and key branches |
| **Sequence** | API call chains, request lifecycles, cache fallback, auth checks, async trace, service interactions | Describe who calls whom, in what order, and what returns |
+| **Data Flow** | Data pipelines, ETL/ELT, analytics events, PII isolation, warehouse sync, lineage, downstream consumers | Describe sources, processing stages, storage, sensitivity boundaries, and consumers |
Workflow is not trying to replace every general-purpose flowchart. It is a technical communication diagram: swimlanes, semantic colors, a clear happy path, and secondary async / approval / trace paths.
@@ -65,6 +66,18 @@ Open the example here: [`examples/sequence-cache-miss-request.html`](examples/se
![Sequence example](examples/images/archify-sequence.png)
+Data Flow diagrams explain how data assets move and change:
+
+```text
+Use archify to draw a data flow:
+Web and Mobile emit analytics events, Edge API collects them, Consent Gate filters PII, Kafka carries accepted events,
+Warehouse stores analytics tables, Feature Store derives daily features, Dashboards and an ML Model consume downstream data.
+```
+
+Open the example here: [`examples/dataflow-product-analytics.html`](examples/dataflow-product-analytics.html).
+
+![Data Flow example](examples/images/archify-dataflow.png)
+
## What's new
Archify is based on [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) v1.0 (dark-only, HTML output). **2.0** rewrote the template around a themeable CSS-variable system and added a client-side export pipeline. **2.1** added copy-to-clipboard + keyboard nav. **2.2** added a print stylesheet + local-font fallback. **2.3** fixed a long-standing upsampling bug and made every raster export genuinely sharp at 4× source resolution (the 1× / 2× / 4× selector introduced in 2.1 was removed at the same time — it only encouraged picking a soft-looking scale). **2.4** upgraded the SVG export to a dual-theme self-contained file — drop the same `.svg` into a GitHub README and it follows the reader's dark/light preference automatically.
@@ -211,6 +224,18 @@ Create an architecture diagram for a microservices system with:
- Kubernetes orchestration
```
+**Data flow / product analytics:**
+```
+Use archify to draw a data flow:
+- Web App and Mobile SDK produce clickstream events
+- Edge API collects events
+- Consent Gate filters identity and PII
+- Kafka/Event Stream carries accepted events
+- Warehouse stores normalized facts
+- Feature Store derives daily feature vectors
+- Dashboards and ML Model consume downstream data
+```
+
## Color palette
| Component Type | Color | Use for |
diff --git a/ROADMAP.md b/ROADMAP.md
index 20aada75..223c0116 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -111,6 +111,12 @@ Sequence diagrams became the second typed renderer pilot. They use `diagram_type
Like workflow, sequence is not a generic auto-layout target. The renderer enforces readable spacing and semantic styling, while Claude still decides which participants matter, how the story is grouped, which messages deserve labels, and which return/async paths should stay quiet.
+### Data-flow renderer pilot (2026-04-24)
+
+Data-flow diagrams became the third typed renderer pilot. They use `diagram_type: "dataflow"` JSON with lifecycle stages, semantic nodes, labeled data flows, optional classifications, and summary cards. The goal is to explain analytics pipelines, ETL/ELT, PII isolation, governance boundaries, warehouse sync, derived features, and downstream consumers.
+
+Like workflow and sequence, data-flow is not a generic graph layout engine. The renderer provides stable stage/row placement and validation checks, while Claude still decides which data assets matter, where sensitive boundaries should appear, which paths are primary, and which batch or restricted joins should stay visually secondary.
+
---
## Not planned
diff --git a/archify.zip b/archify.zip
index ef6dddf5..26ae087d 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/SKILL.md b/archify/SKILL.md
index ee6e8246..b4ac235a 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -1,6 +1,6 @@
---
name: archify
-description: Create professional architecture, workflow, and sequence diagrams as standalone HTML files with SVG graphics, a built-in dark/light theme toggle, and one-click export to PNG / JPEG / WebP / SVG. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, technical workflows, approval flows, runbooks, CI/CD flows, process diagrams, API call sequences, request lifecycles, or interaction diagrams.
+description: Create professional architecture, workflow, sequence, and data-flow diagrams as standalone HTML files with SVG graphics, a built-in dark/light theme toggle, and one-click export to PNG / JPEG / WebP / SVG. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, technical workflows, approval flows, runbooks, CI/CD flows, process diagrams, API call sequences, request lifecycles, interaction diagrams, data pipelines, analytics flows, ETL/ELT maps, PII boundaries, or governance/data lineage diagrams.
license: MIT
metadata:
version: "2.4"
@@ -10,7 +10,7 @@ metadata:
# Archify Skill
-Create professional technical architecture diagrams as self-contained HTML files with inline SVG, a theme toggle, and a built-in image/SVG export menu. No external runtime dependencies beyond Google Fonts.
+Create professional technical diagrams as self-contained HTML files with inline SVG, a theme toggle, and a built-in image/SVG export menu. No external runtime dependencies beyond Google Fonts.
Every diagram this skill produces ships with:
@@ -20,13 +20,14 @@ Every diagram this skill produces ships with:
## Diagram Types
-Archify supports three technical diagram modes:
+Archify supports four technical diagram modes:
| Type | Use for | Output path |
|------|---------|-------------|
| `architecture` | System components, cloud resources, services, storage, security boundaries, and infrastructure relationships | Hand-place SVG components inside `assets/template.html` |
| `workflow` | Technical flows, request lifecycles, approval gates, tool calls, runbooks, CI/CD paths, incident response, and process ownership | Prefer `renderers/workflow/render-workflow.mjs` with a workflow JSON file |
| `sequence` | API calls, request lifecycles, service interactions, cache fallback paths, async trace/logging, and return paths over time | Prefer `renderers/sequence/render-sequence.mjs` with a sequence JSON file |
+| `dataflow` | Data pipelines, ETL/ELT, analytics flows, PII isolation, governance boundaries, lineage, warehouse sync, and downstream consumers | Prefer `renderers/dataflow/render-dataflow.mjs` with a data-flow JSON file |
When the user says "architecture", "system diagram", "cloud diagram", or asks to understand a codebase structure, use the `architecture` mode unless the requested output is clearly process-oriented.
@@ -34,6 +35,8 @@ When the user says "workflow", "flow", "process", "runbook", "sequence of steps"
When the user says "sequence", "interaction", "call sequence", "request lifecycle", "API call chain", "who calls whom", or asks how multiple participants interact over time, use the `sequence` mode.
+When the user says "data flow", "pipeline", "ETL", "ELT", "lineage", "analytics", "warehouse", "PII", "consent", "governance", or asks where data comes from, how it is transformed, and who consumes it, use the `dataflow` mode.
+
### Workflow Mode
Workflow diagrams use a compact JSON IR:
@@ -115,6 +118,49 @@ The renderer:
Use sequence diagrams when the important thing is order over time. Keep labels short; prefer "GET /path", "verify JWT", "cache miss", "emit trace", and "200 JSON" over prose sentences.
+### Data-flow Mode
+
+Data-flow diagrams use a compact JSON IR:
+
+```json
+{
+ "schema_version": 1,
+ "diagram_type": "dataflow",
+ "meta": {
+ "title": "Product Analytics Data Flow",
+ "subtitle": "Events, consent, PII isolation, warehouse sync, and consumers",
+ "output": "product-analytics.html",
+ "viewBox": [900, 720]
+ },
+ "stages": [
+ { "label": "Sources" },
+ { "label": "Ingest" },
+ { "label": "Process" },
+ { "label": "Store" },
+ { "label": "Consume" }
+ ],
+ "nodes": [],
+ "flows": [],
+ "cards": []
+}
+```
+
+If you have filesystem/tool access, create a data-flow JSON file and render it with:
+
+```bash
+node archify/renderers/dataflow/render-dataflow.mjs dataflow.json dataflow.html
+```
+
+The renderer:
+
+- Places nodes by lifecycle stage + row
+- Uses vertical stage bands for source, ingest, process, store, and consume boundaries
+- Uses flow labels to name data assets, plus optional `classification` for PII/governance context
+- Uses semantic variants: `emphasis` for the primary data path, `security` for PII/policy/consent/restricted joins, and `dashed` for async or batch derivations
+- Fails fast when nodes overlap, stages overflow, flow endpoints are unknown, labels are missing, or arrows become unreadably short
+
+Use data-flow diagrams when the important thing is data lineage and governance. Keep labels asset-like: "clickstream", "identity map", "normalized facts", "feature vectors", "restricted join". Put sensitivity in `classification`: "PII touch", "encrypted PII", "approved only", "non-PII", "read-only".
+
## The Cardinal Rule: Use CSS Classes, Not Inline Colors
The theme toggle works by switching CSS custom properties. If you hardcode `fill="rgba(...)"` or `stroke="#22d3ee"` on SVG elements, those values will NOT update when the theme changes. Always prefer the class-based system.
diff --git a/archify/examples/product-analytics.dataflow.json b/archify/examples/product-analytics.dataflow.json
new file mode 100644
index 00000000..497902dd
--- /dev/null
+++ b/archify/examples/product-analytics.dataflow.json
@@ -0,0 +1,70 @@
+{
+ "schema_version": 1,
+ "diagram_type": "dataflow",
+ "meta": {
+ "title": "Product Analytics Data Flow",
+ "subtitle": "Events, consent, PII isolation, warehouse sync, and downstream analytics",
+ "output": "examples/dataflow-product-analytics.html",
+ "viewBox": [900, 720]
+ },
+ "stages": [
+ { "label": "Sources" },
+ { "label": "Ingest" },
+ { "label": "Process" },
+ { "label": "Store" },
+ { "label": "Consume" }
+ ],
+ "nodes": [
+ { "id": "web", "type": "frontend", "label": "Web App", "sublabel": "browser SDK", "stage": 0, "row": 0, "tag": "events" },
+ { "id": "mobile", "type": "frontend", "label": "Mobile", "sublabel": "iOS / Android", "stage": 0, "row": 2, "tag": "events" },
+ { "id": "edge", "type": "cloud", "label": "Edge API", "sublabel": "collector", "stage": 1, "row": 1, "tag": "TLS" },
+ { "id": "consent", "type": "security", "label": "Consent Gate", "sublabel": "policy filter", "stage": 2, "row": 0, "tag": "PII guard" },
+ { "id": "stream", "type": "messagebus", "label": "Event Stream", "sublabel": "Kafka topic", "stage": 2, "row": 2, "tag": "ordered" },
+ { "id": "pii", "type": "security", "label": "PII Vault", "sublabel": "encrypted", "stage": 3, "row": 0, "tag": "restricted" },
+ { "id": "warehouse", "type": "database", "label": "Warehouse", "sublabel": "analytics tables", "stage": 3, "row": 2, "tag": "curated" },
+ { "id": "features", "type": "database", "label": "Feature Store", "sublabel": "daily batch", "stage": 3, "row": 4, "tag": "derived" },
+ { "id": "dashboard", "type": "backend", "label": "Dashboards", "sublabel": "product metrics", "stage": 4, "row": 1, "tag": "SQL" },
+ { "id": "model", "type": "backend", "label": "ML Model", "sublabel": "ranking job", "stage": 4, "row": 3, "tag": "features" }
+ ],
+ "flows": [
+ { "from": "web", "to": "edge", "label": "clickstream", "classification": "user events", "variant": "emphasis", "route": "auto", "labelAt": [176, 182] },
+ { "from": "mobile", "to": "edge", "label": "app events", "classification": "device events", "variant": "default", "route": "auto", "labelAt": [176, 328] },
+ { "from": "edge", "to": "consent", "label": "identity + consent", "classification": "PII touch", "variant": "security", "route": "top-channel", "channelY": 124, "labelAt": [356, 112] },
+ { "from": "edge", "to": "stream", "label": "accepted events", "classification": "append-only", "variant": "emphasis", "route": "auto" },
+ { "from": "consent", "to": "pii", "label": "identity map", "classification": "encrypted PII", "variant": "security", "route": "straight", "labelAt": [536, 178] },
+ { "from": "stream", "to": "warehouse", "label": "normalized facts", "classification": "non-PII", "variant": "emphasis", "route": "straight" },
+ { "from": "warehouse", "to": "features", "label": "daily aggregates", "classification": "batch", "variant": "dashed", "route": "vertical-channel", "channelX": 634, "labelSegment": 1, "labelDx": 10 },
+ { "from": "warehouse", "to": "dashboard", "label": "metrics SQL", "classification": "read-only", "variant": "default", "route": "auto", "labelAt": [700, 310] },
+ { "from": "features", "to": "model", "label": "feature vectors", "classification": "derived", "variant": "dashed", "route": "auto", "labelAt": [704, 512] },
+ { "from": "pii", "to": "dashboard", "label": "restricted join", "classification": "approved only", "variant": "security", "route": "bottom-channel", "channelY": 224, "labelAt": [684, 246] }
+ ],
+ "cards": [
+ {
+ "dot": "emerald",
+ "title": "Primary Data Path",
+ "items": [
+ "Events move left to right through source, ingest, process, store, and consume stages",
+ "The hot path stays visually clear even with secondary batch flows",
+ "Labels name data assets instead of generic API verbs"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "Sensitive Boundary",
+ "items": [
+ "Consent and PII paths are styled as security flows",
+ "PII lands in a restricted vault, separate from the analytics warehouse",
+ "Restricted joins are visible without implying default access"
+ ]
+ },
+ {
+ "dot": "orange",
+ "title": "Derived Consumers",
+ "items": [
+ "Dashboards read curated facts from the warehouse",
+ "Feature vectors are derived by batch from analytics tables",
+ "Consumption paths stay distinct from collection and consent handling"
+ ]
+ }
+ ]
+}
diff --git a/archify/renderers/dataflow/README.md b/archify/renderers/dataflow/README.md
new file mode 100644
index 00000000..6735fc88
--- /dev/null
+++ b/archify/renderers/dataflow/README.md
@@ -0,0 +1,57 @@
+# Data Flow Renderer
+
+Render `diagram_type: "dataflow"` JSON files into the standard Archify HTML
+template.
+
+```bash
+node archify/renderers/dataflow/render-dataflow.mjs input.dataflow.json output.html
+```
+
+If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
+or falls back to `dataflow.html` in the current working directory.
+
+## Input
+
+Data-flow JSON files must set:
+
+```json
+{
+ "schema_version": 1,
+ "diagram_type": "dataflow",
+ "meta": {
+ "title": "Product Analytics Data Flow",
+ "subtitle": "Events, consent, PII isolation, warehouse sync, and consumers",
+ "viewBox": [900, 720]
+ },
+ "stages": [],
+ "nodes": [],
+ "flows": [],
+ "cards": []
+}
+```
+
+The schema lives at:
+
+```text
+archify/schemas/dataflow.schema.json
+```
+
+## Design Rules
+
+- Use stages for data lifecycle boundaries: source, ingest, process, store,
+ consume.
+- Place nodes by stage index and row index; do not hand-place raw SVG for the
+ common case.
+- Use flow labels to name the data asset, not the transport primitive:
+ `clickstream`, `identity map`, `normalized facts`, `feature vectors`.
+- Use `classification` for short sensitivity or governance context:
+ `PII touch`, `non-PII`, `approved only`, `batch`, `read-only`.
+- Use `security` for PII, policy, consent, access-control, or restricted joins.
+- Use `emphasis` for the primary data path and `dashed` for async or batch
+ derivations.
+- Keep labels short enough to fit in narrow previews.
+
+The renderer fails when it can detect layout problems, including missing stages,
+duplicate node IDs, nodes outside the readable diagram area, node overlap,
+unknown flow endpoints, missing flow labels, unreadably short flows, or stages
+that exceed the viewBox.
diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjs
new file mode 100644
index 00000000..a3d8405c
--- /dev/null
+++ b/archify/renderers/dataflow/render-dataflow.mjs
@@ -0,0 +1,368 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const skillRoot = path.resolve(__dirname, '../..');
+const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/product-analytics.dataflow.json'));
+const dataflow = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
+
+const templatePath = path.join(skillRoot, 'assets/template.html');
+const template = fs.readFileSync(templatePath, 'utf8');
+const outPath = path.resolve(process.cwd(), process.argv[3] || dataflow.meta.output || 'dataflow.html');
+
+const viewBox = dataflow.meta.viewBox || [940, 720];
+const layout = {
+ stageY: 46,
+ stageH: 36,
+ stageBottomPad: 74,
+ leftX: 92,
+ colGap: 174,
+ stageW: 142,
+ nodeW: 112,
+ nodeH: 58,
+ rowYs: [136, 242, 348, 454, 560],
+ labelH: 16
+};
+
+const typeClass = {
+ frontend: 'c-frontend',
+ backend: 'c-backend',
+ database: 'c-database',
+ cloud: 'c-cloud',
+ security: 'c-security',
+ messagebus: 'c-messagebus',
+ external: 'c-external'
+};
+
+const textClass = {
+ frontend: 't-frontend',
+ backend: 't-backend',
+ database: 't-database',
+ cloud: 't-cloud',
+ security: 't-security',
+ messagebus: 't-messagebus',
+ external: 't-external'
+};
+
+const arrowClass = {
+ default: ['a-default', 'arrowhead'],
+ emphasis: ['a-emphasis', 'arrowhead-emphasis'],
+ security: ['a-security', 'arrowhead-security'],
+ dashed: ['a-dashed', 'arrowhead-dashed']
+};
+
+function esc(value) {
+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;'
+ }[c]));
+}
+
+function stageX(index) {
+ return layout.leftX + index * layout.colGap;
+}
+
+function measureNode(node) {
+ const width = node.width || layout.nodeW;
+ const height = node.height || layout.nodeH;
+ const cx = stageX(node.stage);
+ const y = layout.rowYs[node.row] + (node.yOffset || 0);
+ return {
+ ...node,
+ width,
+ height,
+ cx,
+ cy: y + height / 2,
+ x: cx - width / 2,
+ y
+ };
+}
+
+const nodes = new Map((dataflow.nodes || []).map((node) => [node.id, measureNode(node)]));
+
+function rectsOverlap(a, b, gap = 0) {
+ return !(
+ a.x + a.width + gap <= b.x ||
+ b.x + b.width + gap <= a.x ||
+ a.y + a.height + gap <= b.y ||
+ b.y + b.height + gap <= a.y
+ );
+}
+
+function validateDataflow() {
+ const problems = [];
+ if (dataflow.schema_version !== 1) problems.push('Data-flow files must set "schema_version": 1.');
+ if (dataflow.diagram_type !== 'dataflow') problems.push('Data-flow files must set "diagram_type": "dataflow".');
+ if (!dataflow.meta?.title) problems.push('Data-flow files must include meta.title.');
+ if (!Array.isArray(dataflow.stages) || dataflow.stages.length < 2) {
+ problems.push('Data-flow diagrams need at least two stages.');
+ }
+ if (!Array.isArray(dataflow.nodes) || dataflow.nodes.length < 2) {
+ problems.push('Data-flow diagrams need at least two nodes.');
+ }
+ if (!Array.isArray(dataflow.flows)) problems.push('Data-flow diagrams must include a flows array.');
+ if (nodes.size !== (dataflow.nodes || []).length) problems.push('Node ids must be unique.');
+
+ for (const node of nodes.values()) {
+ if (typeof node.stage !== 'number' || node.stage < 0 || node.stage >= dataflow.stages.length) {
+ problems.push(`Node "${node.id}" uses invalid stage ${node.stage}.`);
+ }
+ if (typeof node.row !== 'number' || node.row < 0 || node.row >= layout.rowYs.length) {
+ problems.push(`Node "${node.id}" uses invalid row ${node.row}.`);
+ }
+ if (node.x < 24 || node.x + node.width > viewBox[0] - 24) {
+ problems.push(`Node "${node.id}" exceeds the horizontal bounds of the viewBox.`);
+ }
+ if (node.y < layout.stageY + layout.stageH + 22 || node.y + node.height > viewBox[1] - layout.stageBottomPad) {
+ problems.push(`Node "${node.id}" exceeds the readable diagram area.`);
+ }
+ }
+
+ for (let i = 0; i < dataflow.nodes.length; i += 1) {
+ for (let j = i + 1; j < dataflow.nodes.length; j += 1) {
+ const a = nodes.get(dataflow.nodes[i].id);
+ const b = nodes.get(dataflow.nodes[j].id);
+ if (rectsOverlap(a, b, 10)) {
+ problems.push(`Nodes "${a.id}" and "${b.id}" are too close.`);
+ }
+ }
+ }
+
+ for (const flow of dataflow.flows || []) {
+ if (!nodes.has(flow.from)) problems.push(`Flow "${flow.label || flow.from}" references unknown source "${flow.from}".`);
+ if (!nodes.has(flow.to)) problems.push(`Flow "${flow.label || flow.to}" references unknown target "${flow.to}".`);
+ if (!flow.label) problems.push(`Flow "${flow.from}" -> "${flow.to}" must include a short data label.`);
+ if (nodes.has(flow.from) && nodes.has(flow.to)) {
+ const routed = pathFor(flow);
+ const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
+ const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
+ if (distance < 34) problems.push(`Flow "${flow.label}" is too short to read cleanly.`);
+ }
+ }
+
+ const lastStageX = stageX((dataflow.stages || []).length - 1);
+ if (lastStageX + layout.stageW / 2 > viewBox[0] - 24) problems.push('Stages exceed viewBox width.');
+
+ if (problems.length) {
+ throw new Error(`Data-flow layout validation failed:\n- ${problems.join('\n- ')}`);
+ }
+}
+
+function anchor(node, side) {
+ switch (side || 'auto') {
+ case 'left': return [node.x, node.cy];
+ case 'right': return [node.x + node.width, node.cy];
+ case 'top': return [node.cx, node.y];
+ case 'bottom': return [node.cx, node.y + node.height];
+ default:
+ return [node.x + node.width, node.cy];
+ }
+}
+
+function defaultFromSide(from, to) {
+ if (to.cx < from.cx) return 'left';
+ if (to.cx > from.cx) return 'right';
+ if (to.cy > from.cy) return 'bottom';
+ return 'top';
+}
+
+function defaultToSide(from, to) {
+ if (to.cx < from.cx) return 'right';
+ if (to.cx > from.cx) return 'left';
+ if (to.cy > from.cy) return 'top';
+ return 'bottom';
+}
+
+function routeVia(flow, from, to, start, end) {
+ if (flow.via) return flow.via;
+ switch (flow.route || 'auto') {
+ case 'straight':
+ return [];
+ case 'vertical-channel': {
+ const x = flow.channelX || start[0] + (end[0] > start[0] ? 44 : -44);
+ return [[x, start[1]], [x, end[1]]];
+ }
+ case 'bottom-channel': {
+ const y = flow.channelY || Math.max(from.y + from.height, to.y + to.height) + 26;
+ return [[start[0], y], [end[0], y]];
+ }
+ case 'top-channel': {
+ const y = flow.channelY || Math.min(from.y, to.y) - 24;
+ return [[start[0], y], [end[0], y]];
+ }
+ case 'auto':
+ default: {
+ if (Math.abs(start[1] - end[1]) < 4) return [];
+ const midX = start[0] + (end[0] - start[0]) / 2;
+ return [[midX, start[1]], [midX, end[1]]];
+ }
+ }
+}
+
+function pathFor(flow) {
+ const from = nodes.get(flow.from);
+ const to = nodes.get(flow.to);
+ const start = anchor(from, flow.fromSide || defaultFromSide(from, to));
+ const end = anchor(to, flow.toSide || defaultToSide(from, to));
+ const points = [start, ...routeVia(flow, from, to, start, end), end];
+ return {
+ d: points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' '),
+ points
+ };
+}
+
+function labelPoint(flow, points) {
+ if (flow.labelAt) return flow.labelAt;
+ if (points.length === 2) {
+ return [
+ (points[0][0] + points[1][0]) / 2 + (flow.labelDx || 0),
+ points[0][1] - 10 + (flow.labelDy || 0)
+ ];
+ }
+ const segmentIndex = Math.min(points.length - 2, Math.max(0, flow.labelSegment ?? 1));
+ const a = points[segmentIndex];
+ const b = points[segmentIndex + 1];
+ return [(a[0] + b[0]) / 2 + (flow.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (flow.labelDy || 0)];
+}
+
+function renderDefinitions() {
+ return ` <!-- Definitions -->
+ <defs>
+ <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-default" />
+ </marker>
+ <marker id="arrowhead-emphasis" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-emphasis" />
+ </marker>
+ <marker id="arrowhead-security" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-security" />
+ </marker>
+ <marker id="arrowhead-dashed" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-dashed" />
+ </marker>
+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
+ <path d="M 40 0 L 0 0 0 40" class="c-grid" stroke-width="0.5"/>
+ </pattern>
+ </defs>`;
+}
+
+function renderStage(stage, index) {
+ const cx = stageX(index);
+ const x = cx - layout.stageW / 2;
+ const h = viewBox[1] - layout.stageY - layout.stageBottomPad;
+ return ` <rect x="${x}" y="${layout.stageY}" width="${layout.stageW}" height="${h}" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="${cx}" y="${layout.stageY + 22}" class="t-dim" font-size="9" font-weight="600" text-anchor="middle">${String(index + 1).padStart(2, '0')} / ${esc(stage.label)}</text>`;
+}
+
+function renderNode(node) {
+ const fill = typeClass[node.type] || 'c-external';
+ const accent = textClass[node.type] || 't-muted';
+ const tag = node.tag
+ ? `\n <text x="${node.cx}" y="${node.y + node.height - 11}" class="${accent}" font-size="7" text-anchor="middle">${esc(node.tag)}</text>`
+ : '';
+ return ` <rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="6" class="c-mask"/>
+ <rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="6" class="${fill}" stroke-width="1.5"/>
+ <text x="${node.cx}" y="${node.y + 21}" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">${esc(node.label)}</text>
+ <text x="${node.cx}" y="${node.y + 37}" class="t-muted" font-size="7" text-anchor="middle">${esc(node.sublabel || '')}</text>${tag}`;
+}
+
+function flowAccent(flow) {
+ return flow.variant === 'security'
+ ? 't-security'
+ : flow.variant === 'emphasis'
+ ? 't-backend'
+ : flow.variant === 'dashed'
+ ? 't-messagebus'
+ : 't-muted';
+}
+
+function renderFlowPath(flow) {
+ const [cls, marker] = arrowClass[flow.variant || 'default'] || arrowClass.default;
+ const routed = pathFor(flow);
+ const strokeWidth = flow.width || (flow.variant === 'emphasis' ? 1.8 : 1.4);
+ return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
+}
+
+function renderFlowLabel(flow) {
+ const routed = pathFor(flow);
+ const [lx, ly] = labelPoint(flow, routed.points);
+ const labelW = Math.max(34, flow.label.length * 4.9 + 12);
+ const classification = flow.classification
+ ? `\n <text x="${lx}" y="${ly + 11}" class="t-dim" font-size="7" text-anchor="middle">${esc(flow.classification)}</text>`
+ : '';
+ const labelH = flow.classification ? 27 : layout.labelH;
+ return ` <rect x="${lx - labelW / 2}" y="${ly - 11}" width="${labelW}" height="${labelH}" rx="4" class="c-mask"/>
+ <text x="${lx}" y="${ly}" class="${flowAccent(flow)}" font-size="8" text-anchor="middle">${esc(flow.label)}</text>${classification}`;
+}
+
+function renderLegend() {
+ const y = viewBox[1] - 36;
+ return ` <text x="214" y="${y - 20}" class="t-primary" font-size="10" font-weight="600">Legend</text>
+ <path d="M 214 ${y} L 248 ${y}" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <text x="257" y="${y + 3}" class="t-muted" font-size="8">primary data</text>
+ <path d="M 340 ${y} L 374 ${y}" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <text x="383" y="${y + 3}" class="t-muted" font-size="8">policy / PII</text>
+ <path d="M 480 ${y} L 514 ${y}" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <text x="523" y="${y + 3}" class="t-muted" font-size="8">async batch</text>
+ <rect x="625" y="${y - 8}" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>
+ <text x="646" y="${y}" class="t-muted" font-size="8">data store</text>`;
+}
+
+function renderSvg() {
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+${renderDefinitions()}
+
+ <!-- Background Grid -->
+ <rect width="100%" height="100%" fill="url(#grid)" />
+
+ <!-- Data Stages -->
+${dataflow.stages.map(renderStage).join('\n\n')}
+
+ <!-- Flow paths -->
+${(dataflow.flows || []).map(renderFlowPath).join('\n')}
+
+ <!-- Nodes -->
+${[...nodes.values()].map(renderNode).join('\n\n')}
+
+ <!-- Flow labels -->
+${(dataflow.flows || []).map(renderFlowLabel).join('\n')}
+
+ <!-- Legend -->
+${renderLegend()}
+ </svg>`;
+}
+
+function renderCards() {
+ const cards = dataflow.cards || [];
+ return ` <!-- Info Cards -->
+ <div class="cards">
+${cards.map((card) => ` <div class="card">
+ <div class="card-header">
+ <div class="card-dot ${esc(card.dot)}"></div>
+ <h3>${esc(card.title)}</h3>
+ </div>
+ <ul>
+${card.items.map((item) => ` <li>&bull; ${esc(item)}</li>`).join('\n')}
+ </ul>
+ </div>`).join('\n\n')}
+ </div>`;
+}
+
+function applyTemplate(svg, cards) {
+ return template
+ .replace('<title>[PROJECT NAME] Architecture Diagram</title>', `<title>${esc(dataflow.meta.title)} Diagram</title>`)
+ .replace('<h1>[PROJECT NAME] Architecture</h1>', `<h1>${esc(dataflow.meta.title)}</h1>`)
+ .replace('<p class="subtitle">[Subtitle description]</p>', `<p class="subtitle">${esc(dataflow.meta.subtitle || '')}</p>`)
+ .replace(/ <svg viewBox="0 0 1000 680">[\s\S]*? <\/svg>/, svg)
+ .replace(/ <!-- Info Cards -->[\s\S]*? <!-- Footer -->/, `${cards}\n\n <!-- Footer -->`)
+ .replace('[Project Name] &bull; [Additional metadata]', 'Data-flow diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export');
+}
+
+validateDataflow();
+fs.mkdirSync(path.dirname(outPath), { recursive: true });
+fs.writeFileSync(outPath, applyTemplate(renderSvg(), renderCards()));
+console.log(outPath);
diff --git a/archify/schemas/dataflow.schema.json b/archify/schemas/dataflow.schema.json
new file mode 100644
index 00000000..673ef861
--- /dev/null
+++ b/archify/schemas/dataflow.schema.json
@@ -0,0 +1,149 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/tt-a1i/archify/schemas/dataflow.schema.json",
+ "title": "Archify Data Flow Diagram",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schema_version", "diagram_type", "meta", "stages", "nodes", "flows"],
+ "properties": {
+ "schema_version": {
+ "const": 1
+ },
+ "diagram_type": {
+ "const": "dataflow"
+ },
+ "meta": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["title"],
+ "properties": {
+ "title": { "type": "string", "minLength": 1 },
+ "subtitle": { "type": "string" },
+ "output": { "type": "string" },
+ "viewBox": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number", "minimum": 360 },
+ { "type": "number", "minimum": 360 }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ }
+ }
+ },
+ "stages": {
+ "type": "array",
+ "minItems": 2,
+ "maxItems": 5,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["label"],
+ "properties": {
+ "label": { "type": "string", "minLength": 1 }
+ }
+ }
+ },
+ "nodes": {
+ "type": "array",
+ "minItems": 2,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "type", "label", "stage", "row"],
+ "properties": {
+ "id": { "$ref": "#/$defs/id" },
+ "type": {
+ "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
+ },
+ "label": { "type": "string", "minLength": 1 },
+ "sublabel": { "type": "string" },
+ "tag": { "type": "string" },
+ "stage": { "type": "integer", "minimum": 0 },
+ "row": { "type": "integer", "minimum": 0 },
+ "width": { "type": "number", "minimum": 48 },
+ "height": { "type": "number", "minimum": 36 },
+ "yOffset": { "type": "number" }
+ }
+ }
+ },
+ "flows": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["from", "to", "label"],
+ "properties": {
+ "from": { "$ref": "#/$defs/id" },
+ "to": { "$ref": "#/$defs/id" },
+ "label": { "type": "string", "minLength": 1 },
+ "classification": { "type": "string" },
+ "variant": {
+ "enum": ["default", "emphasis", "security", "dashed"]
+ },
+ "route": {
+ "enum": ["auto", "straight", "vertical-channel", "bottom-channel", "top-channel"]
+ },
+ "fromSide": {
+ "enum": ["left", "right", "top", "bottom"]
+ },
+ "toSide": {
+ "enum": ["left", "right", "top", "bottom"]
+ },
+ "channelX": { "type": "number" },
+ "channelY": { "type": "number" },
+ "labelAt": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number" },
+ { "type": "number" }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ },
+ "labelDx": { "type": "number" },
+ "labelDy": { "type": "number" },
+ "labelSegment": { "type": "integer", "minimum": 0 },
+ "via": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number" },
+ { "type": "number" }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ }
+ },
+ "width": { "type": "number", "minimum": 0.5 }
+ }
+ }
+ },
+ "cards": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["dot", "title", "items"],
+ "properties": {
+ "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
+ "title": { "type": "string", "minLength": 1 },
+ "items": {
+ "type": "array",
+ "items": { "type": "string" }
+ }
+ }
+ }
+ }
+ },
+ "$defs": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
+ }
+ }
+}
diff --git a/examples/dataflow-product-analytics.html b/examples/dataflow-product-analytics.html
new file mode 100644
index 00000000..efe15c30
--- /dev/null
+++ b/examples/dataflow-product-analytics.html
@@ -0,0 +1,1110 @@
+<!DOCTYPE html>
+<html lang="en" data-theme="dark">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Product Analytics Data Flow Diagram</title>
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
+ <style>
+ /* ==========================================================
+ THEME VARIABLES — switch by toggling [data-theme] on <html>
+ ========================================================== */
+ :root,
+ [data-theme="dark"] {
+ --bg: #020617;
+ --grid: #1e293b;
+ --text: #ffffff;
+ --text-muted: #94a3b8;
+ --text-dim: #475569;
+
+ --panel: rgba(15, 23, 42, 0.5);
+ --panel-border: #1e293b;
+ --lane-fill: rgba(15, 23, 42, 0.22);
+ --lane-stroke: #334155;
+
+ --arrow: #64748b;
+ --arrow-emphasis: #34d399;
+
+ /* Opaque mask color used behind semi-transparent component fills
+ so the arrows drawn underneath are properly hidden. */
+ --mask: #0f172a;
+
+ --frontend-fill: rgba(8, 51, 68, 0.4);
+ --frontend-stroke: #22d3ee;
+ --backend-fill: rgba(6, 78, 59, 0.4);
+ --backend-stroke: #34d399;
+ --database-fill: rgba(76, 29, 149, 0.4);
+ --database-stroke: #a78bfa;
+ --cloud-fill: rgba(120, 53, 15, 0.3);
+ --cloud-stroke: #fbbf24;
+ --security-fill: rgba(136, 19, 55, 0.4);
+ --security-stroke: #fb7185;
+ --messagebus-fill: rgba(251, 146, 60, 0.3);
+ --messagebus-stroke:#fb923c;
+ --external-fill: rgba(30, 41, 59, 0.5);
+ --external-stroke: #94a3b8;
+
+ --toolbar-bg: rgba(15, 23, 42, 0.8);
+ --toolbar-border: #334155;
+ --toolbar-text: #e2e8f0;
+ --toolbar-hover: rgba(15, 23, 42, 0.95);
+ --toolbar-menu-bg: #0f172a;
+ }
+
+ [data-theme="light"] {
+ --bg: #f8fafc;
+ --grid: #e2e8f0;
+ --text: #0f172a;
+ --text-muted: #64748b;
+ --text-dim: #94a3b8;
+
+ --panel: #ffffff;
+ --panel-border: #e2e8f0;
+ --lane-fill: rgba(248, 250, 252, 0.65);
+ --lane-stroke: #cbd5e1;
+
+ --arrow: #94a3b8;
+ --arrow-emphasis: #059669;
+
+ --mask: #ffffff;
+
+ --frontend-fill: rgba(34, 211, 238, 0.15);
+ --frontend-stroke: #0891b2;
+ --backend-fill: rgba(52, 211, 153, 0.18);
+ --backend-stroke: #059669;
+ --database-fill: rgba(167, 139, 250, 0.2);
+ --database-stroke: #7c3aed;
+ --cloud-fill: rgba(251, 191, 36, 0.18);
+ --cloud-stroke: #d97706;
+ --security-fill: rgba(251, 113, 133, 0.15);
+ --security-stroke: #e11d48;
+ --messagebus-fill: rgba(251, 146, 60, 0.15);
+ --messagebus-stroke:#ea580c;
+ --external-fill: rgba(148, 163, 184, 0.18);
+ --external-stroke: #64748b;
+
+ --toolbar-bg: rgba(255, 255, 255, 0.92);
+ --toolbar-border: #cbd5e1;
+ --toolbar-text: #334155;
+ --toolbar-hover: #ffffff;
+ --toolbar-menu-bg: #ffffff;
+ }
+
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+
+ body {
+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ background: var(--bg);
+ min-height: 100vh;
+ padding: 2rem;
+ color: var(--text);
+ transition: background 0.2s ease, color 0.2s ease;
+ }
+
+ .container { max-width: 1200px; margin: 0 auto; }
+
+ .header { margin-bottom: 2rem; }
+
+ .header-row {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ margin-bottom: 0.5rem;
+ }
+
+ .pulse-dot {
+ width: 12px;
+ height: 12px;
+ background: var(--frontend-stroke);
+ border-radius: 50%;
+ animation: pulse 2s infinite;
+ }
+
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+
+ h1 {
+ font-size: 1.5rem;
+ font-weight: 700;
+ letter-spacing: -0.025em;
+ }
+
+ .subtitle {
+ color: var(--text-muted);
+ font-size: 0.875rem;
+ margin-left: 1.75rem;
+ }
+
+ .diagram-container {
+ background: var(--panel);
+ border-radius: 1rem;
+ border: 1px solid var(--panel-border);
+ padding: 1.5rem;
+ overflow-x: auto;
+ }
+
+ svg {
+ width: 100%;
+ min-width: min(900px, 100%);
+ display: block;
+ }
+
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 1rem;
+ margin-top: 2rem;
+ }
+
+ .card {
+ background: var(--panel);
+ border-radius: 0.75rem;
+ border: 1px solid var(--panel-border);
+ padding: 1.25rem;
+ }
+
+ .card-header {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin-bottom: 0.75rem;
+ }
+
+ .card-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ }
+
+ .card-dot.cyan { background: var(--frontend-stroke); }
+ .card-dot.emerald { background: var(--backend-stroke); }
+ .card-dot.violet { background: var(--database-stroke); }
+ .card-dot.amber { background: var(--cloud-stroke); }
+ .card-dot.rose { background: var(--security-stroke); }
+ .card-dot.orange { background: var(--messagebus-stroke); }
+ .card-dot.slate { background: var(--external-stroke); }
+
+ .card h3 { font-size: 0.875rem; font-weight: 600; color: var(--text); }
+
+ .card ul {
+ list-style: none;
+ color: var(--text-muted);
+ font-size: 0.75rem;
+ }
+
+ .card li { margin-bottom: 0.375rem; }
+
+ .footer {
+ text-align: center;
+ margin-top: 1.5rem;
+ color: var(--text-dim);
+ font-size: 0.75rem;
+ }
+
+ /* ==========================================================
+ Print stylesheet — hide interactive controls, force light,
+ drop the grid so the diagram doesn't waste ink, use landscape
+ so wide diagrams fit, pack summary cards into 2 columns to
+ avoid an orphan card on a trailing page.
+ ========================================================== */
+ @page { size: landscape; margin: 1.5cm; }
+
+ @media print {
+ :root, [data-theme="dark"], [data-theme="light"] {
+ --bg: #ffffff;
+ --grid: transparent;
+ --panel: #ffffff;
+ --panel-border: #e2e8f0;
+ --text: #0f172a;
+ --text-muted: #475569;
+ --text-dim: #94a3b8;
+ --mask: #ffffff;
+ }
+ body { background: #ffffff !important; padding: 0; }
+ .container { max-width: none; }
+ .toolbar, .archify-toast { display: none !important; }
+ .diagram-container, .card { box-shadow: none; border-color: #e2e8f0; }
+ .cards { grid-template-columns: 1fr 1fr; }
+ /* Ensure elements break sensibly across pages */
+ .card { break-inside: avoid; page-break-inside: avoid; }
+ .diagram-container { break-inside: avoid; page-break-inside: avoid; }
+ h1, .subtitle { color: #0f172a; }
+ }
+
+ /* ==========================================================
+ TOOLBAR (theme toggle + export menu)
+ ========================================================== */
+ .toolbar {
+ position: fixed;
+ top: 1rem;
+ right: 1rem;
+ display: flex;
+ gap: 0.5rem;
+ z-index: 100;
+ }
+ .toolbar button {
+ background: var(--toolbar-bg);
+ color: var(--toolbar-text);
+ border: 1px solid var(--toolbar-border);
+ padding: 0.5rem 0.875rem;
+ border-radius: 0.5rem;
+ font-family: inherit;
+ font-size: 0.75rem;
+ font-weight: 500;
+ cursor: pointer;
+ backdrop-filter: blur(8px);
+ transition: background 0.15s, border-color 0.15s;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ }
+ .toolbar button:hover {
+ background: var(--toolbar-hover);
+ border-color: var(--arrow);
+ }
+ .toolbar button:focus-visible {
+ outline: 2px solid var(--frontend-stroke);
+ outline-offset: 2px;
+ }
+ .toolbar .export-wrap { position: relative; }
+ .toolbar .export-menu {
+ position: absolute;
+ top: calc(100% + 0.375rem);
+ right: 0;
+ background: var(--toolbar-menu-bg);
+ border: 1px solid var(--toolbar-border);
+ border-radius: 0.5rem;
+ padding: 0.375rem;
+ min-width: 160px;
+ display: none;
+ flex-direction: column;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);
+ }
+ .toolbar .export-menu.open { display: flex; }
+ .toolbar .export-menu button {
+ background: transparent;
+ border: 0;
+ justify-content: space-between;
+ width: 100%;
+ text-align: left;
+ padding: 0.5rem 0.75rem;
+ }
+ .toolbar .export-menu button:hover {
+ background: var(--toolbar-hover);
+ }
+ .toolbar .export-menu .hint {
+ color: var(--text-dim);
+ font-size: 0.625rem;
+ }
+ .toolbar .export-menu hr {
+ border: 0;
+ border-top: 1px solid var(--toolbar-border);
+ margin: 0.25rem 0.375rem;
+ opacity: 0.5;
+ }
+
+ /* Toast — brief feedback for actions like "copied" */
+ .archify-toast {
+ position: fixed;
+ top: 1rem;
+ left: 50%;
+ transform: translateX(-50%) translateY(-8px);
+ background: var(--toolbar-menu-bg);
+ color: var(--text);
+ border: 1px solid var(--toolbar-border);
+ padding: 0.5rem 1rem;
+ border-radius: 0.5rem;
+ font-family: inherit;
+ font-size: 0.75rem;
+ opacity: 0;
+ transition: opacity 0.2s, transform 0.2s;
+ z-index: 200;
+ pointer-events: none;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);
+ }
+ .archify-toast.show {
+ opacity: 1;
+ transform: translateX(-50%) translateY(0);
+ }
+
+ @media (max-width: 720px) {
+ body { padding: 1rem; }
+ .toolbar {
+ position: static;
+ justify-content: flex-end;
+ margin-bottom: 1rem;
+ }
+ .header { margin-bottom: 1.25rem; }
+ .header-row {
+ gap: 0.75rem;
+ align-items: flex-start;
+ }
+ h1 {
+ font-size: 1.25rem;
+ line-height: 1.25;
+ }
+ .subtitle {
+ margin-left: 0;
+ font-size: 0.8125rem;
+ line-height: 1.55;
+ }
+ .diagram-container {
+ padding: 0.75rem;
+ border-radius: 0.75rem;
+ }
+ .cards {
+ grid-template-columns: 1fr;
+ margin-top: 1rem;
+ }
+ }
+
+ /* ==========================================================
+ SVG SEMANTIC CLASSES — use these instead of inline fill/stroke
+ ========================================================== */
+ .c-grid { stroke: var(--grid); fill: none; }
+ .c-mask { fill: var(--mask); stroke: none; }
+
+ .c-frontend { fill: var(--frontend-fill); stroke: var(--frontend-stroke); }
+ .c-backend { fill: var(--backend-fill); stroke: var(--backend-stroke); }
+ .c-database { fill: var(--database-fill); stroke: var(--database-stroke); }
+ .c-cloud { fill: var(--cloud-fill); stroke: var(--cloud-stroke); }
+ .c-security { fill: var(--security-fill); stroke: var(--security-stroke); }
+ .c-messagebus { fill: var(--messagebus-fill); stroke: var(--messagebus-stroke); }
+ .c-external { fill: var(--external-fill); stroke: var(--external-stroke); }
+
+ /* Text helpers */
+ .t-primary { fill: var(--text); }
+ .t-muted { fill: var(--text-muted); }
+ .t-dim { fill: var(--text-dim); }
+ .t-frontend { fill: var(--frontend-stroke); }
+ .t-backend { fill: var(--backend-stroke); }
+ .t-database { fill: var(--database-stroke); }
+ .t-cloud { fill: var(--cloud-stroke); }
+ .t-security { fill: var(--security-stroke); }
+ .t-messagebus { fill: var(--messagebus-stroke); }
+ .t-external { fill: var(--external-stroke); }
+
+ /* Arrows */
+ .a-default { stroke: var(--arrow); fill: none; }
+ .a-emphasis { stroke: var(--arrow-emphasis); fill: none; }
+ .a-security { stroke: var(--security-stroke); fill: none; stroke-dasharray: 5,5; }
+ .a-dashed { stroke: var(--database-stroke); fill: none; stroke-dasharray: 4,4; }
+
+ /* Arrowhead markers reference these */
+ .m-default { fill: var(--arrow); }
+ .m-emphasis { fill: var(--arrow-emphasis); }
+ .m-security { fill: var(--security-stroke); }
+ .m-dashed { fill: var(--database-stroke); }
+
+ /* Dashed boundary variants */
+ .c-security-group { fill: transparent; stroke: var(--security-stroke); stroke-dasharray: 4,4; }
+ .c-region { fill: rgba(251, 191, 36, 0.05); stroke: var(--cloud-stroke); stroke-dasharray: 8,4; }
+ .c-lane { fill: var(--lane-fill); stroke: var(--lane-stroke); stroke-dasharray: 6,6; }
+ </style>
+</head>
+<body>
+ <!-- Toolbar: theme toggle + export menu (present on every generated diagram)
+ Keyboard: T toggles theme, E opens export menu (when no input focused) -->
+ <div class="toolbar" role="toolbar" aria-label="Diagram actions">
+ <button id="btn-theme" type="button"
+ title="Toggle theme (T)"
+ aria-label="Toggle color theme"
+ aria-pressed="false">
+ <span id="theme-icon" aria-hidden="true">&#9790;</span>
+ <span id="theme-label">Dark</span>
+ </button>
+ <div class="export-wrap">
+ <button id="btn-export" type="button"
+ title="Export diagram (E)"
+ aria-label="Export diagram"
+ aria-haspopup="menu"
+ aria-expanded="false"
+ aria-controls="export-menu">
+ Export <span aria-hidden="true">&#9662;</span>
+ </button>
+ <div class="export-menu" id="export-menu" role="menu" aria-label="Export">
+ <button data-action="copy" type="button" role="menuitem" tabindex="-1">Copy to clipboard <span class="hint">PNG</span></button>
+ <hr role="separator" aria-hidden="true">
+ <button data-format="png" type="button" role="menuitem" tabindex="-1">Download PNG</button>
+ <button data-format="jpeg" type="button" role="menuitem" tabindex="-1">Download JPEG</button>
+ <button data-format="webp" type="button" role="menuitem" tabindex="-1">Download WebP</button>
+ <hr role="separator" aria-hidden="true">
+ <button data-format="svg" type="button" role="menuitem" tabindex="-1">Download SVG <span class="hint">vector</span></button>
+ </div>
+ </div>
+ </div>
+
+ <div class="container">
+ <!-- Header -->
+ <div class="header">
+ <div class="header-row">
+ <div class="pulse-dot"></div>
+ <h1>Product Analytics Data Flow</h1>
+ </div>
+ <p class="subtitle">Events, consent, PII isolation, warehouse sync, and downstream analytics</p>
+ </div>
+
+ <!-- Main Diagram -->
+ <div class="diagram-container">
+ <svg viewBox="0 0 900 720">
+ <!-- Definitions -->
+ <defs>
+ <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-default" />
+ </marker>
+ <marker id="arrowhead-emphasis" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-emphasis" />
+ </marker>
+ <marker id="arrowhead-security" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-security" />
+ </marker>
+ <marker id="arrowhead-dashed" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-dashed" />
+ </marker>
+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
+ <path d="M 40 0 L 0 0 0 40" class="c-grid" stroke-width="0.5"/>
+ </pattern>
+ </defs>
+
+ <!-- Background Grid -->
+ <rect width="100%" height="100%" fill="url(#grid)" />
+
+ <!-- Data Stages -->
+ <rect x="21" y="46" width="142" height="600" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="92" y="68" class="t-dim" font-size="9" font-weight="600" text-anchor="middle">01 / Sources</text>
+
+ <rect x="195" y="46" width="142" height="600" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="266" y="68" class="t-dim" font-size="9" font-weight="600" text-anchor="middle">02 / Ingest</text>
+
+ <rect x="369" y="46" width="142" height="600" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="440" y="68" class="t-dim" font-size="9" font-weight="600" text-anchor="middle">03 / Process</text>
+
+ <rect x="543" y="46" width="142" height="600" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="614" y="68" class="t-dim" font-size="9" font-weight="600" text-anchor="middle">04 / Store</text>
+
+ <rect x="717" y="46" width="142" height="600" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="788" y="68" class="t-dim" font-size="9" font-weight="600" text-anchor="middle">05 / Consume</text>
+
+ <!-- Flow paths -->
+ <path d="M 148 165 L 179 165 L 179 271 L 210 271" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 148 377 L 179 377 L 179 271 L 210 271" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>
+ <path d="M 322 271 L 322 124 L 384 124 L 384 165" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <path d="M 322 271 L 353 271 L 353 377 L 384 377" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 496 165 L 558 165" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <path d="M 496 377 L 558 377" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 614 406 L 634 406 L 634 560 L 614 560" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <path d="M 670 377 L 701 377 L 701 271 L 732 271" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>
+ <path d="M 670 589 L 701 589 L 701 483 L 732 483" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <path d="M 670 165 L 670 224 L 732 224 L 732 271" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+
+ <!-- Nodes -->
+ <rect x="36" y="136" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="36" y="136" width="112" height="58" rx="6" class="c-frontend" stroke-width="1.5"/>
+ <text x="92" y="157" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Web App</text>
+ <text x="92" y="173" class="t-muted" font-size="7" text-anchor="middle">browser SDK</text>
+ <text x="92" y="183" class="t-frontend" font-size="7" text-anchor="middle">events</text>
+
+ <rect x="36" y="348" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="36" y="348" width="112" height="58" rx="6" class="c-frontend" stroke-width="1.5"/>
+ <text x="92" y="369" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Mobile</text>
+ <text x="92" y="385" class="t-muted" font-size="7" text-anchor="middle">iOS / Android</text>
+ <text x="92" y="395" class="t-frontend" font-size="7" text-anchor="middle">events</text>
+
+ <rect x="210" y="242" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="210" y="242" width="112" height="58" rx="6" class="c-cloud" stroke-width="1.5"/>
+ <text x="266" y="263" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Edge API</text>
+ <text x="266" y="279" class="t-muted" font-size="7" text-anchor="middle">collector</text>
+ <text x="266" y="289" class="t-cloud" font-size="7" text-anchor="middle">TLS</text>
+
+ <rect x="384" y="136" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="384" y="136" width="112" height="58" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="440" y="157" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Consent Gate</text>
+ <text x="440" y="173" class="t-muted" font-size="7" text-anchor="middle">policy filter</text>
+ <text x="440" y="183" class="t-security" font-size="7" text-anchor="middle">PII guard</text>
+
+ <rect x="384" y="348" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="384" y="348" width="112" height="58" rx="6" class="c-messagebus" stroke-width="1.5"/>
+ <text x="440" y="369" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Event Stream</text>
+ <text x="440" y="385" class="t-muted" font-size="7" text-anchor="middle">Kafka topic</text>
+ <text x="440" y="395" class="t-messagebus" font-size="7" text-anchor="middle">ordered</text>
+
+ <rect x="558" y="136" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="558" y="136" width="112" height="58" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="614" y="157" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">PII Vault</text>
+ <text x="614" y="173" class="t-muted" font-size="7" text-anchor="middle">encrypted</text>
+ <text x="614" y="183" class="t-security" font-size="7" text-anchor="middle">restricted</text>
+
+ <rect x="558" y="348" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="558" y="348" width="112" height="58" rx="6" class="c-database" stroke-width="1.5"/>
+ <text x="614" y="369" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Warehouse</text>
+ <text x="614" y="385" class="t-muted" font-size="7" text-anchor="middle">analytics tables</text>
+ <text x="614" y="395" class="t-database" font-size="7" text-anchor="middle">curated</text>
+
+ <rect x="558" y="560" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="558" y="560" width="112" height="58" rx="6" class="c-database" stroke-width="1.5"/>
+ <text x="614" y="581" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Feature Store</text>
+ <text x="614" y="597" class="t-muted" font-size="7" text-anchor="middle">daily batch</text>
+ <text x="614" y="607" class="t-database" font-size="7" text-anchor="middle">derived</text>
+
+ <rect x="732" y="242" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="732" y="242" width="112" height="58" rx="6" class="c-backend" stroke-width="1.5"/>
+ <text x="788" y="263" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Dashboards</text>
+ <text x="788" y="279" class="t-muted" font-size="7" text-anchor="middle">product metrics</text>
+ <text x="788" y="289" class="t-backend" font-size="7" text-anchor="middle">SQL</text>
+
+ <rect x="732" y="454" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="732" y="454" width="112" height="58" rx="6" class="c-backend" stroke-width="1.5"/>
+ <text x="788" y="475" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">ML Model</text>
+ <text x="788" y="491" class="t-muted" font-size="7" text-anchor="middle">ranking job</text>
+ <text x="788" y="501" class="t-backend" font-size="7" text-anchor="middle">features</text>
+
+ <!-- Flow labels -->
+ <rect x="143.05" y="171" width="65.9" height="27" rx="4" class="c-mask"/>
+ <text x="176" y="182" class="t-backend" font-size="8" text-anchor="middle">clickstream</text>
+ <text x="176" y="193" class="t-dim" font-size="7" text-anchor="middle">user events</text>
+ <rect x="145.5" y="317" width="61" height="27" rx="4" class="c-mask"/>
+ <text x="176" y="328" class="t-muted" font-size="8" text-anchor="middle">app events</text>
+ <text x="176" y="339" class="t-dim" font-size="7" text-anchor="middle">device events</text>
+ <rect x="305.9" y="101" width="100.2" height="27" rx="4" class="c-mask"/>
+ <text x="356" y="112" class="t-security" font-size="8" text-anchor="middle">identity + consent</text>
+ <text x="356" y="123" class="t-dim" font-size="7" text-anchor="middle">PII touch</text>
+ <rect x="310.25" y="303" width="85.5" height="27" rx="4" class="c-mask"/>
+ <text x="353" y="314" class="t-backend" font-size="8" text-anchor="middle">accepted events</text>
+ <text x="353" y="325" class="t-dim" font-size="7" text-anchor="middle">append-only</text>
+ <rect x="500.6" y="167" width="70.80000000000001" height="27" rx="4" class="c-mask"/>
+ <text x="536" y="178" class="t-security" font-size="8" text-anchor="middle">identity map</text>
+ <text x="536" y="189" class="t-dim" font-size="7" text-anchor="middle">encrypted PII</text>
+ <rect x="481.8" y="356" width="90.4" height="27" rx="4" class="c-mask"/>
+ <text x="527" y="367" class="t-backend" font-size="8" text-anchor="middle">normalized facts</text>
+ <text x="527" y="378" class="t-dim" font-size="7" text-anchor="middle">non-PII</text>
+ <rect x="598.8" y="462" width="90.4" height="27" rx="4" class="c-mask"/>
+ <text x="644" y="473" class="t-messagebus" font-size="8" text-anchor="middle">daily aggregates</text>
+ <text x="644" y="484" class="t-dim" font-size="7" text-anchor="middle">batch</text>
+ <rect x="667.05" y="299" width="65.9" height="27" rx="4" class="c-mask"/>
+ <text x="700" y="310" class="t-muted" font-size="8" text-anchor="middle">metrics SQL</text>
+ <text x="700" y="321" class="t-dim" font-size="7" text-anchor="middle">read-only</text>
+ <rect x="661.25" y="501" width="85.5" height="27" rx="4" class="c-mask"/>
+ <text x="704" y="512" class="t-messagebus" font-size="8" text-anchor="middle">feature vectors</text>
+ <text x="704" y="523" class="t-dim" font-size="7" text-anchor="middle">derived</text>
+ <rect x="641.25" y="235" width="85.5" height="27" rx="4" class="c-mask"/>
+ <text x="684" y="246" class="t-security" font-size="8" text-anchor="middle">restricted join</text>
+ <text x="684" y="257" class="t-dim" font-size="7" text-anchor="middle">approved only</text>
+
+ <!-- Legend -->
+ <text x="214" y="664" class="t-primary" font-size="10" font-weight="600">Legend</text>
+ <path d="M 214 684 L 248 684" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <text x="257" y="687" class="t-muted" font-size="8">primary data</text>
+ <path d="M 340 684 L 374 684" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <text x="383" y="687" class="t-muted" font-size="8">policy / PII</text>
+ <path d="M 480 684 L 514 684" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <text x="523" y="687" class="t-muted" font-size="8">async batch</text>
+ <rect x="625" y="676" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>
+ <text x="646" y="684" class="t-muted" font-size="8">data store</text>
+ </svg>
+ </div>
+
+ <!-- Info Cards -->
+ <div class="cards">
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot emerald"></div>
+ <h3>Primary Data Path</h3>
+ </div>
+ <ul>
+ <li>&bull; Events move left to right through source, ingest, process, store, and consume stages</li>
+ <li>&bull; The hot path stays visually clear even with secondary batch flows</li>
+ <li>&bull; Labels name data assets instead of generic API verbs</li>
+ </ul>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot rose"></div>
+ <h3>Sensitive Boundary</h3>
+ </div>
+ <ul>
+ <li>&bull; Consent and PII paths are styled as security flows</li>
+ <li>&bull; PII lands in a restricted vault, separate from the analytics warehouse</li>
+ <li>&bull; Restricted joins are visible without implying default access</li>
+ </ul>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot orange"></div>
+ <h3>Derived Consumers</h3>
+ </div>
+ <ul>
+ <li>&bull; Dashboards read curated facts from the warehouse</li>
+ <li>&bull; Feature vectors are derived by batch from analytics tables</li>
+ <li>&bull; Consumption paths stay distinct from collection and consent handling</li>
+ </ul>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <p class="footer">
+ Data-flow diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export
+ </p>
+ </div>
+
+ <script>
+ /* ============================================================
+ Theme toggle — persists to localStorage, respects system pref
+ ============================================================ */
+ var Archify = {};
+
+ Archify.theme = (function () {
+ var STORAGE_KEY = 'archify-theme';
+ var html = document.documentElement;
+ var btn = document.getElementById('btn-theme');
+ var icon = document.getElementById('theme-icon');
+ var label = document.getElementById('theme-label');
+
+ function resolveInitial() {
+ // URL param wins (useful for deterministic screenshots / share links)
+ try {
+ var param = new URLSearchParams(window.location.search).get('theme');
+ if (param === 'light' || param === 'dark') return param;
+ } catch (_) {}
+ var saved = localStorage.getItem(STORAGE_KEY);
+ if (saved === 'light' || saved === 'dark') return saved;
+ return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
+ }
+
+ function apply(theme) {
+ html.setAttribute('data-theme', theme);
+ icon.textContent = theme === 'dark' ? '\u263E' : '\u263C';
+ label.textContent = theme === 'dark' ? 'Dark' : 'Light';
+ btn.setAttribute('aria-pressed', theme === 'light' ? 'true' : 'false');
+ }
+
+ function toggle() {
+ var next = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
+ apply(next);
+ localStorage.setItem(STORAGE_KEY, next);
+ }
+
+ apply(resolveInitial());
+ btn.addEventListener('click', toggle);
+
+ return { toggle: toggle };
+ })();
+
+ /* ============================================================
+ Export — PNG / JPEG / WebP / SVG (download) and Copy PNG (clipboard)
+
+ Raster exports are always rendered at 4x source resolution for
+ maximum sharpness. The trick: we set the serialized SVG's
+ `width`/`height` to viewBox * 4 so the browser rasterizes the
+ vectors at that resolution natively. drawImage then draws at
+ the image's natural size (no upscaling = no blur).
+
+ JPEG/WebP paint the current theme's background explicitly since
+ those formats have no alpha channel.
+ ============================================================ */
+ (function () {
+ var RASTER_SCALE = 4;
+
+ function diagramFilename() {
+ var title = (document.title || 'diagram').replace(/\s+Architecture(\s+Diagram)?$/i, '').trim();
+ return title.replace(/[^a-z0-9_\-]+/gi, '-')
+ .toLowerCase()
+ .replace(/^-+|-+$/g, '') || 'diagram';
+ }
+
+ function currentBg() {
+ return getComputedStyle(document.body).backgroundColor || '#ffffff';
+ }
+
+ /**
+ * Serialize the main SVG into a standalone document.
+ *
+ * Two modes:
+ * - Default (opts.autoTheme=false) — locks the serialized SVG to the
+ * viewer's current theme. Used by the raster pipeline
+ * (PNG/JPEG/WebP/clipboard) because canvas rasterization needs
+ * deterministic colors; a raster cannot react to
+ * prefers-color-scheme after encoding.
+ * - autoTheme=true — emits BOTH dark and light variable sets plus a
+ * `@media (prefers-color-scheme)` rule so the resulting SVG
+ * self-themes when embedded in GitHub READMEs or other hosts that
+ * expose a color scheme. Used for "Download SVG".
+ */
+ function serializeSvg(scale, opts) {
+ // scale: integer multiplier for intrinsic SVG pixel dimensions used by
+ // the raster path. Defaults to 1 (natural size) for SVG download.
+ scale = scale || 1;
+ opts = opts || {};
+ var autoTheme = opts.autoTheme === true;
+
+ var svg = document.querySelector('.diagram-container svg');
+ var clone = svg.cloneNode(true);
+
+ var vb = svg.viewBox.baseVal;
+ // Scale width/height so the browser rasterizes the vectors at target
+ // resolution directly. viewBox stays unchanged so coordinates don't
+ // shift. This is the key to sharp rasters — do NOT scale later via
+ // canvas upscaling.
+ clone.setAttribute('width', vb.width * scale);
+ clone.setAttribute('height', vb.height * scale);
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
+
+ var hostStyle = Array.prototype.map.call(document.querySelectorAll('style'), function (s) {
+ return s.textContent;
+ }).join('\n');
+
+ var varNames = [
+ '--bg','--grid','--text','--text-muted','--text-dim',
+ '--arrow','--arrow-emphasis','--mask',
+ '--frontend-fill','--frontend-stroke',
+ '--backend-fill','--backend-stroke',
+ '--database-fill','--database-stroke',
+ '--cloud-fill','--cloud-stroke',
+ '--security-fill','--security-stroke',
+ '--messagebus-fill','--messagebus-stroke',
+ '--external-fill','--external-stroke'
+ ];
+
+ // Resolve the full variable set for a given data-theme via an
+ // off-DOM probe, independent of what the viewer is currently set to.
+ function resolveVars(themeAttr) {
+ var probe = document.createElement('div');
+ probe.setAttribute('data-theme', themeAttr);
+ probe.style.cssText = 'position:absolute;width:0;height:0;visibility:hidden;';
+ document.body.appendChild(probe);
+ try {
+ var c = getComputedStyle(probe);
+ return varNames.map(function (n) {
+ return n + ': ' + c.getPropertyValue(n).trim() + ';';
+ }).join(' ');
+ } finally {
+ document.body.removeChild(probe);
+ }
+ }
+
+ // Prepend a local()-only @font-face block for each weight so that the
+ // sandboxed image-rendering context used during PNG/JPEG/WebP export
+ // can find JetBrains Mono if the user has it installed locally, and
+ // falls through cleanly to the monospace stack otherwise. The usual
+ // Google-Fonts <link> in the host document is unreachable from the
+ // serialized SVG, so url()-sourced faces would just hang.
+ var fontFallback = [400, 500, 600, 700].map(function (w) {
+ return "@font-face { font-family: 'JetBrains Mono'; font-weight: " + w +
+ "; src: local('JetBrains Mono'), local('JetBrainsMono-Regular'); }";
+ }).join('\n');
+
+ var style = document.createElementNS('http://www.w3.org/2000/svg', 'style');
+ var bgRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ bgRect.setAttribute('width', '100%');
+ bgRect.setAttribute('height', '100%');
+
+ if (autoTheme) {
+ // Dual-theme SVG. Dark is the default (so hosts without
+ // prefers-color-scheme still render), light swaps in via media
+ // query, and svg[data-theme="..."] still lets downstream
+ // consumers force a specific theme.
+ var darkVars = resolveVars('dark');
+ var lightVars = resolveVars('light');
+
+ style.textContent =
+ fontFallback + "\n" +
+ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; }\n" +
+ hostStyle + "\n" +
+ ":root, svg { " + darkVars + " }\n" +
+ "@media (prefers-color-scheme: light) { :root, svg { " + lightVars + " } }\n" +
+ "svg[data-theme=\"light\"] { " + lightVars + " }\n" +
+ "svg[data-theme=\"dark\"] { " + darkVars + " }\n" +
+ "rect.c-bg-rect { fill: var(--bg); }\n";
+
+ // Don't lock the serialized SVG to the viewer's current theme.
+ clone.removeAttribute('data-theme');
+ // Background follows the CSS variable, not a fixed color, so it
+ // swaps with the media query.
+ bgRect.setAttribute('class', 'c-bg-rect');
+ } else {
+ // Raster path: lock to the viewer's current theme.
+ var theme = document.documentElement.getAttribute('data-theme') || 'dark';
+ var themeHost = document.querySelector('[data-theme="' + theme + '"]') || document.documentElement;
+ var computed = getComputedStyle(themeHost);
+ var vars = varNames.map(function (n) {
+ return n + ': ' + computed.getPropertyValue(n).trim() + ';';
+ }).join(' ');
+
+ // IMPORTANT: inject the resolved variables AFTER hostStyle,
+ // otherwise hostStyle's ":root, [data-theme=\"dark\"] { ... }" rule
+ // overrides our chosen theme via later-in-cascade equal-specificity.
+ // Keep this order.
+ style.textContent =
+ fontFallback + "\n" +
+ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; }\n" +
+ hostStyle + "\n" +
+ ":root, svg { " + vars + " }\n";
+
+ bgRect.setAttribute('fill', computed.getPropertyValue('--bg').trim() || '#ffffff');
+ }
+
+ clone.insertBefore(style, clone.firstChild);
+ clone.insertBefore(bgRect, style.nextSibling);
+
+ return {
+ svgString: new XMLSerializer().serializeToString(clone),
+ width: vb.width * scale,
+ height: vb.height * scale
+ };
+ }
+
+ function download(blob, filename) {
+ var url = URL.createObjectURL(blob);
+ var a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
+ }
+
+ // Conservative upper bound on total canvas pixels. Older Safari on iOS
+ // silently produces a blank canvas above ~16 Mpx; Chrome / Firefox /
+ // desktop Safari are far higher but start failing on memory-constrained
+ // devices. We pick the largest integer scale in {4,3,2,1} whose target
+ // pixel count fits under this cap.
+ var MAX_CANVAS_PIXELS = 16 * 1024 * 1024;
+
+ function pickSafeScale(vbW, vbH) {
+ for (var s = RASTER_SCALE; s >= 1; s--) {
+ if (vbW * s * vbH * s <= MAX_CANVAS_PIXELS) return s;
+ }
+ return 1;
+ }
+
+ function rasterize(format) {
+ // Serialize at a safe scale (RASTER_SCALE=4 by default, reduced if the
+ // resulting canvas would exceed MAX_CANVAS_PIXELS). The SVG itself is
+ // rasterized at target resolution natively; drawImage draws at natural
+ // size — no upsampling blur.
+ var svg = document.querySelector('.diagram-container svg');
+ var vb = svg.viewBox.baseVal;
+ var scale = pickSafeScale(vb.width, vb.height);
+ var data = serializeSvg(scale);
+ var svgBlob = new Blob([data.svgString], { type: 'image/svg+xml;charset=utf-8' });
+ var svgUrl = URL.createObjectURL(svgBlob);
+
+ return new Promise(function (resolve, reject) {
+ var img = new Image();
+ img.onload = function () {
+ var canvas = document.createElement('canvas');
+ canvas.width = data.width;
+ canvas.height = data.height;
+ var ctx = canvas.getContext('2d');
+ if (format === 'jpeg') {
+ ctx.fillStyle = currentBg();
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ }
+ // Draw at natural size — SVG was already rasterized at target res.
+ ctx.drawImage(img, 0, 0);
+ URL.revokeObjectURL(svgUrl);
+ var mime = format === 'jpeg' ? 'image/jpeg' :
+ format === 'webp' ? 'image/webp' : 'image/png';
+ var quality = format === 'png' ? undefined : 0.95;
+ canvas.toBlob(function (blob) {
+ if (!blob) reject(new Error('toBlob returned null for ' + format));
+ else resolve(blob);
+ }, mime, quality);
+ };
+ img.onerror = function (e) {
+ URL.revokeObjectURL(svgUrl);
+ reject(e);
+ };
+ img.src = svgUrl;
+ });
+ }
+
+ var menu = document.getElementById('export-menu');
+ var btn = document.getElementById('btn-export');
+ var items = function () {
+ return Array.prototype.slice.call(menu.querySelectorAll('button[role="menuitem"]'));
+ };
+
+ // ---- Clipboard support ----------------------------------------------
+ function canCopyImage() {
+ return typeof ClipboardItem !== 'undefined' &&
+ navigator.clipboard &&
+ typeof navigator.clipboard.write === 'function';
+ }
+
+ // ---- Raster format detection ----------------------------------------
+ // canvas.toBlob('image/webp') silently returns a PNG on browsers without
+ // WebP encoding (older Safari), so detect explicitly.
+ function supports(format) {
+ if (format === 'svg' || format === 'png') return true;
+ var mime = format === 'jpeg' ? 'image/jpeg' : 'image/webp';
+ try {
+ var c = document.createElement('canvas');
+ c.width = c.height = 2;
+ return c.toDataURL(mime).indexOf('data:' + mime) === 0;
+ } catch (_) { return false; }
+ }
+
+ // Gray out unsupported items.
+ items().forEach(function (it) {
+ if (it.dataset.format && !supports(it.dataset.format)) {
+ it.disabled = true;
+ it.title = 'Not supported by this browser';
+ it.style.opacity = '0.5';
+ }
+ if (it.dataset.action === 'copy' && !canCopyImage()) {
+ it.disabled = true;
+ it.title = 'Clipboard image write not supported by this browser';
+ it.style.opacity = '0.5';
+ }
+ });
+
+ // ---- Toast ----------------------------------------------------------
+ function toast(msg) {
+ var t = document.createElement('div');
+ t.className = 'archify-toast';
+ t.textContent = msg;
+ document.body.appendChild(t);
+ requestAnimationFrame(function () { t.classList.add('show'); });
+ setTimeout(function () {
+ t.classList.remove('show');
+ setTimeout(function () { t.remove(); }, 300);
+ }, 1500);
+ }
+
+ function open() {
+ menu.classList.add('open');
+ btn.setAttribute('aria-expanded', 'true');
+ var first = items().filter(function (i) { return !i.disabled; })[0];
+ if (first) first.focus();
+ }
+ function close(focusTrigger) {
+ menu.classList.remove('open');
+ btn.setAttribute('aria-expanded', 'false');
+ if (focusTrigger) btn.focus();
+ }
+ function isOpen() { return menu.classList.contains('open'); }
+
+ btn.addEventListener('click', function (e) {
+ e.stopPropagation();
+ if (isOpen()) close(false);
+ else open();
+ });
+ document.addEventListener('click', function (e) {
+ if (!menu.contains(e.target) && e.target !== btn) close(false);
+ });
+
+ // Keyboard navigation inside the menu.
+ // Menu items: Up/Down, Home/End.
+ // Esc closes + returns focus to trigger; Tab closes.
+ menu.addEventListener('keydown', function (e) {
+ if (e.key === 'Escape') { e.preventDefault(); close(true); return; }
+ if (e.key === 'Tab') { close(false); return; }
+
+ var available = items().filter(function (i) { return !i.disabled; });
+ var current = available.indexOf(document.activeElement);
+ switch (e.key) {
+ case 'ArrowDown':
+ e.preventDefault();
+ if (available.length) available[(current + 1 + available.length) % available.length].focus();
+ break;
+ case 'ArrowUp':
+ e.preventDefault();
+ if (available.length) available[(current - 1 + available.length) % available.length].focus();
+ break;
+ case 'Home':
+ e.preventDefault();
+ if (available[0]) available[0].focus();
+ break;
+ case 'End':
+ e.preventDefault();
+ if (available.length) available[available.length - 1].focus();
+ break;
+ }
+ });
+
+ function runExport(format) {
+ var base = diagramFilename();
+ close(false);
+ return (format === 'svg'
+ ? Promise.resolve(serializeSvg(1, { autoTheme: true })).then(function (d) {
+ download(new Blob([d.svgString], { type: 'image/svg+xml;charset=utf-8' }), base + '.svg');
+ })
+ : rasterize(format).then(function (blob) {
+ download(blob, base + '.' + format);
+ })
+ ).catch(function (err) {
+ console.error(err);
+ alert('Export failed: ' + (err && err.message ? err.message : format));
+ });
+ }
+
+ function runCopy() {
+ close(false);
+ if (!canCopyImage()) {
+ alert('Clipboard image write not supported in this browser.');
+ return;
+ }
+ return rasterize('png').then(function (blob) {
+ return navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ }).then(function () {
+ toast('Copied PNG to clipboard');
+ }).catch(function (err) {
+ console.error(err);
+ alert('Copy failed: ' + (err && err.message ? err.message : 'unknown'));
+ });
+ }
+
+ menu.addEventListener('click', function (e) {
+ var copyBtn = e.target.closest('button[data-action="copy"]');
+ if (copyBtn && !copyBtn.disabled) { runCopy(); return; }
+
+ var formatBtn = e.target.closest('button[data-format]');
+ if (formatBtn && !formatBtn.disabled) { runExport(formatBtn.dataset.format); }
+ });
+
+ Archify.exportMenu = { open: open, close: close, isOpen: isOpen, run: runExport };
+
+ // Auto-open on page load for demo/screenshot purposes: ?openExport=1
+ // Wait for fonts (so the menu doesn't flash before typography lands)
+ // and paint before opening. Fallback timeout for browsers without the
+ // Font Loading API.
+ try {
+ if (new URLSearchParams(window.location.search).get('openExport') === '1') {
+ var openWhenReady = function () {
+ requestAnimationFrame(function () { requestAnimationFrame(open); });
+ };
+ if (document.fonts && document.fonts.ready) {
+ document.fonts.ready.then(openWhenReady);
+ } else {
+ setTimeout(openWhenReady, 200);
+ }
+ }
+ } catch (_) {}
+ })();
+
+ /* ============================================================
+ Global keyboard shortcuts
+ T -> toggle theme
+ E -> open export menu
+ Ignored when focus is inside an input/textarea/contenteditable.
+ ============================================================ */
+ document.addEventListener('keydown', function (e) {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ var t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (e.key === 't' || e.key === 'T') {
+ e.preventDefault();
+ Archify.theme.toggle();
+ } else if (e.key === 'e' || e.key === 'E') {
+ e.preventDefault();
+ if (!Archify.exportMenu.isOpen()) Archify.exportMenu.open();
+ }
+ });
+ </script>
+</body>
+</html>
diff --git a/examples/images/archify-dataflow.png b/examples/images/archify-dataflow.png
new file mode 100644
index 00000000..3d1e9eee
Binary files /dev/null and b/examples/images/archify-dataflow.png differ