feat(lib-core): biblioteca atomica @pulse-libs/core v1.0.0-beta.1

Esta commit conteudo a estrutura atomica completa:

- types:     Result<T,E>, AsyncState<T>, Paginated<T>, SortConfig<T>
- utils:     date, str, num, cn, debounce, throttle, storage, arr, obj
- validators: Zod schemas — email, password, uuid, url, phone, CPF/CNPJ, sanitizedStr, safeParse
- hooks:     useToggle, useAsync, useDebounce, useLocalStorage, useMedia, useInterval, useOnClickOutside, useClipboard, useFetch
- components: Button, Input, Alert, Card, Spinner (atomic design pattern)
- build:     tsup v8 ESM+CJS + DTS + sourcemaps — 0 erros
- tests:     57 testes 100% usuarios
- docker:    multi-stage Dockerfile (node 20-alpine)
- config:    vitest, tsup, tsconfig strict, .npmignore

Filosofia atomica:/utils ← /types ← /validators ← /hooks ← /components
Build: npm run build | Test: npm test | Publish: npm publish

🤖 Generated with Pulse (openclaw + nova-self-improver)
This commit is contained in:
pulse-agent
2026-05-19 21:43:03 -03:00
parent ae39e45460
commit bbdb68a6de
7030 changed files with 2040595 additions and 0 deletions
@@ -0,0 +1,8 @@
{
"version": 1,
"registry": "https://clawhub.ai",
"slug": "d2-diagram-creator",
"installedVersion": "1.0.0",
"installedAt": 1779235744784,
"fingerprint": "9063d4b6592b57d32454ec4a1a4a5ab501152f99c3ae3156816f235db21ab962"
}
+49
View File
@@ -0,0 +1,49 @@
# D2 Diagram Creator
D2 Diagram Creator is a skill that can directly convert natural language descriptions into high-quality D2 diagram code and image files. After installation, you only need to describe the desired diagram structure in text, and it will automatically generate it for you.
Whether it's a flowchart in academic writing, a model architecture diagram in scientific illustration, or a module relationship diagram when understanding a new open-source project, you no longer need to draw it manually step by step.
[中文版本(Chinese version)](README_zh.md)
![](https://oss.furina.org.cn:443/images/github/20260402160052535.svg)
## Quick Use
### Dependency Installation
The recommended and simplest installation method is to use D2's installation script, which will detect your operating system and architecture and use the best installation method.
```bash
curl -fsSL https://d2lang.com/install.sh | sh -s --
# TALA is a powerful diagram layout engine specifically designed for software architecture diagrams. It requires separate installation.
curl -fsSL https://d2lang.com/install.sh | sh -s -- --tala
```
Please refer to the official D2 documentation for details:
+ https://github.com/terrastruct/d2/blob/master/docs/INSTALL.md
+ https://github.com/terrastruct/tala
After successful installation, use the following command to check
```bash
d2 --version
d2 layout tala
```
### Import Claude Code
```bash
git clone https://github.com/HuTa0kj/d2-diagram-creator ~/.claude/skills/d2-diagram-creator
```
## Example Prompts
+ Please use D2 to draw the system flowchart for the current project.
+ Please use D2 SKILL to draw a TCP three-way handshake sequence diagram.
+ Please use D2 to draw the database ER diagram for the current project, in dark mode and a thatched cottage style, and export it as a PNG.
+49
View File
@@ -0,0 +1,49 @@
# D2 Diagram Creator
D2 Diagram Creator 是一个能将自然语言描述直接转换为高质量 D2 图表代码及图片文件的 SKILL。安装后,你只需用文字描述想要的图表结构,它就能帮你自动生成。
无论是论文写作中的方法流程图、科研绘图里的模型架构示意,还是理解一个新的开源项目时的模块关系图,你都不需要再一点一点手动绘制。
![](https://oss.furina.org.cn:443/images/github/20260402160052535.svg)
## 快速使用
### 依赖安装
推荐且最简单的安装方法是使用 D2 的安装脚本,该脚本将检测您使用的操作系统和架构,并使用最佳安装方法
```bash
curl -fsSL https://d2lang.com/install.sh | sh -s --
# TALA 是一款专为软件架构图设计的图表布局引擎,非常强大,该引擎需要单独安装
curl -fsSL https://d2lang.com/install.sh | sh -s -- --tala
```
具体请参考 D2 的官方文档:
+ https://github.com/terrastruct/d2/blob/master/docs/INSTALL.md
+ https://github.com/terrastruct/tala
安装成功后使用下面的命令检查
```bash
d2 --version
d2 layout tala
```
### 导入 Claude Code
```bash
git clone https://github.com/HuTa0kj/d2-diagram-creator ~/.claude/skills/d2-diagram-creator
```
## 示例提示词
+ 帮我使用 D2 绘制当前项目的系统流程图
+ 使用 D2 SKILL 帮我画一个 TCP 三次握手的时序图
+ 使用 D2 绘制当前项目的数据库ER图,深色模式、草屋风格,导出PNG
+212
View File
@@ -0,0 +1,212 @@
---
name: d2-diagram-creator
description: "Generate D2 diagram code supporting flowcharts, system architecture diagrams, organizational charts, service topology diagrams, state machine diagrams, swimlane diagrams, sequence diagrams, SQL table relationship diagrams, and grid diagrams. Use when users need to: (1) create or generate flowcharts and process diagrams, (2) design system architecture or infrastructure diagrams, (3) build state machine or sequence diagrams, (4) visualize relationships between components, entities or services, (5) create swimlane diagrams for cross-functional processes, (6) design database table structures and ER diagrams, (7) create grid layouts or dashboard designs, or any diagram that can be represented with nodes, connections, and containers in D2 syntax."
license: MIT
metadata:
author: Fur1na
version: "1.0.0"
---
# D2 Diagram Creator
Three-agent pipeline for high-quality diagram generation:
```
AskUserQuestion → Agent 1 (Analyzer) → Agent 2 (Generator) → Agent 3 (Validator)
```
Each agent is a `general-purpose` subagent with its own focused instructions. You (the main agent) orchestrate the pipeline — ask the user questions, then spawn agents in sequence, passing outputs forward.
---
## Step 1: Ask Requirements
Use AskUserQuestion to ask all questions at once. Do not split into multiple rounds, do not skip any.
### First round (always required)
```json
{
"questions": [
{
"question": "How detailed should the diagram be?",
"header": "Detail Level",
"options": [
{ "label": "Core Flow", "description": "5-8 nodes" },
{ "label": "Moderate", "description": "10-15 nodes" },
{ "label": "Full Detail", "description": "Include all details and exception branches" }
]
},
{
"question": "What is the layout direction of the diagram?",
"header": "Layout Direction",
"options": [
{ "label": "Horizontal", "description": "direction: right, left to right" },
{ "label": "Vertical", "description": "direction: down, top to bottom" }
]
},
{
"question": "What format to export as?",
"header": "Export Format",
"options": [
{ "label": "D2 Code Only", "description": "No image export" },
{ "label": "SVG", "description": "Vector graphics (recommended)" },
{ "label": "PNG", "description": "Bitmap" },
{ "label": "Preview", "description": "ASCII text" }
]
}
]
}
```
### Second round (only when SVG/PNG is selected)
```json
{
"questions": [
{
"question": "Which theme to use?",
"header": "Theme",
"options": [
{ "label": "Light Theme", "description": "--theme 0, white background (default)" },
{ "label": "Dark Theme", "description": "--theme 200, dark background" }
]
},
{
"question": "Enable hand-drawn sketch style?",
"header": "Sketch",
"options": [
{ "label": "No", "description": "Normal style (default)" },
{ "label": "Yes", "description": "--sketch, hand-drawn effect" }
]
},
{
"question": "Choose layout engine?",
"header": "Layout Engine",
"options": [
{ "label": "dagre", "description": "Default, fast and efficient" },
{ "label": "elk", "description": "Complex diagrams, 100+ nodes" },
{ "label": "tala", "description": "Most powerful, SVG only, requires installation" }
]
}
]
}
```
Only provide 2 theme options (Light/Dark). Do not add colorful, terminal, or other themes.
---
## Step 2: Spawn Analyzer Agent
Use the Agent tool to spawn the requirements analyzer. This agent deeply analyzes the user's request and produces a structured JSON document.
- **subagent_type**: `general-purpose`
- **description**: `Analyze diagram requirements`
The prompt should be:
```
Read the file at <skill-base-path>/agents/analyzer.md for your instructions.
Analyze this diagram request:
User request: <user's original description>
User preferences:
- Detail level: <answer>
- Layout direction: <answer>
- Export format: <answer>
- Theme: <answer, or "not selected">
- Sketch: <answer, or "not selected">
- Layout engine: <answer, or "not selected">
Return the structured requirements JSON.
```
Save the returned JSON — you will pass it to the generator agent.
---
## Step 3: Spawn Generator Agent
Use the Agent tool to spawn the D2 code generator.
- **subagent_type**: `general-purpose`
- **description**: `Generate D2 diagram code`
The prompt should be:
```
Read the file at <skill-base-path>/agents/generator.md for your instructions.
Generate D2 code based on these requirements:
<the requirements JSON from Step 2>
Read the diagram type guide at:
<skill-base-path>/references/diagram-types/<diagram_type>.md
Save the D2 code to a .d2 file (use a descriptive filename).
Return the file path.
```
Save the returned file path — you will pass it to the validator agent.
---
## Step 4: Spawn Validator Agent
Use the Agent tool to spawn the validator.
- **subagent_type**: `general-purpose`
- **description**: `Validate and export diagram`
The prompt should be:
```
Read the file at <skill-base-path>/agents/validator.md for your instructions.
Your skill base directory is: <skill-base-path>
The watermark removal script is at: <skill-base-path>/scripts/remove_watermark.py
Validate and export:
D2 file: <path from Step 3>
Requirements: <the requirements JSON>
Export preferences:
- Format: <export_format>
- Theme: <theme or "default">
- Sketch: <sketch or false>
- Layout engine: <engine or "dagre">
Fix any issues and export the final diagram.
```
Report the validator's summary to the user.
---
## Diagram Types Reference
| Type | Use Case |
|------|----------|
| **Flowchart** | Business processes, decision trees, algorithm flows |
| **System Architecture** | Component relationships, infrastructure, service interactions |
| **Organizational Chart** | Hierarchical structures, reporting relationships |
| **Service Topology** | Cloud architecture, network topology |
| **State Machine** | State transitions, workflow states, lifecycles |
| **Swimlane Diagram** | Cross-functional processes, multi-role workflows |
| **Sequence Diagram** | Time-based interactions, protocol flows |
| **SQL Table Diagram** | Database schemas, ER diagrams |
| **Grid Diagram** | Dashboard layouts, UI prototypes |
---
## Prohibitions
1. Do not skip requirement questions — always ask first
2. Do not add visual styles unless the user explicitly requests them
3. Do not add a diagram title unless the user explicitly requests one
4. Do not skip any of the three agents — the pipeline must run to completion
+6
View File
@@ -0,0 +1,6 @@
{
"ownerId": "kn7cm8jm5xnvtaj28v6b4y9t7s842d5t",
"slug": "d2-diagram-creator",
"version": "1.0.0",
"publishedAt": 1775119154697
}
@@ -0,0 +1,81 @@
# Requirements Analyzer Agent
You are a specialized requirements analyzer for D2 diagram generation. Your job is to deeply understand the user's request and produce a structured requirements document that the generator agent can use directly.
## What you receive
- The user's original description of what diagram they want
- Their answers to preference questions (detail level, layout direction, export format, theme, sketch, layout engine)
## What to do
1. Read the diagram type reference files to understand what structures each type supports. Start with the most likely type based on the user's description:
- `references/diagram-types/flowchart.md` — processes, decision trees
- `references/diagram-types/architecture.md` — system components, infrastructure
- `references/diagram-types/org-chart.md` — hierarchies, reporting
- `references/diagram-types/topology.md` — cloud, network
- `references/diagram-types/state-machine.md` — states, transitions
- `references/diagram-types/swimlane.md` — cross-functional processes
- `references/diagram-types/sequence.md` — time-based interactions
- `references/diagram-types/sql-table.md` — database schemas, ER
- `references/diagram-types/grid.md` — dashboards, layouts
2. Identify the diagram type that best matches the user's request
3. Extract all entities (nodes, components, tables, states, actors, etc.) the user mentioned
4. Extract all relationships and connections between entities
5. Identify any natural groupings or containers
6. Produce a structured requirements document
## Output format
Return ONLY a JSON object with this structure (no markdown wrapping):
```json
{
"diagram_type": "flowchart|architecture|org-chart|topology|state-machine|swimlane|sequence|sql-table|grid",
"title": null,
"entities": [
{
"id": "short_english_id",
"label": "User's Original Label",
"shape": "rectangle",
"container": "parent_id or null"
}
],
"connections": [
{
"from": "entity_id or container.entity_id",
"to": "entity_id or container.entity_id",
"label": "connection label or null",
"arrow": "->"
}
],
"containers": [
{
"id": "short_english_id",
"label": "Display Label"
}
],
"preferences": {
"detail_level": "core|moderate|full",
"layout_direction": "right|down",
"export_format": "d2|svg|png|preview",
"theme": 0,
"sketch": false,
"layout_engine": "dagre"
}
}
```
## Guidelines
- Entity IDs must be short, descriptive, in English, and free of special characters (no hyphens, dots, colons). Use underscores if needed.
- Labels should preserve the user's original wording and language.
- Use quotes around any ID that contains special characters.
- The `arrow` field supports: `->`, `<-`, `<->`, `--`.
- If a connection crosses container boundaries, use dot-separated paths in from/to (e.g., `"frontend.ui"``"api.gateway"`).
- Don't invent entities the user didn't mention.
- Don't omit entities the user explicitly described.
- Think about logical grouping — related entities belong in the same container.
- If the user's request doesn't fit neatly into one diagram type, pick the closest one.
- `title` should be null unless the user explicitly asked for a diagram title.
- Shape should be a valid D2 shape. Use `rectangle` as default when unsure.
@@ -0,0 +1,90 @@
# D2 Diagram Generator Agent
You are a specialized D2 diagram code generator. Your job is to produce clean, correct D2 code from a structured requirements document.
## What you receive
- A structured JSON requirements document (from the analyzer agent)
- The path to the relevant diagram type reference file
## What to do
1. Read the diagram type guide specified by the `diagram_type` field in the requirements:
- `references/diagram-types/<diagram_type>.md`
2. If you need detailed syntax info, read `references/syntax.md`
3. Generate D2 code that faithfully implements every entity and connection in the requirements
4. Write the D2 code to the specified output file
5. Return the file path
## Design principles
These principles matter because D2 auto-layouts everything — bad code structure means bad diagrams.
1. **Simplicity first** — show core content, avoid excessive nesting
2. **Minimal styling** — only use semantic attributes (shape, label, direction). No colors, shadows, or icons unless the user explicitly asked
3. **Automatic layout** — use `direction` to control flow, never try manual positioning
4. **Semantic naming** — IDs should clearly describe what the node represents
5. **Reasonable grouping** — use containers for logically related entities, but don't over-nest
6. **No title by default** — unless `title` in the requirements is non-null
### Allowed attributes
```d2
Node: { shape: circle } # Shape
Container: { label: "Label" } # Label
Connection: { label: "Note" } # Connection label
direction: right # Layout direction
```
### Forbidden attributes (unless user explicitly requested)
```d2
style.fill: "#color"
style.stroke: "#color"
style.opacity: 0.5
style.shadow: true
icon: https://...
```
## Critical syntax rules
### Container node references — this is the #1 source of bugs
When connecting nodes that live inside containers, you MUST use the full dot-separated path. Otherwise D2 creates duplicate orphan nodes and the diagram falls apart.
Wrong:
```d2
Frontend Layer: {
User Interface: { label: "Web UI" }
}
API Layer: {
Gateway: { label: "API Gateway" }
}
User Interface -> Gateway
```
Correct:
```d2
Frontend Layer.User Interface -> API Layer.Gateway
```
### Attribute separation — no semicolons, no commas
Wrong: `Node: { shape: circle; style.fill: red }`
Correct:
```d2
Node: {
shape: circle
style.fill: red
}
```
### Special characters in IDs
IDs containing `-`, `:`, `.` must be quoted:
Wrong: `my-node: { shape: circle }`
Correct: `"my-node": { shape: circle }`
## Output
Write the complete D2 code to the specified output file path. Then return the file path.
@@ -0,0 +1,81 @@
# D2 Output Validator Agent
You are a specialized D2 code validator and exporter. Your job is to catch mistakes, fix them, and produce the final output file.
## What you receive
- Path to the generated `.d2` file
- The structured requirements JSON (to verify completeness)
- Export preferences (format, theme, sketch, layout engine)
## What to do — in this order
### Step 1: Read the D2 file and do a manual code review
Check every one of these:
- **Container node references**: Cross-container connections use full dot-separated paths (e.g., `Frontend.UI -> Backend.API`). This is the most common bug — if you see a bare node name that also appears inside a container, it's wrong.
- **No orphan nodes**: Every node participates in at least one connection. Orphans mean something got disconnected.
- **No semicolons or commas**: Attributes are separated by newlines only.
- **Special characters**: IDs with `-`, `:`, `.` are wrapped in quotes.
- **Bracket matching**: Every `{` has a matching `}`.
- **Arrow syntax**: Connections use `->`, `<-`, `<->`, or `--` (nothing else).
If you find any issues, fix them directly in the file.
### Step 2: Verify requirements completeness
Compare the D2 code against the requirements JSON:
- Every entity in `entities` is present in the D2 code
- Every connection in `connections` is present
- Container/grouping structure matches what was specified
- Layout direction is set correctly (`direction: right` or `direction: down`)
If entities or connections are missing, add them. If extras were added that weren't in the requirements, remove them unless they're clearly implied by the diagram type's structure (e.g., sequence diagrams need lifecycle bars).
### Step 3: Syntax validation
```bash
d2 validate <file_path>
```
If it fails, read the error message, fix the code, and re-validate. Repeat until it passes.
### Step 4: Export (if not D2-only)
If `export_format` is `d2`, skip this step — the .d2 file is the final output.
Otherwise, build and run the export command:
```bash
d2 [options] input.d2 output.<format>
```
Options based on preferences:
- Theme: `--theme 0` (light) or `--theme 200` (dark)
- Sketch: `--sketch` (if enabled)
- Engine: `-l dagre` | `-l elk` | `-l tala`
#### Export format mapping
| Format | Command |
|--------|---------|
| SVG | `d2 [opts] input.d2 output.svg` |
| PNG | `d2 [opts] input.d2 output.png` |
| Preview | `d2 input.d2 output.txt` |
#### Tala engine special handling
- Tala only supports SVG. If the user wanted PNG, fall back to dagre/elk and note this in your output.
- Check installation: `d2 layout tala`
- If not installed, tell the user: "Tala engine is not installed. See https://github.com/terrastruct/tala"
- **After SVG export with tala, you MUST remove the watermark.** The script is at `<skill-base-path>/scripts/remove_watermark.py`. Run: `python <skill-base-path>/scripts/remove_watermark.py output.svg`. This step is not optional — tala always adds a watermark and the user does not want it.
### Step 5: Return summary
Report back with:
1. Issues found during code review (and what you fixed)
2. Whether `d2 validate` passed (and any fixes applied)
3. The export command you ran (if any)
4. Path to the final output file(s)
@@ -0,0 +1,65 @@
```
d2 0.7.1
Usage:
d2 [--watch=false] [--theme=0] file.d2 [file.svg | file.png | file.pdf | file.pptx | file.gif | file.txt]
d2 layout [name]
d2 fmt file.d2 ...
d2 play [--theme=0] [--sketch] file.d2
d2 validate file.d2
d2 compiles and renders file.d2 to file.svg | file.png | file.pdf | file.pptx | file.gif | file.txt
It defaults to file.svg if an output path is not provided.
Use - to have d2 read from stdin or write to stdout.
See man d2 for more detailed docs.
Flags:
-w, --watch $D2_WATCH watch for changes to input and live reload. Use $HOST and $PORT to specify the listening address.
(default localhost:0, which will open on a randomly available local port). (default false)
-h, --host string $HOST host listening address when used with watch (default "localhost")
-p, --port string $PORT port listening address when used with watch (default "0")
-b, --bundle $D2_BUNDLE when outputting SVG, bundle all assets and layers into the output file (default true)
--force-appendix $D2_FORCE_APPENDIX an appendix for tooltips and links is added to PNG exports since they are not interactive. --force-appendix adds an appendix to SVG exports as well (default false)
-d, --debug $DEBUG print debug logs. (default false)
--img-cache $IMG_CACHE in watch mode, images used in icons are cached for subsequent compilations. This should be disabled if images might change. (default true)
-l, --layout string $D2_LAYOUT the layout engine used (default "dagre")
-t, --theme int $D2_THEME the diagram theme ID (default 0)
--dark-theme int $D2_DARK_THEME the theme to use when the viewer's browser is in dark mode. When left unset -theme is used for both light and dark mode. Be aware that explicit styles set in D2 code will still be applied and this may produce unexpected results. We plan on resolving this by making style maps in D2 light/dark mode specific. See https://github.com/terrastruct/d2/issues/831. (default -1)
--pad int $D2_PAD pixels padded around the rendered diagram (default 100)
--animate-interval int $D2_ANIMATE_INTERVAL if given, multiple boards are packaged as 1 SVG which transitions through each board at the interval (in milliseconds). Can only be used with SVG exports. (default 0)
--timeout int $D2_TIMEOUT the maximum number of seconds that D2 runs for before timing out and exiting. When rendering a large diagram, it is recommended to increase this value (default 120)
-v, --version get the version (default false)
-s, --sketch $D2_SKETCH render the diagram to look like it was sketched by hand (default false)
--stdout-format string output format when writing to stdout (svg, png, ascii, txt, pdf, pptx, gif). Usage: d2 input.d2 --stdout-format png - > output.png (default "")
--browser string $BROWSER browser executable that watch opens. Setting to 0 opens no browser. (default "")
-c, --center $D2_CENTER center the SVG in the containing viewbox, such as your browser screen (default false)
--scale float $SCALE scale the output. E.g., 0.5 to halve the default size. Default -1 means that SVG's will fit to screen and all others will use their default render size. Setting to 1 turns off SVG fitting to screen. (default -1)
--target string target board to render. Pass an empty string to target root board. If target ends with '*', it will be rendered with all of its scenarios, steps, and layers. Otherwise, only the target board will be rendered. E.g. --target='' to render root board only or --target='layers.x.*' to render layer 'x' with all of its children. (default "*")
--font-regular string $D2_FONT_REGULAR path to .ttf file to use for the regular font. If none provided, Source Sans Pro Regular is used. (default "")
--font-italic string $D2_FONT_ITALIC path to .ttf file to use for the italic font. If none provided, Source Sans Pro Regular-Italic is used. (default "")
--font-bold string $D2_FONT_BOLD path to .ttf file to use for the bold font. If none provided, Source Sans Pro Bold is used. (default "")
--font-semibold string $D2_FONT_SEMIBOLD path to .ttf file to use for the semibold font. If none provided, Source Sans Pro Semibold is used. (default "")
--font-mono string $D2_FONT_MONO path to .ttf file to use for the monospace font. If none provided, Source Code Pro Regular is used. (default "")
--font-mono-bold string $D2_FONT_MONO_BOLD path to .ttf file to use for the monospace bold font. If none provided, Source Code Pro Bold is used. (default "")
--font-mono-italic string $D2_FONT_MONO_ITALIC path to .ttf file to use for the monospace italic font. If none provided, Source Code Pro Italic is used. (default "")
--font-mono-semibold string $D2_FONT_MONO_SEMIBOLD path to .ttf file to use for the monospace semibold font. If none provided, Source Code Pro Semibold is used. (default "")
--check $D2_CHECK check that the specified files are formatted correctly. (default false)
--no-xml-tag $D2_NO_XML_TAG omit XML tag (<?xml ...?>) from output SVG files. Useful when generating SVGs for direct HTML embedding (default false)
--salt string Add a salt value to ensure the output uses unique IDs. This is useful when generating multiple identical diagrams to be included in the same HTML doc, so that duplicate IDs do not cause invalid HTML. The salt value is a string that will be appended to IDs in the output. (default "")
--omit-version $OMIT_VERSION omit D2 version from generated image (default false)
--ascii-mode string $D2_ASCII_MODE ASCII rendering mode for text outputs. Options: 'standard' (basic ASCII chars) or 'extended' (Unicode chars) (default "extended")
Subcommands:
d2 layout - Lists available layout engine options with short help
d2 layout [name] - Display long help for a particular layout engine, including its configuration options
d2 themes - Lists available themes
d2 fmt file.d2 ... - Format passed files
d2 play file.d2 - Opens the file in playground, an online web viewer (https://play.d2lang.com)
d2 validate file.d2 - Validates file.d2
```
@@ -0,0 +1,182 @@
# System Architecture
## Use Cases
- Software system component relationships
- Infrastructure planning
- Service interaction design
- Technical architecture documentation
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Database | `shape: cylinder` | Data storage |
| External System | `shape: cloud` | Third-party services, external APIs |
| Service Component | Default rectangle | Microservices, application services |
## Basic Example
```d2
direction: right
Frontend App
Backend Service: { shape: rectangle }
Database: { shape: cylinder }
Frontend App -> Backend Service: HTTP
Backend Service -> Database: SQL Query
```
## Cloud Architecture Example
```d2
direction: right
Load Balancer
Web Server: { shape: rectangle }
Database: { shape: cylinder }
Load Balancer -> Web Server: "Distribute traffic"
Web Server -> Database: "Query data"
```
## Microservices Architecture
```d2
direction: right
Frontend Layer: {
Web App
Mobile App
Admin Console
}
Gateway Layer: {
API Gateway: { shape: rectangle }
Load Balancer: { shape: rectangle }
}
Service Layer: {
User Service: { shape: rectangle }
Order Service: { shape: rectangle }
Payment Service: { shape: rectangle }
}
Data Layer: {
User Database: { shape: cylinder }
Order Database: { shape: cylinder }
Cache: { shape: cylinder }
}
External Services: {
Third-party Payment: { shape: cloud }
Logistics Service: { shape: cloud }
}
Frontend Layer -> Gateway Layer: HTTPS
Gateway Layer -> Service Layer: gRPC
User Service -> User Database: SQL
Order Service -> Order Database: SQL
Service Layer -> Cache: Redis
Payment Service -> Third-party Payment: API
Order Service -> Logistics Service: API
```
## Multi-tier Application Architecture
```d2
direction: down
Presentation Layer: {
Web Frontend
Mobile Client
Desktop App
}
Application Layer: {
API Gateway
Business Services: {
direction: right
Auth Service
Data Service
Report Service
}
}
Middleware Layer: {
Message Queue: { shape: queue }
Cache Layer: { shape: cylinder }
}
Data Layer: {
Primary Database: { shape: cylinder }
Replica Database: { shape: cylinder }
Data Warehouse: { shape: cylinder }
}
Presentation Layer -> API Gateway: HTTPS
API Gateway -> Business Services: REST
Business Services -> Cache Layer: Redis
Business Services -> Message Queue: AMQP
Business Services -> Primary Database: SQL
Primary Database -> Replica Database: Replication
```
## Design Principles
1. **Clear Layering** - Use containers to distinguish different tiers
2. **Label Protocols** - Annotate communication protocols on connection lines
3. **Proper Layout** - Use `direction` to control flow direction
4. **Complete Connections** - Every node must have at least one connection, avoid orphan nodes
## Common Mistakes
### ❌ Wrong: Orphan Nodes (Unconnected Modules)
```d2
# Problem: Logging System, Report Generator not connected to other components
Service Layer: {
API Service
Auth Service
}
Utility Layer: {
Logging System # Orphan!
Report Generator # Orphan!
}
API Service -> Auth Service
```
### ✅ Correct: Ensure All Nodes Are Connected
```d2
Service Layer: {
API Service
Auth Service
}
Utility Layer: {
Logging System
Report Generator
}
API Service -> Auth Service
API Service -> Logging System: "Log records"
Auth Service -> Logging System: "Log records"
API Service -> Report Generator: "Generate report"
```
### ✅ Better: Remove Non-core Dependencies, Keep It Simple
If a component (like logging) relates to all modules, consider omitting it and only keeping core data flows in the diagram:
```d2
Service Layer: {
API Service
Auth Service
}
Database: { shape: cylinder }
API Service -> Auth Service
API Service -> Database
Auth Service -> Database
# Auxiliary components like logging omitted to keep diagram clean
```
@@ -0,0 +1,97 @@
# Flowchart
## Use Cases
- Business process flows
- Decision trees and branching logic
- Algorithm flow descriptions
- Operation step instructions
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Start/End | `shape: circle` | Beginning and end of process |
| Decision Node | `shape: diamond` | Conditional branches, decision points |
| Process Step | Default rectangle | Operations, processes, actions |
| Input/Output | `shape: parallelogram` | Data input and output |
## Basic Example
```d2
direction: down
Start: { shape: circle }
Step One
Condition: { shape: diamond }
End: { shape: circle }
Start -> Step One -> Condition
Condition -> Step Two -> End
Condition -> End: "End directly"
```
## Example with Input/Output
```d2
direction: down
Start: { shape: circle }
Input Data: { shape: parallelogram }
Process Data
Validate Result: { shape: diamond }
Output Report: { shape: parallelogram }
End: { shape: circle }
Start -> Input Data -> Process Data -> Validate Result
Validate Result -> Output Report: "Success"
Validate Result -> Process Data: "Failed, reprocess"
Output Report -> End
```
## Complex Decision Branching
```d2
direction: down
Start: { shape: circle }
Enter Credentials
Validate Credentials: { shape: diamond }
Credentials Valid: { shape: diamond }
Check Account Status: { shape: diamond }
Generate Token
End: { shape: circle }
Error Handling
Lock Handling
Start -> Enter Credentials
Enter Credentials -> Validate Credentials
Validate Credentials -> Error Handling: "Invalid"
Validate Credentials -> Check Account Status: "Valid"
Check Account Status -> Lock Handling: "Locked"
Check Account Status -> Generate Token: "Normal"
Generate Token -> End
Lock Handling -> End: "Notify user"
Error Handling -> End: "Return error"
```
## Design Principles
1. **Simplicity First** - Show core processes, avoid over-detailing
2. **Use Decision Nodes Wisely** - Only use diamond at key branching points
3. **Clear Labeling** - Label branch conditions on connection lines
4. **Avoid Displaying Loops** - Use text descriptions for loops instead of drawing cycles
## Common Mistakes
❌ Over-detailing
```
Start → Validate Input Format → Format Correct? → Query User → User Exists? →
Validate Password → Password Correct? → Create Session → Generate Token → Redirect to Home
```
✅ Core Process
```
Start → Enter Credentials → Query User → User Exists? → Validate Password → Password Correct? →
Create Session → Login Success
```
@@ -0,0 +1,308 @@
# Grid Diagram
## Use Cases
- Dashboard layout design
- UI prototype design
- Object matrix display
- Heatmap-style visualization
- Structured component arrangement
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Row Grid | `grid-rows: N` | Specify N rows |
| Column Grid | `grid-columns: N` | Specify N columns |
| Vertical Gap | `vertical-gap: N` | Row spacing |
| Horizontal Gap | `horizontal-gap: N` | Column spacing |
| Unified Gap | `grid-gap: N` | Set both row and column spacing |
| Cell Width | `width: N` | Control cell width |
| Cell Height | `height: N` | Control cell height |
## Basic Examples
### Rows Only
```d2
grid-rows: 3
Executive
Legislative
Judicial
```
### Columns Only
```d2
grid-columns: 3
Executive
Legislative
Judicial
```
### Both Rows and Columns
```d2
grid-rows: 2
grid-columns: 2
Executive
Legislative
Judicial
Fourth Item
```
## Controlling Cell Size
Use `width` and `height` to create specific structures:
```d2
grid-rows: 2
Executive
Legislative
Judicial
The American Government.width: 400
```
When only one of rows or columns is defined, objects will expand automatically:
```d2
grid-rows: 3
Executive
Legislative
Judicial
The American Government.width: 400
Voters
Non-voters
```
## Grid Spacing
| Property | Description |
|----------|-------------|
| `grid-gap` | Set both vertical and horizontal spacing |
| `vertical-gap` | Row spacing (can override grid-gap) |
| `horizontal-gap` | Column spacing (can override grid-gap) |
### Tight Grid (Heatmap Style)
```d2
grid-gap: 0
grid-columns: 3
Cell1
Cell2
Cell3
Cell4
Cell5
Cell6
```
## Nested Grids
Grid diagrams can be nested within other grids to create complex layouts:
```d2
grid-gap: 0
grid-columns: 1
header: "Header"
body: {
grid-gap: 0
grid-columns: 2
content: "Main Content"
sidebar: "Sidebar"
}
footer: "Footer"
```
## Complete Example: Dashboard Layout
```d2
grid-rows: 5
style.fill: black
classes: {
white square: {
label: ""
width: 120
style: {
fill: white
stroke: cornflowerblue
stroke-width: 10
}
}
block: {
style: {
text-transform: uppercase
font-color: white
fill: darkcyan
stroke: black
}
}
}
flow1.class: white square
flow2.class: white square
flow3.class: white square
flow4.class: white square
flow5.class: white square
flow6.class: white square
flow7.class: white square
flow8.class: white square
flow9.class: white square
dagger engine: {
width: 800
class: block
style: {
fill: beige
stroke: darkcyan
font-color: blue
stroke-width: 8
}
}
any docker compatible runtime: {
width: 800
class: block
style: {
fill: lightcyan
stroke: darkcyan
font-color: black
stroke-width: 8
}
}
any ci: {
class: block
style: {
fill: gold
stroke: maroon
font-color: maroon
stroke-width: 8
}
}
windows.class: block
linux.class: block
macos.class: block
kubernetes.class: block
```
## Complete Example: User Access Architecture
```d2
direction: right
users -- via -- teleport
teleport -> jita: "all connections audited and logged"
teleport -> infra
teleport -> identity provider
teleport <- identity provider
users: {
grid-columns: 1
Engineers: {
shape: circle
}
Machines: {
shape: circle
}
}
via: {
grid-columns: 1
https: "HTTPS://"
kubectl: "> kubectl"
tsh: "> tsh"
api: "> api"
db clients: "DB Clients"
}
teleport: Teleport {
grid-rows: 2
inp: |md
# Identity Native Proxy
| {
width: 300
}
Audit Log
Cert Authority
}
jita: "Just-in-time Access via" {
grid-rows: 1
Slack
Mattermost
Jira
Pagerduty
Email
}
infra: Infrastructure {
grid-rows: 2
ssh
Kubernetes
My SQL
MongoDB
PSQL
Windows
}
identity provider: Indentity Provider
```
## Design Principles
1. **Row/Column Priority** - Determine the primary direction first (rows or columns)
2. **Appropriate Spacing** - Use `grid-gap` to control visual rhythm
3. **Nested Composition** - Achieve complex layouts through nesting
4. **Consistent Styling** - Use `class` to unify styles for similar cells
## Common Patterns
### Equal Grid
```d2
grid-columns: 3
grid-gap: 20
Module A
Module B
Module C
```
### Unequal Layout
```d2
grid-columns: 3
grid-gap: 10
Sidebar.width: 200
Main Content.width: 400
Right Panel.width: 150
```
### Compact Heatmap
```d2
grid-gap: 0
grid-columns: 4
1.style.fill: "#ff0000"
2.style.fill: "#ff4444"
3.style.fill: "#ff8888"
4.style.fill: "#ffcccc"
5.style.fill: "#00ff00"
6.style.fill: "#44ff44"
7.style.fill: "#88ff88"
8.style.fill: "#ccffcc"
```
@@ -0,0 +1,124 @@
# Organization Chart
## Use Cases
- Company organizational structure
- Team composition display
- Reporting relationships
- Department structure diagrams
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Person Node | `shape: person` | Employees, roles |
| Department Container | `{}` nested | Organizational units |
| Hierarchical Relationship | `->` connection | Reporting, management relationships |
## Basic Example
```d2
direction: down
CEO: { shape: person }
Tech Department: {
CTO: { shape: person }
Frontend Team: {
Frontend Lead: { shape: person }
Frontend Engineer: { shape: person }
}
Backend Team: {
Backend Lead: { shape: person }
Backend Engineer: { shape: person }
}
}
Marketing Department: {
Marketing Director: { shape: person }
Marketing Specialist: { shape: person }
}
CEO -> CTO
CEO -> Marketing Director
CTO -> Frontend Team.Frontend Lead
CTO -> Backend Team.Backend Lead
```
## Complete Company Organization Structure
```d2
direction: down
Board: {
Chairman
}
Executive Team: {
CEO
CFO
CTO
}
Tech Department: {
Frontend Team: {
direction: right
Frontend Lead
Frontend Engineer1: { shape: person }
Frontend Engineer2: { shape: person }
}
Backend Team: {
direction: right
Backend Lead
Backend Engineer1: { shape: person }
Backend Engineer2: { shape: person }
}
DevOps Team: {
direction: right
DevOps Lead
DevOps Engineer: { shape: person }
}
}
Business Department: {
Product Manager: { shape: person }
Operations Team: {
direction: right
Operations Lead
Operations Specialist: { shape: person }
}
}
Finance Department: {
Finance Lead
Accountant: { shape: person }
Cashier: { shape: person }
}
Board -> CEO: "Appoint"
CEO -> CFO
CEO -> CTO
CTO -> Tech Department
CEO -> Business Department
CFO -> Finance Department
```
## Design Principles
1. **Vertical Layout Preferred** - `direction: down` works best
2. **Container Nesting** - Use containers to represent department hierarchy
3. **Person Shape** - Use `shape: person` to identify person nodes
4. **Clear Role Labels** - Include position information in node names
## Team Internal Layout
Members within the same team can use horizontal layout:
```d2
Frontend Team: {
direction: right
Frontend Lead
Frontend Engineer1: { shape: person }
Frontend Engineer2: { shape: person }
}
```
@@ -0,0 +1,166 @@
# Sequence Diagram
## Use Cases
- Time-based interaction flows
- API call sequences
- Protocol flows
- Message passing
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Sequence Diagram Shape | `shape: sequence_diagram` | Top-level declaration |
| Participant | Node declaration | Interacting roles/systems |
| Message | `->` or `<-` | Call direction |
| Phase Grouping | Container `{}` | Logical grouping |
## Basic Example
```d2
shape: sequence_diagram
Client
Server
Database
Client -> Server: Request data
Server -> Database: Query
Database <- Server: Return result
Client <- Server: Response data
```
## User Login Sequence
```d2
shape: sequence_diagram
User Browser
Backend Service
Auth Service
Database
Cache Service
Login Request: {
User Browser -> Backend Service: POST /login {username, password}
Backend Service -> Cache Service: Check login limit
Cache Service <- Backend Service: Return limit status
Backend Service -> Auth Service: Verify credentials
Auth Service -> Database: Query user info
Database <- Auth Service: Return user data
Auth Service <- Backend Service: Verification result
Backend Service -> Cache Service: Store session
Cache Service <- Backend Service: Store success
User Browser <- Backend Service: Return JWT Token
}
Subsequent Request: {
User Browser -> Backend Service: GET /api/resource {Authorization: Bearer}
Backend Service -> Cache Service: Validate session
Cache Service <- Backend Service: Session valid
User Browser <- Backend Service: Return resource data
}
```
## Payment Flow Sequence
```d2
shape: sequence_diagram
User
Merchant System
Payment Platform
Bank System
Notification Service
Create Order: {
User -> Merchant System: Place order
Merchant System -> Payment Platform: Create payment order
Merchant System <- Payment Platform: Return payment link
User <- Merchant System: Redirect to payment page
}
User Payment: {
User -> Payment Platform: Enter payment password
Payment Platform -> Bank System: Deduct request
Bank System <- Payment Platform: Deduction success
User <- Payment Platform: Payment success page
}
Async Notification: {
Payment Platform -> Notification Service: Payment result notification
Notification Service -> Merchant System: Webhook callback
Merchant System <- Notification Service: Acknowledge receipt
Notification Service <- Merchant System: Return 200 OK
}
```
## API Call Sequence
```d2
shape: sequence_diagram
Client
API Gateway
User Service
Order Service
Message Queue
Client -> API Gateway: POST /orders
API Gateway -> User Service: Validate user
User Service <- API Gateway: User valid
API Gateway -> Order Service: Create order
Order Service -> Message Queue: Send order event
Message Queue <- Order Service: Acknowledge receipt
Order Service <- API Gateway: Order created successfully
Client <- API Gateway: Return order ID
```
## Styled Sequence Diagram
```d2
shape: sequence_diagram
Client
Server
Request Phase: {
Client -> Server: Request data
Server -> Server: Process data {
style.stroke: blue
}
Client <- Server: Return result {
style.stroke: green
}
}
```
## Design Principles
1. **Declare Participants at Top** - List all roles before interactions
2. **Phase Grouping** - Use containers to group related messages
3. **Consistent Direction** - `->` for requests, `<-` for responses
4. **Clear Labels** - Message labels describe specific operations
## Message Direction Explanation
- `A -> B: message` - A sends message to B (request)
- `A <- B: message` - A receives message from B (response)
- Typically use `->` for requests and `<-` for responses
## Animation Effects
Add animation to key messages:
```d2
shape: sequence_diagram
Client
Server
Client -> Server: Normal request
Server -> Client: Important response {
style.animated: true
}
```
@@ -0,0 +1,315 @@
# SQL Table Diagram
## Use Cases
- Database table structure design
- ER Diagrams (Entity-Relationship)
- Data model documentation
- Table relationship visualization
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Table Shape | `shape: sql_table` | Define SQL table |
| Field Definition | `field_name: type` | Table columns |
| Primary Key | `constraint: primary_key` | Primary key field |
| Foreign Key | `constraint: foreign_key` | Foreign key field |
| Unique Constraint | `constraint: unique` | Unique field |
| Table Connection | `TableA.field -> TableB.field` | Foreign key relationship |
## Basic Example
```d2
direction: right
users: {
shape: sql_table
id: int {constraint: primary_key}
username: varchar(50)
email: varchar(100) {constraint: unique}
created_at: timestamp
}
```
## Table with Constraints
### Single Constraint
```d2
products: {
shape: sql_table
id: int {constraint: primary_key}
name: varchar(100)
price: decimal(10,2)
sku: varchar(20) {constraint: unique}
created_at: timestamp
}
```
### Multiple Constraints
Use an array to specify multiple constraint conditions:
```d2
items: {
shape: sql_table
id: int {constraint: [primary_key; unique]}
code: varchar(20) {constraint: [unique; not_null]}
name: varchar(100)
}
```
## Table Relationships (Foreign Keys)
### One-to-Many Relationship
```d2
direction: right
users: {
shape: sql_table
id: int {constraint: primary_key}
username: varchar(50)
email: varchar(100)
}
orders: {
shape: sql_table
id: int {constraint: primary_key}
user_id: int {constraint: foreign_key}
total: decimal(10,2)
status: varchar(20)
}
orders.user_id -> users.id
```
### Multi-table Relationships
```d2
direction: right
users: {
shape: sql_table
id: int {constraint: primary_key}
username: varchar(50)
email: varchar(100)
}
posts: {
shape: sql_table
id: int {constraint: primary_key}
user_id: int {constraint: foreign_key}
title: varchar(200)
content: text
created_at: timestamp
}
comments: {
shape: sql_table
id: int {constraint: primary_key}
post_id: int {constraint: foreign_key}
user_id: int {constraint: foreign_key}
content: text
created_at: timestamp
}
posts.user_id -> users.id
comments.post_id -> posts.id
comments.user_id -> users.id
```
## Nested in Containers
Organize tables into logical groups:
```d2
direction: right
cloud: {
disks: {
shape: sql_table
id: int {constraint: primary_key}
name: varchar(100)
size_gb: int
}
blocks: {
shape: sql_table
id: int {constraint: primary_key}
disk_id: int {constraint: foreign_key}
data: blob
}
blocks.disk_id -> disks.id
}
AWS S3 -> cloud.disks
```
## Complete E-commerce Data Model
```d2
direction: right
User Module: {
users: {
shape: sql_table
id: int {constraint: primary_key}
username: varchar(50)
email: varchar(100) {constraint: unique}
password_hash: varchar(255)
created_at: timestamp
}
addresses: {
shape: sql_table
id: int {constraint: primary_key}
user_id: int {constraint: foreign_key}
province: varchar(50)
city: varchar(50)
address: varchar(200)
}
addresses.user_id -> users.id
}
Product Module: {
categories: {
shape: sql_table
id: int {constraint: primary_key}
name: varchar(100)
parent_id: int {constraint: foreign_key}
}
products: {
shape: sql_table
id: int {constraint: primary_key}
category_id: int {constraint: foreign_key}
name: varchar(200)
price: decimal(10,2)
stock: int
}
categories.parent_id -> categories.id
products.category_id -> categories.id
}
Order Module: {
orders: {
shape: sql_table
id: int {constraint: primary_key}
user_id: int {constraint: foreign_key}
address_id: int {constraint: foreign_key}
total: decimal(10,2)
status: varchar(20)
created_at: timestamp
}
order_items: {
shape: sql_table
id: int {constraint: primary_key}
order_id: int {constraint: foreign_key}
product_id: int {constraint: foreign_key}
quantity: int
price: decimal(10,2)
}
orders.user_id -> User Module.users.id
orders.address_id -> User Module.addresses.id
order_items.order_id -> orders.id
order_items.product_id -> Product Module.products.id
}
```
## Reserved Keyword Handling
If a field name is a reserved keyword, wrap it in quotes:
```d2
my_table: {
shape: sql_table
id: int {constraint: primary_key}
"label": string
"order": int
"group": varchar(50)
}
```
## Supported Data Types
Common SQL data types:
| Type | Description |
|------|-------------|
| `int` / `integer` | Integer |
| `varchar(n)` | Variable-length string |
| `text` | Long text |
| `decimal(m,n)` | Exact decimal |
| `float` | Floating point |
| `boolean` / `bool` | Boolean |
| `date` | Date |
| `timestamp` | Timestamp |
| `json` / `jsonb` | JSON data |
| `blob` | Binary data |
| `uuid` | UUID identifier |
## Constraint Types
| Constraint | Description |
|------------|-------------|
| `primary_key` | Primary key |
| `foreign_key` | Foreign key |
| `unique` | Unique value |
| `not_null` | Not null |
## Design Principles
1. **Direction Layout** - Use `direction: right` for clearer relationship lines
2. **Logical Grouping** - Organize related tables into containers
3. **Label Relationships** - Add relationship descriptions on connection lines
4. **Naming Conventions** - Use consistent naming (snake_case recommended)
## Common Patterns
### Self-referencing Relationship
```d2
categories: {
shape: sql_table
id: int {constraint: primary_key}
name: varchar(100)
parent_id: int {constraint: foreign_key}
}
categories.parent_id -> categories.id: "Parent category"
```
### Many-to-Many Junction Table
```d2
direction: right
students: {
shape: sql_table
id: int {constraint: primary_key}
name: varchar(100)
}
courses: {
shape: sql_table
id: int {constraint: primary_key}
name: varchar(100)
}
enrollments: {
shape: sql_table
student_id: int {constraint: foreign_key}
course_id: int {constraint: foreign_key}
enrolled_at: timestamp
}
enrollments.student_id -> students.id
enrollments.course_id -> courses.id
```
@@ -0,0 +1,135 @@
# State Machine
## Use Cases
- Object state transitions
- Workflow state management
- Lifecycle diagrams
- Business process states
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| State Node | `shape: circle` or rectangle | Represents state |
| Transition Arrow | `->` with label | State change |
| Initial State | Style distinction | Starting state |
| Final State | Style distinction | Ending state |
## Basic Example
```d2
direction: right
Pending -> Processing: "Start processing"
Processing -> Completed: "Success"
Processing -> Cancelled: "Failed"
```
## Order State Machine
```d2
direction: right
Awaiting Payment: {
style.stroke-width: 3
}
Paid
Processing
Shipped
Completed: {
style.stroke-width: 3
}
Cancelled: {
style.stroke-width: 3
}
Refunding
Refunded: {
style.stroke-width: 3
}
Awaiting Payment -> Paid: "Payment success"
Awaiting Payment -> Cancelled: "Timeout/Cancel"
Paid -> Processing: "Confirm order"
Processing -> Shipped: "Warehouse ships"
Shipped -> Completed: "Confirm receipt"
Paid -> Cancelled: "User cancel"
Processing -> Cancelled: "Cancel order"
Shipped -> Refunding: "Request refund"
Refunding -> Refunded: "Refund complete"
Completed -> Refunding: "After-sale request"
```
## User Session State Machine
```d2
direction: right
Not Logged In: {
style.stroke-width: 3
}
Logging In
Logged In
Session Expired
Locked
Logged Out
Not Logged In -> Logging In: "Submit credentials"
Logging In -> Logged In: "Auth success"
Logging In -> Locked: "Multiple failures"
Logging In -> Not Logged In: "Auth failed"
Logged In -> Session Expired: "Timeout"
Logged In -> Logged Out: "Active logout"
Session Expired -> Not Logged In: "Re-login"
Logged Out -> Not Logged In
Locked -> Not Logged In: "Admin unlock"
```
## Styled State Machine
Use colors to distinguish state types:
```d2
direction: right
# Initial state - Green
Initial State: {
shape: circle
style.fill: "#c8e6c9"
style.stroke: "#2e7d32"
}
# Intermediate state - Blue
Processing: {
style.fill: "#bbdefb"
}
# Final state - Red
Final State: {
shape: circle
style.fill: "#ffcdd2"
style.stroke: "#c62828"
}
Initial State -> Processing: "Event A"
Processing -> Final State: "Event B"
```
## Bidirectional State Toggle
```d2
direction: right
On <-> Off: "Toggle"
# Or use two one-way arrows
# On -> Off: "Turn off"
# Off -> On: "Turn on"
```
## Design Principles
1. **Label Transitions Clearly** - Every transition arrow should have a trigger condition
2. **Distinguish State Types** - Use styles to differentiate initial/final states
3. **Avoid Over-complexity** - Consider splitting if more than 10 states
4. **Horizontal Layout** - `direction: right` usually works better
@@ -0,0 +1,158 @@
# Swimlane Diagram
## Use Cases
- Cross-functional processes
- Multi-role workflows
- Inter-departmental collaboration
- Approval workflows
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Swimlane Container | `{}` | One container per role/department |
| Cross-lane Connection | `RoleA.Node -> RoleB.Node` | Cross-role interaction |
| Decision Node | `shape: diamond` | Branch decisions |
## Basic Example
```d2
direction: right
User: {
Submit Request
View Result
}
System: {
Validate Request
Process Data
}
User.Submit Request -> System.Validate Request
System.Validate Request -> System.Process Data
System.Process Data -> User.View Result
```
## E-commerce Order Processing Swimlane
```d2
direction: right
Customer: {
Place Order
Pay for Order
Confirm Receipt
Request Refund
}
Order System: {
Validate Order
Create Payment
Update Inventory
Generate Shipment
Process Refund
}
Warehouse: {
Pick Items
Pack Items
Ship Order
}
Logistics: {
Transport
Deliver
}
Finance System: {
Confirm Payment
Process Refund
}
Customer.Place Order -> Order System.Validate Order
Order System.Validate Order -> Order System.Create Payment
Order System.Create Payment -> Customer.Pay for Order
Customer.Pay for Order -> Finance System.Confirm Payment
Finance System.Confirm Payment -> Order System.Update Inventory
Order System.Update Inventory -> Order System.Generate Shipment
Order System.Generate Shipment -> Warehouse.Pick Items
Warehouse.Pick Items -> Warehouse.Pack Items
Warehouse.Pack Items -> Warehouse.Ship Order
Warehouse.Ship Order -> Logistics.Transport
Logistics.Transport -> Logistics.Deliver
Logistics.Deliver -> Customer.Confirm Receipt
Customer.Request Refund -> Order System.Process Refund
Order System.Process Refund -> Finance System.Process Refund
```
## Approval Workflow Swimlane
```d2
direction: right
Applicant: {
Submit Application
Provide Additional Info
Receive Result
}
Department Manager: {
Initial Review
Approve: { shape: diamond }
Reject
}
Finance Department: {
Verify Amount
Confirm Budget: { shape: diamond }
}
CEO: {
Final Review
Final Approval: { shape: diamond }
}
Applicant.Submit Application -> Department Manager.Initial Review
Department Manager.Initial Review -> Department Manager.Approve
Department Manager.Approve -> Department Manager.Reject: "Not approved"
Department Manager.Approve -> Finance Department.Verify Amount: "Approved"
Department Manager.Reject -> Applicant.Provide Additional Info
Applicant.Provide Additional Info -> Department Manager.Initial Review
Finance Department.Verify Amount -> Finance Department.Confirm Budget
Finance Department.Confirm Budget -> CEO.Final Review: "Over budget"
Finance Department.Confirm Budget -> Applicant.Receive Result: "Within budget"
CEO.Final Review -> CEO.Final Approval
CEO.Final Approval -> Applicant.Receive Result: "Approved"
CEO.Final Approval -> Applicant.Receive Result: "Rejected"
```
## Design Principles
1. **Clear Roles** - Each swimlane represents a role or department
2. **Horizontal Layout** - `direction: right` suits most swimlane diagrams
3. **Cross-lane Connections** - Use full paths `Role.Node`
4. **Concise Naming** - Keep swimlane names short and clear
## Vertical Swimlanes
Vertical layout may be more suitable in some scenarios:
```d2
direction: down
Frontend: {
Page Render
User Interaction
}
Backend: {
API Processing
Data Query
}
Frontend.Page Render -> Backend.API Processing
Backend.API Processing -> Backend.Data Query
Backend.Data Query -> Frontend.User Interaction
```
@@ -0,0 +1,167 @@
# Service Topology
## Use Cases
- Cloud infrastructure planning
- Kubernetes cluster architecture
- Network topology design
- Resource dependency relationships
## Key Patterns
| Element | Syntax | Purpose |
|---------|--------|---------|
| Container Grouping | `{}` | Group by environment or type |
| Dashed Connection | `style.stroke-dash: 3` | Optional or indirect relationships |
| Database | `shape: cylinder` | Data storage |
| Cloud Service | `shape: cloud` | External services |
## Kubernetes Cluster Example
```d2
direction: right
Ingress Controller: {
Nginx: { shape: rectangle }
}
Service Mesh: {
API Service: {
direction: down
Pod1
Pod2
Pod3
}
User Service: {
direction: down
Pod1
Pod2
}
Order Service: {
direction: down
Pod1
Pod2
}
}
Data Storage: {
Redis Cluster: { shape: cylinder }
PostgreSQL: { shape: cylinder }
}
Monitoring: {
Prometheus
Grafana
}
External Traffic -> Ingress Controller.Nginx
Ingress Controller.Nginx -> Service Mesh.API Service
Service Mesh.API Service -> Service Mesh.User Service
Service Mesh.API Service -> Service Mesh.Order Service
Service Mesh.User Service -> Data Storage.Redis Cluster
Service Mesh.Order Service -> Data Storage.PostgreSQL
Service Mesh -> Prometheus: Metrics
Prometheus -> Grafana
```
## Cloud Infrastructure Example
```d2
direction: right
VPC: {
Public Subnet: {
Load Balancer: { shape: rectangle }
NAT Gateway: { shape: rectangle }
}
Private Subnet: {
Web Servers: {
direction: down
Instance1
Instance2
}
App Servers: {
direction: down
Instance1
Instance2
Instance3
}
}
Data Subnet: {
Primary DB: { shape: cylinder }
Replica DB: { shape: cylinder }
}
}
External Services: {
CDN: { shape: cloud }
Monitoring Service: { shape: cloud }
}
User Traffic -> CDN
CDN -> VPC.Public Subnet.Load Balancer
Load Balancer -> Private Subnet.Web Servers
Web Servers -> Private Subnet.App Servers
App Servers -> Data Subnet.Primary DB
Primary DB -> Data Subnet.Replica DB: Replication
Private Subnet.App Servers -> NAT Gateway
NAT Gateway -> External Services.Monitoring Service
```
## Network Topology Example
```d2
direction: right
Internet: { shape: cloud }
DMZ Zone: {
Firewall
Web Server
}
Internal Zone: {
App Server
DB Server: { shape: cylinder }
}
Management Zone: {
Monitoring Server
Log Server
}
Internet -> DMZ Zone.Firewall
DMZ Zone.Firewall -> DMZ Zone.Web Server
DMZ Zone.Web Server -> Internal Zone.App Server
Internal Zone.App Server -> Internal Zone.DB Server
DMZ Zone.Web Server -> Management Zone.Monitoring Server: Logs
Internal Zone.App Server -> Management Zone.Log Server
```
## Design Principles
1. **Group by Environment** - Use containers to distinguish production/test/development environments
2. **Label Dependencies** - Annotate protocols and purposes on connection lines
3. **Dashed for Optional** - Use dashed lines for non-essential connections
4. **Use Icons Wisely** - Use icons for cloud services to enhance recognition
## Class Style Reuse
Unify styles for the same type of resources:
```d2
class: server
server: {
style.fill: "#e3f2fd"
style.stroke: "#1976d2"
}
Web Server: {
class: server
}
App Server: {
class: server
}
```
@@ -0,0 +1,532 @@
# D2 Syntax Reference
## Node Shapes
### Basic Shapes
- `rectangle` - Rectangle (default)
- `square` - Square
- `circle` - Circle
- `oval` - Oval
- `ellipse` - Ellipse (alias for oval)
### Flowchart Shapes
- `diamond` - Diamond (conditional)
- `parallelogram` - Parallelogram (input/output)
- `trapezoid` - Trapezoid
- `rounded_rectangle` - Rounded rectangle
- `stroke_rectangle` - Stroked rectangle
### Data and Storage
- `cylinder` - Cylinder (database)
- `queue` - Queue (cylinder variant)
- `disk` - Disk
- `storage` - Storage
### System and Network
- `cloud` - Cloud (external system/service)
- `hexagon` - Hexagon
- `octagon` - Octagon
- `callout` - Callout box
- `note` - Note
### People and Organization
- `person` - Person
- `queue` - Queue (waiting line)
### Documents and Pages
- `page` - Document page
- `document` - Document
### Special Shapes
- `image` - Image node
- `sql_table` - SQL table
- `class` - Class diagram (UML)
**Note**: `shape: label` is not supported in some versions of D2. It's recommended to use the node's `label` property or the direct label syntax:
```
node: "Label text" # Recommended approach
```
## Connection Types
### Basic Connections
```
A -> B # Directed arrow
A <- B # Reverse arrow
A <-> B # Bidirectional arrow
A -- B # Undirected line
A - B # Undirected line (shorthand)
```
### Connection Labels
```
A -> B: Label text # Single-line label
# Note: Multi-line labels use block syntax or |md syntax
```
### Arrowhead Styles
Customize arrows with `source-arrowhead` and `target-arrowhead`:
```
source-arrowhead: triangle # Triangle (default)
source-arrowhead: arrow # Arrow
source-arrowhead: diamond # Diamond
source-arrowhead: circle # Circle
source-arrowhead: box # Box
source-arrowhead: cross # Cross
source-arrowhead: none # No arrowhead
```
### Connection Line Styles
```
A -> B {
style.stroke-dash: 3 # Dashed line
style.stroke-width: 2 # Line width
style.stroke: red # Line color
style.animated: true # Animation effect
}
```
## Style Properties
### Colors
```
style.fill: "#ff0000" # Fill color (hexadecimal)
style.fill: red # Fill color (color name)
style.stroke: blue # Border color
style.opacity: 0.5 # Opacity (0-1)
```
### Borders
```
style.stroke-width: 2 # Border width
style.stroke-dash: 5 # Dash pattern (number is spacing)
style.border-radius: 8 # Border radius
```
### Fonts
```
style.font-size: 14 # Font size
style.font-color: "#333" # Font color
# Note: style.font-weight and style.font-style are not supported in some versions
```
**Important**: Multiple style properties **must be separated by newlines, do not use semicolons or commas**.
Correct example:
```
node: {
style.fill: red
style.stroke: blue
style.stroke-width: 2
}
```
Incorrect example:
```
node: { style.fill: red; style.stroke: blue }
```
### Fill Patterns
```
style.fill-pattern: dots # Dots pattern
style.fill-pattern: lines # Lines pattern
style.fill-pattern: crosshatch # Crosshatch pattern
```
### Multiplicity
```
style.multiple: true # Display multiple nodes (e.g., multiple databases)
```
### Animation
```
style.animated: true # Enable animation
```
## Container Syntax
### Basic Container
```
container_name: {
nodeA
nodeB
}
```
### Nested Containers
```
outer_container: {
inner_container: {
nodeC
}
nodeA
nodeB
}
```
### Container Styles
```
container: {
style.fill: "#f0f0f0"
style.stroke: "#333"
nodeA
nodeB
}
```
### Container Layout
```
container: {
direction: right # Layout direction within container
grid-columns: 3 # Number of grid columns
nodeA
nodeB
nodeC
}
```
### Referencing Parent Containers
```
outer: {
middle: {
node -> _ # _ references outer container
}
parent_node
}
middle.node -> outer.parent_node # Full path reference
```
## Classes and Style Reuse
### Defining Classes
```
class: class_name
class_name: {
style.fill: yellow
style.stroke: orange
}
```
### Applying Classes
```
nodeA: {
class: class_name
}
```
### Multiple Classes
```
nodeA: {
class: [class1, class2] # Applied in order
}
```
### Class Inheritance
Object properties override class properties:
```
class_name: {
style.fill: yellow
}
node: {
class: class_name
style.fill: red # Overrides class fill property
}
```
## Layout Control
### Global Layout Direction
```
direction: right # Left to right (default)
direction: down # Top to bottom
direction: left # Right to left
direction: up # Bottom to top
```
### Layout Engine
Set in `vars`:
```
vars: {
d2-config: {
layout-engine: dagre # dagre (default)
layout-engine: elk # ELK layout
layout-engine: tala # TALA layout
}
}
```
### Themes
```
vars: {
d2-config: {
theme-id: 0 # Default theme
theme-id: 1 # Neutral theme
theme-id: 3 # Terrastruct theme
theme-id: 100 # Custom theme number
}
}
```
### Sketch Mode
```
vars: {
d2-config: {
sketch: true # Enable hand-drawn style
}
}
```
## Variables
### Defining Variables
```
vars: {
variable_name: value
colors: {
primary: "#007bff"
secondary: "#6c757d"
}
}
```
### Using Variables
```
nodeA: {
style.fill: ${vars.colors.primary}
}
title: ${vars.variable_name}
```
## Advanced Features
### Tooltips
```
node: { tooltip: "Hover tooltip text" }
```
### Links
```
node: {
link: "https://example.com"
tooltip: "Click to visit"
}
```
### SQL Tables
```
table: {
shape: sql_table
column1: type1
column2: type2
column3: type3
}
```
### Multi-line Labels
Use block syntax to support multi-line text:
```
node: |md
# Markdown Heading
Supports multi-line text
Supports **bold** and *italic*
|
```
Or use simple line breaks:
```
node: |md
First line
Second line
Third line
|
```
### Grid Layout
```
container: {
grid-columns: 3 # 3-column grid
nodeA
nodeB
nodeC
nodeD
nodeE
nodeF
}
```
### Wildcard Styles
```
*.style.fill: blue # All nodes
*.*.style.fill: green # All nested nodes
(nodeA -- *)[*].style.stroke: red # All connections of nodeA
```
### Title
```
title: "Diagram Title" # Simple title
title: |md # Markdown title
# Heading 1
Supports **Markdown** format
| {near: top-center} # Title position
```
### Position Control (Use Sparingly)
```
node: {
position: absolute
x: 100
y: 200
}
```
Note: Prefer automatic layout; only use manual positioning when necessary.
## Comments
### Line Comments
```
# This is a single-line comment
nodeA -- nodeB # End-of-line comment
```
### Multi-line Comments
Use multiple line comments for multi-line comments:
```
# This is the first line of comment
# This is the second line of comment
# This is the third line of comment
nodeA -- nodeB
```
## Special Syntax
### Implicit Connections
Multiple nodes on the same line are automatically connected:
```
A B C D # Equivalent to A -> B -> C -> D
```
### Connection Grouping
```
(A B C) -> (D E F) # A, B, C each connect to D, E, F
```
### Conditional Styles
```
node: {
style.fill?: red # Conditional style (if not set)
}
```
### Label Shorthand
```
node: Label text # Node name is "node", label is "Label text"
```
## Common Patterns
### Database Connection
```
app <-> database: {
style.stroke-dash: 3
source-arrowhead: none
target-arrowhead: triangle
}
```
### Conditional Branch
```
decision: {
shape: diamond
style.fill: lightyellow
}
```
### Loop Process
```
stepA -> stepB -> stepC
stepC -> stepA: "Loop"
```
### Parallel Processing
```
parallel_tasks: {
direction: right
task1
task2
task3
}
start -> parallel_tasks
parallel_tasks -> end
```
### Error Handling
```
main_process -> error_handler: "Exception"
error_handler: {
style.fill: "#ffcccc"
style.stroke: red
}
```
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
def main():
if len(sys.argv) < 2:
print("Usage: python remove_watermark.py <svg_file_path>")
sys.exit(1)
svg_path = Path(sys.argv[1])
if not svg_path.exists():
print(f"Error: File not found - {svg_path}")
sys.exit(1)
content = svg_path.read_text(encoding='utf-8')
new_content = content.replace('UNLICENSED COPY', '')
if content == new_content:
print("'UNLICENSED COPY' text not found")
return
svg_path.write_text(new_content, encoding='utf-8')
print(f"Watermark removed: {svg_path}")
if __name__ == '__main__':
main()