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,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
}
```