code-to-diagram
Generate architecture diagrams, ER diagrams, sequence diagrams, flowcharts, and class diagrams from codebases using Mermaid.js. Use when users ask to visualize code structure, draw architecture diagrams, create ER diagrams from database models, generate sequence diagrams from API flows, or produce any diagram from source code. Triggers on: 'draw architecture', 'generate diagram', 'visualize code', 'ER diagram', 'sequence diagram', 'class diagram', 'flowchart from code', 'module dependency graph'.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install moosegoose0701-skill-compose-code-to-diagram
Repository
Skill path: seed_skills/code-to-diagram
Generate architecture diagrams, ER diagrams, sequence diagrams, flowcharts, and class diagrams from codebases using Mermaid.js. Use when users ask to visualize code structure, draw architecture diagrams, create ER diagrams from database models, generate sequence diagrams from API flows, or produce any diagram from source code. Triggers on: 'draw architecture', 'generate diagram', 'visualize code', 'ER diagram', 'sequence diagram', 'class diagram', 'flowchart from code', 'module dependency graph'.
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack, Backend.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: MooseGoose0701.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install code-to-diagram into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/MooseGoose0701/skill-compose before adding code-to-diagram to shared team environments
- Use code-to-diagram for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: code-to-diagram
description: "Generate architecture diagrams, ER diagrams, sequence diagrams, flowcharts, and class diagrams from codebases using Mermaid.js. Use when users ask to visualize code structure, draw architecture diagrams, create ER diagrams from database models, generate sequence diagrams from API flows, or produce any diagram from source code. Triggers on: 'draw architecture', 'generate diagram', 'visualize code', 'ER diagram', 'sequence diagram', 'class diagram', 'flowchart from code', 'module dependency graph'."
---
# Code to Diagram
Generate production-quality diagrams from source code via Mermaid.js, rendered to SVG/PNG with `mmdc`.
## Environment
**Executor required:** This skill needs the `diagram` executor (Chromium + Node.js + mmdc pre-installed).
If `mmdc` is not available, install first:
```bash
npm install -g @mermaid-js/mermaid-cli
```
Puppeteer config for headless environments — create at `/tmp/puppeteer-config.json` if missing:
```json
{"args": ["--no-sandbox", "--disable-setuid-sandbox"]}
```
## Workflow
1. **Analyze** — Read the codebase to understand structure (`glob`, `grep`, `read`)
2. **Plan** — Decide diagram type(s) based on user request and code patterns
3. **Generate** — Write `.mmd` file with Mermaid syntax
4. **Render** — Run `mmdc` to produce SVG and PNG
5. **Verify** — Read the output image and check correctness
## Diagram Type Selection
| User Intent | Diagram Type | Mermaid Keyword |
|-------------|-------------|-----------------|
| System overview, module layout | Architecture | `graph TD` + `subgraph` |
| Database tables, ORM models | ER Diagram | `erDiagram` |
| API flow, request lifecycle | Sequence Diagram | `sequenceDiagram` |
| Inheritance, interfaces | Class Diagram | `classDiagram` |
| Business logic, conditionals | Flowchart | `flowchart TD` |
| Task states, lifecycle | State Diagram | `stateDiagram-v2` |
| Import/dependency tree | Dependency Graph | `graph LR` |
| Timeline, project phases | Gantt Chart | `gantt` |
## Analysis Strategy
Do NOT read every file. Use progressive analysis:
**Step 1 — Directory scan:**
`glob("**/*.py")` or `glob("**/*.ts")` to understand module structure.
**Step 2 — Entry points:**
- Python: `main.py`, `app.py`, `__init__.py`, `pyproject.toml`
- Node.js: `package.json`, `index.ts`, `app.ts`
- Java: `pom.xml`, `Application.java`
**Step 3 — Targeted reads by diagram type:**
- **ER** → ORM models (`models.py`, `schema.prisma`, `*.entity.ts`)
- **Architecture** → Router registrations, dependency injection, config
- **Sequence** → Specific endpoint handler + service call chain
- **Class** → Class definitions via `grep("class ")`
**Step 4 — GitHub repos:**
```bash
git clone --depth 1 <url> /tmp/repo-name
```
Then apply the same progressive scan.
## Rendering
```bash
# SVG (transparent background, good for docs)
mmdc -i diagram.mmd -o diagram.svg -b transparent -p /tmp/puppeteer-config.json
# PNG (white background, 2x scale for sharpness)
mmdc -i diagram.mmd -o diagram.png -b white -s 2 -p /tmp/puppeteer-config.json
```
Always generate both formats. Use `-s 2` for PNG (sharp at any zoom level).
## Mermaid Syntax Reference
For detailed patterns and examples per diagram type, see [references/mermaid-patterns.md](references/mermaid-patterns.md).
Key rules:
- Short IDs, descriptive labels: `DB[("PostgreSQL 16")]`
- Use `subgraph` for logical grouping in architecture diagrams
- Limit ER diagrams to ~10 entities — split by domain if larger
- `participant` aliases in sequence diagrams for short names
- Quote labels with special chars: `A["Node (v1)"]`
- Max ~20 nodes per diagram — split into multiple if larger
## Output Conventions
- Write `.mmd` source + rendered files to workspace
- Descriptive names: `architecture.mmd`, `er-diagram.png`, `api-sequence.svg`
- Multiple diagrams → create `diagrams/` folder with index
## Quality Checklist
- All entities/modules from the code are represented
- Relationships and data flow directions are correct
- Labels readable, not truncated or overlapping
- No Mermaid syntax errors
- Output image visually verified
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### references/mermaid-patterns.md
```markdown
# Mermaid Diagram Patterns
## Table of Contents
- [Architecture Diagram](#architecture-diagram)
- [ER Diagram](#er-diagram)
- [Sequence Diagram](#sequence-diagram)
- [Class Diagram](#class-diagram)
- [Flowchart](#flowchart)
- [State Diagram](#state-diagram)
- [Dependency Graph](#dependency-graph)
- [Gantt Chart](#gantt-chart)
- [Styling Tips](#styling-tips)
## Architecture Diagram
Use `graph TD` (top-down) or `graph LR` (left-right) with `subgraph` for layers.
```mermaid
graph TD
Client["Browser / Mobile"]
subgraph Frontend["Frontend :3000"]
UI["React App"]
Store["Redux Store"]
end
subgraph Backend["API Server :8000"]
API["REST API"]
Auth["Auth Middleware"]
BL["Business Logic"]
end
subgraph Data["Data Layer"]
DB[("PostgreSQL")]
Cache[("Redis")]
S3["S3 / Object Storage"]
end
Client --> UI
UI --> Store
UI --> API
API --> Auth --> BL
BL --> DB
BL --> Cache
BL --> S3
```
**Tips:**
- Use `[("...")]` for database cylinder shape
- Use `["..."]` for rectangles, `(["..."])` for rounded
- Group related components in `subgraph` with descriptive titles
- Add port numbers in subgraph titles for clarity
## ER Diagram
```mermaid
erDiagram
users {
uuid id PK
varchar email UK
varchar name
timestamp created_at
}
orders {
uuid id PK
uuid user_id FK
decimal total
varchar status
timestamp created_at
}
order_items {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal price
}
products {
uuid id PK
varchar name
decimal price
int stock
}
users ||--o{ orders : places
orders ||--|{ order_items : contains
products ||--o{ order_items : "included in"
```
**Relationship symbols:**
- `||--||` one to one
- `||--o{` one to many
- `o{--o{` many to many
- `|` mandatory, `o` optional
**Tips:**
- Include PK/FK/UK annotations
- Use common SQL types: `uuid`, `varchar`, `int`, `decimal`, `timestamp`, `text`, `boolean`, `json`
- Quote relationship labels with spaces: `"included in"`
## Sequence Diagram
```mermaid
sequenceDiagram
participant U as User
participant F as Frontend
participant A as API
participant DB as Database
U->>F: Click "Submit"
F->>A: POST /api/orders
activate A
A->>DB: INSERT INTO orders
DB-->>A: order_id
A->>A: Validate & process
A-->>F: 201 Created {id}
deactivate A
F-->>U: Show confirmation
alt Payment fails
A-->>F: 400 Bad Request
F-->>U: Show error
end
```
**Arrow types:**
- `->>` solid line with arrowhead (sync call)
- `-->>` dashed line with arrowhead (response)
- `--)` async message
**Tips:**
- Use `participant X as "Short Name"` for readability
- `activate`/`deactivate` to show lifeline
- `alt`/`else` for conditional branches
- `loop` for repeated operations
- `Note over A,B: text` for annotations
## Class Diagram
```mermaid
classDiagram
class Animal {
+String name
+int age
+makeSound() String
}
class Dog {
+String breed
+fetch() void
+makeSound() String
}
class Cat {
+bool indoor
+purr() void
+makeSound() String
}
class Shelter {
-List~Animal~ animals
+addAnimal(Animal a) void
+getCount() int
}
Animal <|-- Dog : extends
Animal <|-- Cat : extends
Shelter o-- Animal : houses
```
**Visibility:**
- `+` public, `-` private, `#` protected, `~` package
**Relationships:**
- `<|--` inheritance
- `*--` composition
- `o--` aggregation
- `-->` association
- `..>` dependency
## Flowchart
```mermaid
flowchart TD
Start([Start]) --> Input[/Read user input/]
Input --> Validate{Valid?}
Validate -->|Yes| Process[Process data]
Validate -->|No| Error[Show error]
Error --> Input
Process --> Save[(Save to DB)]
Save --> Notify[/Send notification/]
Notify --> End([End])
```
**Node shapes:**
- `[text]` rectangle
- `(text)` rounded
- `{text}` diamond (decision)
- `[(text)]` cylinder (database)
- `([text])` stadium (start/end)
- `[/text/]` parallelogram (I/O)
## State Diagram
```mermaid
stateDiagram-v2
[*] --> Draft
Draft --> Pending : submit
Pending --> Approved : approve
Pending --> Rejected : reject
Rejected --> Draft : revise
Approved --> Published : publish
Published --> Archived : archive
Archived --> [*]
state Pending {
[*] --> UnderReview
UnderReview --> NeedsChanges : request changes
NeedsChanges --> UnderReview : resubmit
UnderReview --> Ready : approve
}
```
## Dependency Graph
Use `graph LR` for module dependency visualization:
```mermaid
graph LR
main --> api
main --> config
api --> auth
api --> handlers
handlers --> services
services --> db
services --> cache
auth --> db
config --> db
```
## Gantt Chart
```mermaid
gantt
title Project Timeline
dateFormat YYYY-MM-DD
section Design
Requirements :done, req, 2024-01-01, 2024-01-14
UI Design :done, ui, after req, 14d
section Development
Backend API :active, api, after ui, 21d
Frontend :fe, after ui, 28d
section Testing
Integration Test :test, after api, 14d
UAT :uat, after fe, 7d
```
## Styling Tips
### Theme
mmdc supports themes via config:
```json
{
"theme": "default"
}
```
Available: `default`, `dark`, `forest`, `neutral`. Pass via `-c config.json` to mmdc.
### Large Diagrams
When a diagram exceeds ~20 nodes:
1. Split into multiple diagrams by domain/layer
2. Create an overview diagram linking to detail diagrams
3. Use `graph LR` (horizontal) for wide dependency trees
4. Use `graph TD` (vertical) for deep hierarchies
### Text in Labels
- Quote strings with special characters: `A["API (v2)"]`
- Use `<br/>` for line breaks in labels: `A["Line 1<br/>Line 2"]`
- Avoid `--` in labels (conflicts with Mermaid syntax)
```