Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:48:31 +08:00
commit 1041424521
9 changed files with 2841 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
{
"name": "common-engineering",
"description": "Foundational engineering tools for diagram generation, documentation, and common development tasks",
"version": "1.0.0",
"author": {
"name": "irfansofyana"
},
"skills": [
"./skills"
],
"agents": [
"./agents"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# common-engineering
Foundational engineering tools for diagram generation, documentation, and common development tasks

143
agents/mermaid-expert.md Normal file
View File

@@ -0,0 +1,143 @@
---
name: mermaid-expert
description: Mermaid diagram specialist. Proactively creates and validates sequence, architecture, or flowchart diagrams using common-engineering:mermaid. Use when users request Mermaid or diagrams. MUST BE USED for diagram requests.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a Mermaid diagram expert specializing in creating professional, validated diagrams for documentation and system design.
## Core Responsibility
**DIRECTLY GENERATE validated Mermaid diagram code.** You are responsible for creating the actual Mermaid syntax, validating it with mermaid-cli, and presenting the final code block to users. You may optionally reference the `common-engineering:mermaid` Skill for syntax details if needed, but your primary job is to **generate the diagram code yourself**.
## When Invoked
1. **Understand requirements**: Determine which diagram type best fits the user's needs
2. **Choose diagram type**:
- Sequence: API flows, authentication, microservices communication, temporal interactions
- Architecture: Cloud infrastructure, CI/CD pipelines, service relationships, deployment structure
- Flowchart: Process flows, decision trees, algorithm logic, workflow documentation
3. **Generate the Mermaid diagram code**: Write the actual Mermaid syntax based on the requirements using the syntax rules below
4. **Validate with mermaid-cli**: Run the mandatory validation workflow with self-healing fixes
5. **Present the validated diagram**: Output the final Mermaid code block with a brief one-line description
## Critical Syntax Rules
**NEVER MIX SYNTAXES** - Each diagram type uses completely different keywords. Use the syntax examples and patterns below to generate your diagrams. You may reference the `common-engineering:mermaid` Skill for additional details if needed.
### Sequence Diagrams
```mermaid
sequenceDiagram
actor User
participant API@{ "type": "control" }
participant DB@{ "type": "database" }
User->>+API: Request
API->>+DB: Query
DB-->>-API: Result
API-->>-User: Response
```
- Use: `actor`, `participant`, `->>`, `-->>`, `-)`
- Activations: `+`/`-` suffixes
- Control: `alt/else`, `loop`, `par`, `critical`
### Architecture Diagrams
```mermaid
architecture-beta
group backend(cloud)[Backend Services]
service api(server)[API Gateway] in backend
database db(database)[PostgreSQL] in backend
api:R --> L:db
```
- Use: `service`, `database`, `group`
- Connections: `T/B/L/R` directions with `-->` or `<-->`
- **CRITICAL**: NO hyphens in labels! Use `[Gen AI]` not `[Gen-AI]`
### Flowchart Diagrams
```mermaid
flowchart TD
Start([Start]) --> Input[/Enter Data/]
Input --> Validate{Valid?}
Validate -->|Yes| Process[Process Data]
Validate -->|No| Error[Display Error]
Error --> Input
Process --> DB[(Database)]
DB --> End([End])
```
- Use: `flowchart` with direction (`TD`, `LR`, `BT`, `RL`)
- Node shapes: `[Process]`, `{Decision}`, `(Start/End)`, `[(Database)]`, `[/Input/]`
- Arrows: `-->` (standard), `-.->` (dotted), `==>` (thick), `-->|label|` (with text)
- **CRITICAL**: Capitalize "end" keyword or wrap in quotes to avoid breaking diagram
## Mandatory Validation Process
For EVERY diagram created:
1. **Generate diagram** using the Skill
2. **Validate with mermaid-cli**:
```bash
echo "DIAGRAM_CONTENT" > /tmp/mermaid_validate.mmd
mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
rc=$?
if [ $rc -ne 0 ]; then
echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
fi
# Check SVG for error markers that mmdc might miss
if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
echo "🛑 Mermaid syntax error found in output SVG"
exit 1
fi
# Verify SVG actually contains diagram content (not just error text)
if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
echo "🛑 SVG output appears invalid or empty"
exit 1
fi
echo "✅ Diagram appears valid"
```
3. **Apply self-healing fixes** if validation fails:
- Remove hyphens from labels: `[Cross-Account]` → `[Cross Account]`
- Remove colons: `[API:prod]` → `[API Prod]`
- Fix IDs: use underscores, no spaces
- Verify syntax keywords match diagram type
- Review error details in `/tmp/mermaid_validate.err` for specific issues
4. **Re-validate until successful**
5. **Clean up**: `rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err`
**NEVER present unvalidated diagrams to users.**
## Size Guidelines
- **Sequence diagrams**: Maximum 7 participants for clarity
- **Architecture diagrams**: Maximum 12 services for readability
- **Flowchart diagrams**: Maximum 15 nodes for clarity
- **Large systems**: Split into multiple focused diagrams
## Output Policy
**YOU MUST output the actual Mermaid code, not just a description.**
- Return a single final ```mermaid code block containing the validated diagram syntax
- Include a brief one-line caption explaining the diagram's purpose
- No partial drafts, descriptions only, or unvalidated content
- The output should be the actual Mermaid syntax that users can copy and render
## Best Practices
- Start simple, add complexity incrementally
- Use consistent naming conventions
- Group related services in architecture diagrams with `group`
- Show activations in sequence diagrams for processing periods (`+`/`-`)
- Apply control structures (`alt`, `loop`) for complex sequence flows
- Use standard shapes in flowcharts (diamonds for decisions, cylinders for databases)
- Label flowchart arrows to clarify logic and decision paths
- Test readability at documentation sizes
Always invoke and load the `common-engineering:mermaid` Skill and follow its validation workflow to ensure professional, error-free diagrams.

View File

@@ -0,0 +1,288 @@
---
name: web-research-specialist
description: Expert web researcher for debugging, technical solutions, and comprehensive topic research across GitHub issues, Stack Overflow, Reddit, forums, and documentation. Use when users need to find solutions to technical problems, research implementation approaches, or gather information from multiple online sources. Particularly strong for code-related research and finding community solutions to library/framework issues.
tools: Read, Grep, Glob, Bash, WebSearch, WebFetch, AskUserQuestion, mcp__plugin_shared-mcp_exa__web_search_exa, mcp__plugin_shared-mcp_exa__get_code_context_exa, mcp__plugin_shared-mcp_tavily__tavily_search, mcp__plugin_shared-mcp_tavily__tavily_extract, mcp__plugin_shared-mcp_tavily__tavily_crawl, mcp__plugin_shared-mcp_tavily__tavily_map
model: inherit
color: blue
---
You are an expert internet researcher specializing in finding relevant information across diverse online sources. Your expertise lies in creative search strategies, thorough investigation, and comprehensive compilation of findings.
## Core Capabilities
- You excel at crafting multiple search query variations to uncover hidden gems of information
- You systematically explore GitHub issues, Reddit threads, Stack Overflow, technical forums, blog posts, and documentation
- You never settle for surface-level results - you dig deep to find the most relevant and helpful information
- You are particularly skilled at debugging assistance, finding others who've encountered similar issues
- You have specialized tools for code-related research that provide the highest quality context for APIs, libraries, and SDKs
## Tool Selection Process
**IMPORTANT: Always start by asking the user which search tool they prefer**
Before conducting any research, you MUST ask the user to choose their preferred search tool:
```python
AskUserQuestion(
questions=[{
"question": "Which search tool would you like me to use for your research?",
"header": "Search Tool Selection",
"options": [
{
"label": "Exa AI",
"description": "AI-powered search with comprehensive technical research capabilities. Best for: code/API documentation, programming queries, GitHub issues, framework research, and deep technical analysis."
},
{
"label": "Tavily",
"description": "Content-focused search with excellent extraction capabilities. Best for: article processing, news research, content extraction, website analysis, and structured content."
},
{
"label": "Native WebSearch",
"description": "Basic web search with broad coverage. Best for: simple queries, general browsing, and when other tools might fail or are unavailable."
}
],
"multiSelect": false
}]
)
```
### Tool Recommendation Guidelines
Based on the user's query, you should recommend the most appropriate tool:
- **For technical/programming queries**: Recommend Exa AI
- **For article/news content**: Recommend Tavily
- **For simple general queries**: Native WebSearch is sufficient
- **If unsure**: Let user choose based on descriptions
### Selected Tool Mode
Once the user chooses a tool, you will operate in that tool's mode for the entire research session, following the specific methodology and tool selection strategy for that chosen tool.
## Tool Selection Strategy
**Your tool selection strategy depends on the user's choice from the initial prompt**
### IF USER CHOSE "Exa AI":
**Primary Research Tools:**
1. **For Code/Programming/API Research**: **Use `mcp__plugin_shared-mcp_exa__get_code_context_exa`**
- API documentation and usage examples
- Library/SDK implementation guides
- Framework best practices
- Code snippets and patterns
- Programming language features
- Any task involving code, libraries, or technical implementations
2. **For General Web Research**: **Use `mcp__plugin_shared-mcp_exa__web_search_exa`**
- Debugging issues and error solutions
- Finding community discussions
- Technical problem-solving
- Comparative research
- GitHub issues, Stack Overflow, Reddit, forums
3. **For Deep Research**: **Use `mcp__plugin_shared-mcp_exa__deep_researcher_start/check`**
- Complex, multi-step research tasks
- Comprehensive analysis requiring multiple sources
### IF USER CHOSE "Tavily":
**Primary Research Tools:**
1. **For General Web Search**: **Use `mcp__plugin_shared-mcp_tavily__tavily_search`**
- News articles and current events
- Blog posts and web content
- General web research
- Time-based searches (past day, week, month)
2. **For Content Extraction**: **Use `mcp__plugin_shared-mcp_tavily__tavily_extract`**
- Extracting clean content from specific URLs
- Converting articles to markdown
- Processing web pages and documents
3. **For Website Analysis**: **Use `mcp__plugin_shared-mcp_tavily__tavily_crawl` and `mcp__plugin_shared-mcp_tavily__tavily_map`**
- Multi-page crawling from websites
- Website structure mapping and discovery
### IF USER CHOSE "Native WebSearch":
**Primary Research Tools:**
1. **For Web Search**: **Use `WebSearch`**
- Basic web search across all sources
- General queries and browsing
- When other tools are unavailable
2. **For Content Extraction**: **Use `WebFetch`**
- Extracting content from specific URLs
- Processing web pages and articles
### Universal Fallback Strategy
**For ALL tool choices, use these fallbacks when primary tools fail:**
1. **If Exa tools fail**: Try Tavily tools, then WebSearch
2. **If Tavily tools fail**: Try Exa tools, then WebSearch
3. **If WebSearch fails**: Try Exa tools, then Tavily tools
4. **If ALL fail**: Indicate the limitation and suggest alternative approaches
**IMPORTANT**: Always prioritize the user's chosen tool, but be prepared to use fallbacks when necessary to complete the research task.
## Research Methodology
### 1. Query Generation
When given a topic or problem, you will:
- Generate 5-10 different search query variations
- Include technical terms, error messages, library names, and common misspellings
- Think of how different people might describe the same issue
- Consider searching for both the problem AND potential solutions
### 2. Source Prioritization
You will search across:
- GitHub Issues (both open and closed)
- Reddit (r/programming, r/webdev, r/javascript, and topic-specific subreddits)
- Stack Overflow and other Stack Exchange sites
- Technical forums and discussion boards
- Official documentation and changelogs
- Blog posts and tutorials
- Hacker News discussions
### 3. Information Gathering
You will:
- Read beyond the first few results
- Look for patterns in solutions across different sources
- Pay attention to dates to ensure relevance
- Note different approaches to the same problem
- Identify authoritative sources and experienced contributors
### 4. Compilation Standards
When presenting findings, you will:
- Organize information by relevance and reliability
- Provide direct links to sources
- Summarize key findings upfront
- Include relevant code snippets or configuration examples
- Note any conflicting information and explain the differences
- Highlight the most promising solutions or approaches
- Include timestamps or version numbers when relevant
## Research Execution
**Your execution strategy must be adapted based on the user's chosen tool**
### IF USER CHOSE "Exa AI":
#### 1. Always Start with Exa Tools
- **For any search query**: First use `mcp__plugin_shared-mcp_exa__web_search_exa`
- **For code/API queries**: First use `mcp__plugin_shared-mcp_exa__get_code_context_exa`
#### 2. For Debugging Assistance
- Use `mcp__plugin_shared-mcp_exa__web_search_exa` to search for exact error messages in quotes
- Find workarounds and known solutions from community sources
- Look for GitHub issues, Stack Overflow discussions, and forum posts
#### 3. For Code Research (SPECIALIZED)
- **Always use `mcp__plugin_shared-mcp_exa__get_code_context_exa`** as your primary tool for code-related queries
- This provides the highest quality and freshest context for APIs, libraries, and frameworks
- Adjust token count (1000-50000) based on complexity - use higher values for comprehensive documentation
#### 4. For Complex Research Tasks
- **Use `mcp__plugin_shared-mcp_exa__deep_researcher_start/check`** for multi-step, comprehensive research
- Monitor progress with `deep_researcher_check` until status shows "completed"
### IF USER CHOSE "Tavily":
#### 1. Always Start with Tavily Tools
- **For general search**: Use `mcp__plugin_shared-mcp_tavily__tavily_search`
- **For content extraction**: Use `mcp__plugin_shared-mcp_tavily__tavily_extract`
- **For website analysis**: Use `mcp__plugin_shared-mcp_tavily__tavily_map` or `tavily_crawl`
#### 2. For Debugging Assistance
- Use `mcp__plugin_shared-mcp_tavily__tavily_search` to search for error messages and solutions
- Use time-based searches to find recent solutions (past day, week, month)
- Extract content from relevant pages using `tavily_extract`
#### 3. For Content-Focused Research
- Use `tavily_search` for finding relevant articles and resources
- Use `tavily_extract` to get clean markdown content from specific URLs
- Use `tavily_crawl` for exploring multiple pages from a website
#### 4. For Website Analysis
- Use `tavily_map` to understand website structure and find relevant pages
- Use `tavily_crawl` to systematically extract content from multiple related pages
### IF USER CHOSE "Native WebSearch":
#### 1. Always Start with Built-in Tools
- **For general search**: Use `WebSearch`
- **For content extraction**: Use `WebFetch` for specific URLs
#### 2. For Debugging Assistance
- Use `WebSearch` to search for error messages and solutions
- Use `WebFetch` to extract and read content from relevant pages
- Focus on finding multiple sources to cross-reference information
#### 3. For General Research
- Use `WebSearch` with multiple query variations
- Use `WebFetch` to read promising results in detail
- Leverage advanced search parameters (time ranges, site-specific searches)
### Universal Fallback Execution
**For ALL tool choices, follow this fallback sequence:**
1. **Primary tool fails or returns no results**:
- Try different search terms with the same tool
- Adjust search parameters (time ranges, query phrasing)
2. **Still no results**: Switch to next tool in this sequence:
- **Exa → Tavily → WebSearch**
- **Tavily → Exa → WebSearch**
- **WebSearch → Exa → Tavily**
3. **Final fallback**: If ALL tools fail:
- Indicate the limitations encountered
- Suggest alternative research approaches
- Ask user for clarification or different search terms
**IMPORTANT**: Always clearly indicate in your findings when you had to use fallback tools and why the primary choice was insufficient.
## Quality Assurance
- Verify information across multiple sources when possible
- Clearly indicate when information is speculative or unverified
- Date-stamp findings to indicate currency
- Distinguish between official solutions and community workarounds
- Note the credibility of sources (official docs vs. random blog post)
## Output Format
Structure your findings as:
### 1. Executive Summary
Key findings in 2-3 sentences
### 2. Detailed Findings
Organized by relevance/approach with:
- Clear headings for each finding or approach
- Source links
- Code examples when relevant
- Version/date information
### 3. Sources and References
Direct links to all sources consulted:
- GitHub issues/PRs
- Stack Overflow threads
- Documentation pages
- Blog posts
- Forum discussions
### 4. Recommendations
If applicable:
- Best approach based on research
- Trade-offs to consider
- Implementation suggestions
### 5. Additional Notes
- Caveats or warnings
- Areas needing more research
- Conflicting information explained
- Edge cases discovered
Remember: You are not just a search engine - you are a research specialist who understands context, can identify patterns, and knows how to find information that others might miss. Your goal is to provide comprehensive, actionable intelligence that saves time and provides clarity.

65
plugin.lock.json Normal file
View File

@@ -0,0 +1,65 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:irfansofyana/my-claude-code-marketplace:plugins/02-common-engineering",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "d40de9d993427981738a7699dc42bb075e040051",
"treeHash": "b7fcc74068c5b90d14239967751a8bcc39f8c0eb78a868bffddcb0674ed30527",
"generatedAt": "2025-11-28T10:17:40.994276Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "common-engineering",
"description": "Foundational engineering tools for diagram generation, documentation, and common development tasks",
"version": "1.0.0"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "a34d17d71392523f4ce0b7e8e8ae01efed61f8edd7f551894139e271b9d5c79b"
},
{
"path": "agents/web-research-specialist.md",
"sha256": "4f3b7df30da7748b3b751bdb620d1a8fd777543e6287ed524261be20b706a38b"
},
{
"path": "agents/mermaid-expert.md",
"sha256": "098c7de1f22e345a8705f4b7fd95bd8176c29439b646a36915e1d88fbdf2557d"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "764c120fcb60e73712359826faa03733491fe2978cdaae7f264a202ef84ca9a9"
},
{
"path": "skills/mermaid/flowchart-diagram-reference.md",
"sha256": "5bf2b5b764398e4c210e46d7bdc5a02c7cc4ffba93f84b25e6a0e20e83989730"
},
{
"path": "skills/mermaid/architecture-diagram-reference.md",
"sha256": "10333796f689eddae1493032155d5b3118d2919d75fdcaf49e2389709bdee35b"
},
{
"path": "skills/mermaid/sequence-diagrams-reference.md",
"sha256": "cb12424845a5cedbed665a3b56d3310f70f9f5a11898e1a680cc6498b46a9167"
},
{
"path": "skills/mermaid/SKILL.md",
"sha256": "7e30c2b76e5339acf439a07be35dc0d54845705e572a5dd0e797e85938545f0d"
}
],
"dirSha256": "b7fcc74068c5b90d14239967751a8bcc39f8c0eb78a868bffddcb0674ed30527"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

478
skills/mermaid/SKILL.md Normal file
View File

@@ -0,0 +1,478 @@
---
name: mermaid-diagrams
description: Create sequence diagrams for message flows and temporal interactions, architecture diagrams for cloud/CI-CD infrastructure relationships, or flowchart diagrams for process flows and decision logic. Automatically validates all diagrams with mermaid-cli and applies self-healing fixes. Use for documenting API interactions, system workflows, microservices communication, cloud service architectures, or process documentation.
---
# Mermaid Diagrams
Create professional diagrams using Mermaid syntax for documentation, design discussions, and system architecture planning. This skill covers three primary diagram types:
- **Sequence Diagrams**: Show temporal interactions and message flows between actors, services, or processes
- **Architecture Diagrams**: Visualize relationships between services and resources in cloud or CI/CD deployments
- **Flowchart Diagrams**: Illustrate processes, decision trees, algorithms, and workflow logic
## 🚀 Automatic Validation Workflow
**IMPORTANT**: All diagrams generated by this skill are automatically validated with mermaid-cli. This ensures error-free diagrams that render correctly every time.
### Mandatory Workflow Steps
When creating diagrams, ALWAYS follow this exact workflow:
1. **Generate Diagram Content** (based on user requirements)
2. **AUTOMATICALLY VALIDATE** using mermaid-cli (mandatory step)
3. **APPLY SELF-HEALING FIXES** if validation fails (automatic)
4. **CONFIRM VALIDATION SUCCESS** before presenting to user
5. **DELIVER VALIDATED DIAGRAM** to user
**NEVER skip validation or present unvalidated diagrams to users.**
## Sequence Diagrams
Sequence diagrams are interaction diagrams that show how processes operate with one another and in what order. They visualize temporal interactions between participants, making them ideal for documenting API flows, system integrations, user interactions, and distributed system communications.
### Quick Instructions
1. Define participants: Use `actor` (humans) or `participant` with type attributes
2. Add messages: `->>` (sync), `-->>` (response), `-)` (async)
3. Show activations: Append `+`/`-` to arrows (`A->>+B`, `B-->>-A`)
4. Control structures: `alt`/`else`, `loop`, `par`, `critical` for complex flows
**→ For detailed syntax, see [sequence-diagrams-reference.md](sequence-diagrams-reference.md)**
### 🔍 Automatic Validation Process
After generating any sequence diagram, you MUST:
1. **Create temp files:**
```bash
echo "YOUR_SEQUENCE_DIAGRAM_HERE" > /tmp/mermaid_validate.mmd
```
2. **Run enhanced validation (your bash script approach):**
```bash
mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
rc=$?
if [ $rc -ne 0 ]; then
echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
fi
# Check SVG for error markers that mmdc might miss
if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
echo "🛑 Mermaid syntax error found in output SVG"
exit 1
fi
# Verify SVG actually contains diagram content (not just error text)
if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
echo "🛑 SVG output appears invalid or empty"
exit 1
fi
echo "✅ Diagram appears valid"
```
3. **If validation fails, apply fixes:**
- Check participant syntax: ensure `participant` or `actor` keywords used correctly
- Verify arrow syntax: `->>`, `-->>`, `-)` patterns are correct
- Validate control structures: `alt`, `loop`, `par` blocks are properly closed
- Review error details in `/tmp/mermaid_validate.err` for specific issues
4. **Re-validate until successful:** (repeat step 2)
5. **Cleanup and confirm:**
```bash
rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err
```
**VALIDATION MUST PASS BEFORE PRESENTING TO USER!**
### ⚠️ CRITICAL: Key Syntax Differences
**NEVER MIX THESE SYNTAXES!** Each diagram type has completely different keywords. Mixing them will break your diagram.
**Sequence Diagrams:**
```mermaid
sequenceDiagram
actor User
participant API@{ "type": "control" }
participant DB@{ "type": "database" }
```
- Use `actor` for humans (stick figure icon)
- Use `participant` with type attributes for systems
- ✓ Use: `participant`, `actor`
- ✗ NEVER use: `service`, `database`, `group`
**Architecture Diagrams:**
```mermaid
architecture-beta
service api(server)[API]
database db(database)[Database]
group backend(cloud)[Backend]
```
- Use `service` for components
- Use `database` as a keyword (NOT participant!)
- Use `group` for organizing services
- ✓ Use: `service`, `database`, `group`
- ✗ NEVER use: `participant`, `actor`
### Minimal Example
```mermaid
sequenceDiagram
actor User
participant API@{ "type": "control" }
participant DB@{ "type": "database" }
User->>+API: Request data
API->>+DB: Query
DB-->>-API: Result
API-->>-User: Response
```
### Guidelines
- Limit to 5-7 participants per diagram for clarity
- Use activations (`+`/`-`) to show processing periods
- Apply control structures (`alt`, `loop`, `par`) for complex flows
**→ See [sequence-diagrams-reference.md](sequence-diagrams-reference.md) for detailed patterns and best practices**
---
## Architecture Diagrams
Architecture diagrams show relationships between services and resources commonly found within cloud or CI/CD deployments. Services (nodes) are connected by edges, and related services can be placed within groups to illustrate organization.
### Quick Instructions
1. Start with `architecture-beta` keyword
2. Define groups: `group {id}({icon})[{label}]`
3. Add services: `service {id}({icon})[{label}] in {group}`
4. Connect edges: `{id}:{T|B|L|R} -- {T|B|L|R}:{id}`
5. Add arrows: `-->` (single) or `<-->` (bidirectional)
**CRITICAL Syntax Rules:**
- **IDs**: Use simple alphanumeric (e.g., `api`, `db1`, `auth_service`) - NO spaces or special chars
- **Labels**: AVOID special characters that break parsing:
- ❌ NO hyphens (`Gen-AI`, `Cross-Account`)
- ❌ NO colons (`AWS Account: prod`)
- ❌ NO special punctuation
- ✓ Use spaces: `[Gen AI]` instead of `[Gen-AI]`
- ✓ Use simple words: `[Cross Account IAM Role]` instead of `[Cross-Account IAM Role]`
**Default icons**: `cloud`, `database`, `disk`, `internet`, `server`
**→ For extended icons and advanced features, see [architecture-diagram-reference.md](architecture-diagram-reference.md)**
### 🔍 Automatic Validation Process
After generating any architecture diagram, you MUST:
1. **Create temp files:**
```bash
echo "YOUR_ARCHITECTURE_DIAGRAM_HERE" > /tmp/mermaid_validate.mmd
```
2. **Run enhanced validation (your bash script approach):**
```bash
mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
rc=$?
if [ $rc -ne 0 ]; then
echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
fi
# Check SVG for error markers that mmdc might miss
if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
echo "🛑 Mermaid syntax error found in output SVG"
exit 1
fi
# Verify SVG actually contains diagram content (not just error text)
if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
echo "🛑 SVG output appears invalid or empty"
exit 1
fi
echo "✅ Diagram appears valid"
```
3. **If validation fails, apply automatic fixes:**
- **Fix hyphens in labels**: `[Gen-AI]` → `[Gen AI]`
- **Remove colons**: `[API:prod]` → `[API Prod]`
- **Remove special characters**: keep only alphanumeric, spaces, underscores
- **Fix IDs**: ensure no spaces in service/group IDs (use underscores)
- Review error details in `/tmp/mermaid_validate.err` for specific issues
4. **Re-validate until successful:** (repeat step 2)
5. **Cleanup and confirm:**
```bash
rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err
```
**VALIDATION MUST PASS BEFORE PRESENTING TO USER!**
### Minimal Example
```mermaid
architecture-beta
group stg_aitools(cloud)[AWS Stg AI Tools]
group stg_genai(cloud)[AWS Stg Gen AI]
service litellm(server)[LiteLLM Service] in stg_aitools
service rds(database)[RDS PostgreSQL] in stg_aitools
service redis(disk)[Redis Cache] in stg_aitools
service bedrock(server)[AWS Bedrock] in stg_genai
service iam_role(server)[Cross Account IAM Role] in stg_genai
litellm:R --> L:rds
litellm:B --> T:redis
litellm:R --> L:iam_role
iam_role:B --> T:bedrock
```
**Note**: No hyphens in labels! Use spaces instead (`Gen AI` not `Gen-AI`)
### Guidelines
- Group related services with `group` declarations
- Use clear directional indicators (T/B/L/R) and arrows (`-->`)
- Limit to 8-12 services per diagram for clarity
**→ See [architecture-diagram-reference.md](architecture-diagram-reference.md) for icons, junctions, and complex patterns**
---
## Flowchart Diagrams
Flowchart diagrams visualize processes, decision logic, algorithms, and workflows using nodes (shapes) and edges (arrows). They're ideal for documenting business processes, algorithm logic, decision trees, and step-by-step workflows.
### Quick Instructions
1. Start with `flowchart` keyword and direction: `flowchart TD` (Top Down), `LR` (Left Right)
2. Define nodes with shapes: `[Process]`, `{Decision}`, `(Start/End)`, `[(Database)]`
3. Connect with arrows: `-->` (standard), `-.->` (dotted), `==>` (thick)
4. Add text to arrows: `-->|label|` or `-- label -->`
5. Group related nodes: use `subgraph` blocks
6. Apply styling: `style id fill:#color,stroke:#color`
**→ For detailed syntax, see [flowchart-diagram-reference.md](flowchart-diagram-reference.md)**
### 🔍 Automatic Validation Process
After generating any flowchart diagram, you MUST:
1. **Create temp files:**
```bash
echo "YOUR_FLOWCHART_DIAGRAM_HERE" > /tmp/mermaid_validate.mmd
```
2. **Run enhanced validation (your bash script approach):**
```bash
mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
rc=$?
if [ $rc -ne 0 ]; then
echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
fi
# Check SVG for error markers that mmdc might miss
if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
echo "🛑 Mermaid syntax error found in output SVG"
exit 1
fi
# Verify SVG actually contains diagram content (not just error text)
if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
echo "🛑 SVG output appears invalid or empty"
exit 1
fi
echo "✅ Diagram appears valid"
```
3. **If validation fails, apply fixes:**
- Check node shape syntax: ensure brackets/braces are balanced
- Verify arrow syntax: `-->`, `-.->`, `==>` patterns are correct
- Validate subgraph blocks: ensure `subgraph` has matching `end`
- Avoid reserved words: capitalize "end" or wrap in quotes
- Review error details in `/tmp/mermaid_validate.err` for specific issues
4. **Re-validate until successful:** (repeat step 2)
5. **Cleanup and confirm:**
```bash
rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err
```
**VALIDATION MUST PASS BEFORE PRESENTING TO USER!**
### Minimal Example
```mermaid
flowchart TD
Start([Start Process]) --> Input[/Enter Data/]
Input --> Validate{Valid Data?}
Validate -->|Yes| Process[Process Data]
Validate -->|No| Error[Display Error]
Error --> Input
Process --> DB[(Save to Database)]
DB --> End([End])
```
### Guidelines
- Limit to 10-15 nodes per diagram for clarity
- Use standard shapes: diamonds for decisions, cylinders for databases
- Label arrows to clarify flow logic
- Group related processes with `subgraph` for organization
**→ See [flowchart-diagram-reference.md](flowchart-diagram-reference.md) for all node shapes, arrow types, subgraphs, and styling options**
---
## When to Use Each Diagram Type
### Use Sequence Diagrams When:
- Documenting **temporal interactions** and message ordering
- Showing **API request/response flows**
- Illustrating **authentication or authorization flows**
- Explaining **microservices communication patterns**
- Demonstrating **error handling** and conditional logic
- Visualizing **actor interactions** over time
### Use Architecture Diagrams When:
- Showing **infrastructure relationships** and deployment structure
- Documenting **cloud service architecture**
- Illustrating **CI/CD pipeline components**
- Visualizing **system topology** and service organization
- Explaining **resource dependencies** (databases, storage, networks)
- Presenting **high-level system design**
### Use Flowchart Diagrams When:
- Documenting **business processes** and workflows
- Illustrating **decision logic** and conditional branches
- Visualizing **algorithm steps** and computation flow
- Showing **approval workflows** or multi-step procedures
- Explaining **error handling** paths and retry logic
- Creating **troubleshooting guides** and decision trees
---
## Common Best Practices
**For Both Diagram Types:**
1. **Start simple**: Begin with basic structures, then add complexity as needed
2. **Use consistent naming**: Follow your project's naming conventions
3. **Keep it focused**: If a diagram becomes unclear, split it into multiple diagrams
4. **Test readability**: Ensure diagrams are readable at typical documentation sizes
5. **Version control**: Treat diagrams as code—review changes and maintain them alongside implementation
6. **Document assumptions**: Use notes or descriptions to clarify business rules or technical constraints
**Diagram Size Guidelines:**
- **Sequence**: Limit to 5-7 participants per diagram
- **Architecture**: Limit to 8-12 services per diagram
- **Flowchart**: Limit to 10-15 nodes per diagram
- For larger systems, create multiple diagrams focusing on specific subsystems or layers
**When Diagrams Conflict:**
- For **runtime behavior** → use sequence diagrams
- For **deployment structure** → use architecture diagrams
- For **process/decision flows** → use flowchart diagrams
- For complex systems, use combinations: architecture for infrastructure, sequence for interactions, flowcharts for business logic
---
## Common Mistakes
### ❌ Common Syntax Mistakes
**Architecture diagrams**: NEVER use these patterns:
1. **Hyphens in labels** (breaks parsing):
- ❌ `[Gen-AI]`, `[Cross-Account]`, `[AI-Tools]`
- ✓ `[Gen AI]`, `[Cross Account]`, `[AI Tools]`
2. **Special characters in labels**:
- ❌ `[AWS Account: prod]` (colons)
- ❌ `[DB@prod]` (at symbols)
- ✓ `[AWS Account Prod]` (simple words)
3. **Invalid keywords in sequence diagrams**:
- ❌ `database DB`, `service API`
- ✓ `participant DB@{ "type": "database" }`
4. **Unbalanced brackets in flowchart nodes**:
- ❌ `A[Text`, `B{Decision`, `C(Start`
- ✓ `A[Text]`, `B{Decision}`, `C(Start)`
5. **Reserved words in flowcharts**:
- ❌ `end` (breaks diagram)
- ✓ `End`, `END`, or `"end"`
**→ See examples above for correct syntax patterns**
**🔧 Validation Tip**: These errors are automatically caught and fixed by the mandatory validation process. See the [Automatic Validation Workflow](#-automatic-validation-workflow) section.
---
## Troubleshooting
**Sequence Diagrams:**
- **"end" keyword breaks diagram**: Wrap in quotes `"end"` or parentheses `(end)`
- **Participant not appearing**: Explicitly declare with `participant Name` before first use
- **Arrow not rendering**: Verify syntax (`->>`, `-->>`, `->`, `-->`, `-)`)
**Architecture Diagrams:**
- **Parsing errors with labels**: Avoid colons (`:`) and complex punctuation in labels
- ❌ Wrong: `[AWS Account: prod api]`
- ✓ Correct: `[AWS Account Prod API]`
- **Invalid ID errors**: Use simple alphanumeric IDs without spaces
- ❌ Wrong: `group stg ai-tools` (space in ID)
- ✓ Correct: `group stg_aitools` or `group aitools_stg`
- **Service not in group**: Ensure group is declared before service, use `in {group_id}`
- **Edge not connecting**: Verify both services exist and direction indicators are valid (T/B/L/R)
- **Icon not displaying**: Check icon name spelling or use default icons
**Flowchart Diagrams:**
- **Unbalanced brackets**: Ensure all node shapes have matching opening/closing brackets
- ❌ Wrong: `A[Process`, `B{Decision`
- ✓ Correct: `A[Process]`, `B{Decision}`
- **Reserved word "end"**: Capitalize or quote it to avoid breaking diagram
- ❌ Wrong: `flowchart TD\n A --> end`
- ✓ Correct: `flowchart TD\n A --> End`
- **Arrow syntax errors**: Verify arrow patterns (`-->`, `-.->`, `==>`)
- **Subgraph not closed**: Ensure every `subgraph` has matching `end`
- **Node not appearing**: Check node ID is defined before use in connections
**Validation & mmdc Issues:**
- **mmdc not found**: Install mermaid-cli with `npm install -g @mermaid-js/mermaid-cli`
- **Permission errors**: Check write permissions to `/tmp` directory
- **Silent failures**: Enhanced validation now checks both exit codes AND SVG content for embedded errors
- **False positive validation**: The new validation catches cases where mmdc returns success but SVG contains syntax errors
- **Error file analysis**: Check `/tmp/mermaid_validate.err` for detailed error messages when validation fails
- **SVG validation failures**: Diagrams with embedded syntax errors are now detected via SVG content scanning
- **Persistent syntax errors**: Use the [Automatic Validation Workflow](#-automatic-validation-workflow) to automatically detect and fix common issues
**Enhanced Validation Features:**
- **Dual-layer validation**: Checks both mmdc exit codes AND SVG output for error markers
- **Error pattern detection**: Scans for 'Syntax error in graph', 'mermaidError', 'errorText', 'Parse error' in SVG
- **SVG integrity check**: Verifies output contains valid SVG structure with width/height attributes
- **Detailed error reporting**: Captures mmdc stderr output for specific syntax issues
---
## Reference Documentation
For complete syntax, advanced features, and more examples:
- **[sequence-diagrams-reference.md](sequence-diagrams-reference.md)** - All arrow types, activations, control structures, styling, and configuration
- **[architecture-diagram-reference.md](architecture-diagram-reference.md)** - Complete syntax, junctions, extended icons (200k+ from iconify), and complex patterns
- **[flowchart-diagram-reference.md](flowchart-diagram-reference.md)** - All node shapes, arrow types, subgraphs, styling, and advanced features
---
This skill enables you to create professional diagrams for documentation, design discussions, API specifications, system architecture planning, and process documentation. Choose the appropriate diagram type based on whether you're documenting temporal interactions (sequence), structural relationships (architecture), or process flows (flowchart).

View File

@@ -0,0 +1,175 @@
# Architecture Diagrams Documentation (v11.1.0+)
> In the context of mermaid-js, the architecture diagram is used to show the relationship between services and resources commonly found within the Cloud or CI/CD deployments. In an architecture diagram, services (nodes) are connected by edges. Related services can be placed within groups to better illustrate how they are organized.
## Example
```mermaid-example
architecture-beta
group api(cloud)[API]
service db(database)[Database] in api
service disk1(disk)[Storage] in api
service disk2(disk)[Storage] in api
service server(server)[Server] in api
db:L -- R:server
disk1:T -- B:server
disk2:T -- B:db
```
## Syntax
The building blocks of an architecture are `groups`, `services`, `edges`, and `junctions`.
For supporting components, icons are declared by surrounding the icon name with `()`, while labels are declared by surrounding the text with `[]`.
To begin an architecture diagram, use the keyword `architecture-beta`, followed by your groups, services, edges, and junctions. While each of the 3 building blocks can be declared in any order, care must be taken to ensure the identifier was previously declared by another component.
### Groups
The syntax for declaring a group is:
```
group {group id}({icon name})[{title}] (in {parent id})?
```
Put together:
```
group public_api(cloud)[Public API]
```
creates a group identified as `public_api`, uses the icon `cloud`, and has the label `Public API`.
Additionally, groups can be placed within a group using the optional `in` keyword
```
group private_api(cloud)[Private API] in public_api
```
### Services
The syntax for declaring a service is:
```
service {service id}({icon name})[{title}] (in {parent id})?
```
Put together:
```
service database1(database)[My Database]
```
creates the service identified as `database1`, using the icon `database`, with the label `My Database`.
If the service belongs to a group, it can be placed inside it through the optional `in` keyword
```
service database1(database)[My Database] in private_api
```
### Edges
The syntax for declaring an edge is:
```
{serviceId}{{group}}?:{T|B|L|R} {<}?--{>}? {T|B|L|R}:{serviceId}{{group}}?
```
#### Edge Direction
The side of the service the edge comes out of is specified by adding a colon (`:`) to the side of the service connecting to the arrow and adding `L|R|T|B`
For example:
```
db:R -- L:server
```
creates an edge between the services `db` and `server`, with the edge coming out of the right of `db` and the left of `server`.
```
db:T -- L:server
```
creates a 90 degree edge between the services `db` and `server`, with the edge coming out of the top of `db` and the left of `server`.
#### Arrows
Arrows can be added to each side of an edge by adding `<` before the direction on the left, and/or `>` after the direction on the right.
For example:
```
subnet:R --> L:gateway
```
creates an edge with the arrow going into the `gateway` service
#### Edges out of Groups
To have an edge go from a group to another group or service within another group, the `{group}` modifier can be added after the `serviceId`.
For example:
```
service server[Server] in groupOne
service subnet[Subnet] in groupTwo
server{group}:B --> T:subnet{group}
```
creates an edge going out of `groupOne`, adjacent to `server`, and into `groupTwo`, adjacent to `subnet`.
It's important to note that `groupId`s cannot be used for specifying edges and the `{group}` modifier can only be used for services within a group.
### Junctions
Junctions are a special type of node which acts as a potential 4-way split between edges.
The syntax for declaring a junction is:
```
junction {junction id} (in {parent id})?
```
```mermaid-example
architecture-beta
service left_disk(disk)[Disk]
service top_disk(disk)[Disk]
service bottom_disk(disk)[Disk]
service top_gateway(internet)[Gateway]
service bottom_gateway(internet)[Gateway]
junction junctionCenter
junction junctionRight
left_disk:R -- L:junctionCenter
top_disk:B -- T:junctionCenter
bottom_disk:T -- B:junctionCenter
junctionCenter:R -- L:junctionRight
top_gateway:B -- T:junctionRight
bottom_gateway:T -- B:junctionRight
```
## Icons
By default, architecture diagram supports the following icons: `cloud`, `database`, `disk`, `internet`, `server`.
Users can use any of the 200,000+ icons available in iconify.design, or add other custom icons, by [registering an icon pack](../config/icons.md).
After the icons are installed, they can be used in the architecture diagram by using the format "name:icon-name", where name is the value used when registering the icon pack.
```mermaid-example
architecture-beta
group api(logos:aws-lambda)[API]
service db(logos:aws-aurora)[Database] in api
service disk1(logos:aws-glacier)[Storage] in api
service disk2(logos:aws-s3)[Storage] in api
service server(logos:aws-ec2)[Server] in api
db:L -- R:server
disk1:T -- B:server
disk2:T -- B:db
```

View File

@@ -0,0 +1,878 @@
# Flowchart Diagram Reference
Comprehensive syntax reference for creating flowchart diagrams in Mermaid. Flowcharts consist of **nodes** (geometric shapes) and **edges** (connecting lines/arrows) that visualize processes, decision logic, algorithms, and workflows.
## Basic Syntax
All flowcharts start with the `flowchart` keyword followed by an optional direction:
```mermaid
flowchart TD
Start --> Stop
```
## Direction Control
Control the orientation of your flowchart:
| Direction | Description |
|-----------|-------------|
| `TB` or `TD` | Top to Bottom (default) |
| `BT` | Bottom to Top |
| `LR` | Left to Right |
| `RL` | Right to Left |
**Example:**
```mermaid
flowchart LR
A --> B
```
---
## Node Shapes
### Basic Node Types
#### Default Node (Rectangle with Text)
```mermaid
flowchart TD
id
id1[This is the text in the box]
```
#### Round Edges (Rounded Rectangle)
```mermaid
flowchart TD
id1(This is the text in the box)
```
#### Stadium Shape (Pill Shape)
```mermaid
flowchart TD
id1([This is the text in the box])
```
#### Subroutine (Rectangle with Vertical Lines)
```mermaid
flowchart TD
id1[[This is the text in the box]]
```
#### Cylinder (Database)
```mermaid
flowchart TD
id1[(Database)]
```
#### Circle
```mermaid
flowchart TD
id1((This is the text in the circle))
```
#### Double Circle
```mermaid
flowchart TD
id1(((This is the text in the circle)))
```
#### Asymmetric Shape
```mermaid
flowchart TD
id1>This is the text in the box]
```
#### Diamond/Rhombus (Decision)
```mermaid
flowchart TD
id1{This is the text in the box}
```
#### Hexagon
```mermaid
flowchart TD
id1{{This is the text in the box}}
```
#### Parallelogram (Input/Output)
```mermaid
flowchart TD
id1[/This is the text in the box/]
```
#### Parallelogram Alt
```mermaid
flowchart TD
id1[\This is the text in the box\]
```
#### Trapezoid
```mermaid
flowchart TD
A[/Christmas\]
```
#### Trapezoid Alt
```mermaid
flowchart TD
B[\Go shopping/]
```
### Node Shape Quick Reference Table
| Shape | Syntax | Common Use |
|-------|--------|------------|
| Rectangle | `id[Text]` | Process/Action |
| Round edges | `id(Text)` | Start/End |
| Stadium | `id([Text])` | Start/End (alternate) |
| Subroutine | `id[[Text]]` | Predefined process |
| Cylinder | `id[(Text)]` | Database |
| Circle | `id((Text))` | Connection point |
| Double circle | `id(((Text)))` | Special endpoint |
| Diamond | `id{Text}` | Decision/Condition |
| Hexagon | `id{{Text}}` | Preparation |
| Parallelogram | `id[/Text/]` | Input/Output |
| Trapezoid | `id[/Text\]` | Manual operation |
---
## Text Formatting
### Unicode Support
Use quotes for Unicode characters:
```mermaid
flowchart LR
id["This ❤ Unicode"]
```
### Markdown in Nodes
Use backticks with double quotes for markdown formatting:
```mermaid
flowchart LR
markdown["`This **is** _Markdown_`"]
newLines["`Line1
Line2
Line3`"]
```
Supports:
- **Bold**: `**text**`
- *Italics*: `*text*`
- Line breaks (automatic wrapping)
---
## Edges/Links
### Basic Link Types
#### Standard Arrow
```mermaid
flowchart LR
A-->B
```
#### Open Link (No Arrow)
```mermaid
flowchart LR
A --- B
```
#### Text on Link
```mermaid
flowchart LR
A-- This is the text! ---B
C---|This is the text|D
```
#### Arrow with Text
```mermaid
flowchart LR
A-->|text|B
C-- text -->D
```
#### Dotted Link
```mermaid
flowchart LR
A-.->B
```
#### Dotted Link with Text
```mermaid
flowchart LR
A-. text .-> B
```
#### Thick Link
```mermaid
flowchart LR
A ==> B
```
#### Thick Link with Text
```mermaid
flowchart LR
A == text ==> B
```
#### Invisible Link (for spacing)
```mermaid
flowchart LR
A ~~~ B
```
### Special Edge Types
#### Circle Edge
```mermaid
flowchart LR
A --o B
```
#### Cross Edge
```mermaid
flowchart LR
A --x B
```
### Multi-directional Arrows
```mermaid
flowchart LR
A o--o B
B <--> C
C x--x D
```
### Edge Types Quick Reference
| Type | Syntax | Description |
|------|--------|-------------|
| Standard arrow | `A-->B` | Directional flow |
| Open link | `A---B` | Connection without direction |
| Arrow with text | `A-->|text|B` | Labeled flow |
| Dotted arrow | `A-.->B` | Optional/alternative path |
| Thick arrow | `A==>B` | Emphasized flow |
| Invisible link | `A~~~B` | Hidden connection (spacing) |
| Circle edge | `A--oB` | Special connection |
| Cross edge | `A--xB` | Terminated/blocked flow |
| Bidirectional | `A<-->B` | Two-way flow |
---
## Link Length Control
Control the visual length of connections by adding extra dashes or dots:
| Length Type | 1 | 2 | 3 |
|---|---|---|---|
| Normal | `---` | `----` | `-----` |
| With arrow | `-->` | `--->` | `---->` |
| Thick | `===` | `====` | `=====` |
| Thick arrow | `==>` | `===>` | `====>` |
| Dotted | `-.-` | `-..-` | `-...-` |
| Dotted arrow | `-.->` | `-..->` | `-...->` |
**Example:**
```mermaid
flowchart TD
A --> B
A ---> C
A -----> D
```
---
## Chaining Links
### Sequential Chaining
Connect multiple nodes in one line:
```mermaid
flowchart LR
A -- text --> B -- text2 --> C
```
### Parallel Connections with Ampersand
Connect multiple nodes to multiple targets:
```mermaid
flowchart TD
a --> b & c --> d
```
Multiple sources to multiple targets:
```mermaid
flowchart TD
A & B --> C & D
```
---
## Subgraphs
Group related nodes together using subgraphs.
### Basic Subgraph
```mermaid
flowchart TB
c1-->a2
subgraph one
a1-->a2
end
subgraph two
b1-->b2
end
subgraph three
c1-->c2
end
```
### Subgraph with Explicit ID
```mermaid
flowchart TB
subgraph ide1 [one]
a1-->a2
end
```
### Nested Subgraphs
```mermaid
flowchart TB
subgraph TOP
direction TB
subgraph B1
direction RL
i1 -->f1
end
subgraph B2
direction BT
i2 -->f2
end
end
A --> TOP --> B
```
### Direction in Subgraphs
```mermaid
flowchart LR
subgraph TOP
direction TB
subgraph B1
direction RL
i1 -->f1
end
end
```
**Note:** External node links can override subgraph direction settings.
---
## Styling
### Link Styling
Apply styles to specific links by their order (zero-indexed):
```mermaid
flowchart LR
A-->B
B-->C
C-->D
D-->E
linkStyle 0 stroke:#ff3,stroke-width:4px,color:red;
linkStyle 3 stroke:#00f,stroke-width:2px;
```
Style multiple links at once:
```mermaid
flowchart LR
A-->B
B-->C
C-->D
linkStyle 0,1,2 color:blue;
```
### Node Styling
Apply inline styles to specific nodes:
```mermaid
flowchart LR
id1(Start)-->id2(Stop)
style id1 fill:#f9f,stroke:#333,stroke-width:4px
style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
```
**Available style properties:**
- `fill`: Background color
- `stroke`: Border color
- `stroke-width`: Border width
- `color`: Text color
- `stroke-dasharray`: Dashed border pattern
### Classes
Define reusable style classes:
```mermaid
flowchart LR
A:::someclass --> B
classDef someclass fill:#f96
```
Apply class to multiple nodes:
```mermaid
flowchart LR
A-->B[AAA<span>BBB</span>]
B-->D
class A cssClass
```
**Class definition syntax:**
```mermaid
flowchart TD
A[Start] --> B[Process]
classDef green fill:#9f6,stroke:#333,stroke-width:2px;
classDef orange fill:#f96,stroke:#333,stroke-width:4px;
class A green
class B orange
```
### Default Class
Apply styles to all nodes without specific styling:
```mermaid
flowchart TD
A[Start] --> B{Decision}
B -->|Yes| C[OK]
B -->|No| D[Not OK]
classDef default fill:#f9f,stroke:#333,stroke-width:2px;
```
### CSS Classes
Reference predefined CSS classes from your HTML/stylesheet:
```html
<style>
.cssClass > rect {
fill:#FF0000;
stroke:#FFFF00;
stroke-width:4px;
}
</style>
```
```mermaid
flowchart LR
A-->B[AAA<span>BBB</span>]
B-->D
class A cssClass
```
---
## Curve Styles
Control the curve interpolation of edges at the diagram level:
```mermaid
---
config:
flowchart:
curve: stepBefore
---
flowchart LR
A --> B --> C
```
**Available curve types:**
- `basis`
- `bumpX`
- `bumpY`
- `cardinal`
- `catmullRom`
- `linear` (default)
- `monotoneX`
- `monotoneY`
- `natural`
- `step`
- `stepAfter`
- `stepBefore`
---
## Advanced Features
### Edge IDs and Animation
Assign IDs to edges and apply animations:
```mermaid
flowchart LR
A e1@--> B
e1@{ animate: true }
```
**Animation speeds:**
- `fast`
- `slow`
### Icons in Nodes
Add FontAwesome icons to nodes:
```mermaid
flowchart TD
A@{ icon: "fa:user", form: "square", label: "User Icon", pos: "t", h: 60 }
B@{ icon: "fa:database", form: "circle", label: "Database", pos: "b" }
```
**Icon parameters:**
- `icon`: Icon identifier (e.g., `"fa:user"`)
- `form`: Shape - `square`, `circle`, `rounded`
- `label`: Text label
- `pos`: Position - `t` (top), `b` (bottom)
- `h`: Height in pixels
- `w`: Width in pixels
### Images in Nodes
Embed images in nodes:
```mermaid
flowchart LR
A@{ img: "https://example.com/image.png", label: "Label", w: 60, h: 60, constraint: "on" }
```
**Image parameters:**
- `img`: Image URL
- `label`: Text label
- `w`: Width in pixels
- `h`: Height in pixels
- `constraint`: Layout constraint (`"on"` or `"off"`)
---
## Interactions
### Click Events
Add clickable elements to nodes:
#### Callback Function
```mermaid
flowchart LR
A-->B
click A callback "Tooltip for A"
```
```javascript
const callback = function() {
alert('A callback was triggered');
}
```
#### External Link
```mermaid
flowchart LR
A-->B
click A "https://www.github.com" "Navigate to GitHub"
```
#### Function Call
```mermaid
flowchart LR
A-->B
click A call callback() "Tooltip"
```
### Link Targets
Specify how links open:
```mermaid
flowchart LR
A-->B
click A "https://www.github.com" _blank
```
**Target options:**
- `_self` - Same frame (default)
- `_blank` - New window/tab
- `_parent` - Parent frame
- `_top` - Full window
**Security Note:** Click interactions are disabled with `securityLevel='strict'` and enabled with `securityLevel='loose'`.
---
## Special Characters and Escaping
### Using Quotes
Wrap text containing special characters in quotes:
```mermaid
flowchart LR
id1["This is the (text) in the box"]
```
Characters that need escaping: `()`, `{}`, `[]`, `:`, `;`, `|`
### Entity Codes
Use HTML entity codes for special characters:
```mermaid
flowchart LR
A["A double quote:#quot;"] --> B["A dec char:#9829;"]
```
**Common entity codes:**
- `#quot;` - `"`
- `#35;` - `#`
- `#9829;` - ❤
- `#amp;` - `&`
- `#lt;` - `<`
- `#gt;` - `>`
---
## FontAwesome Icons
Embed FontAwesome icons in node text:
### Basic Syntax
```mermaid
flowchart TD
B["fa:fa-twitter for peace"]
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner)
B-->E(A fa:fa-camera-retro perhaps?)
```
### Icon Prefixes
- `fa` - Standard icons
- `fab` - Brand icons
- `fas` - Solid style
- `far` - Regular style
- `fal` - Light style
- `fad` - Duotone style
- `fak` - Custom uploaded icons
### Required CSS
Include FontAwesome CSS in your HTML `<head>`:
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet"/>
```
---
## Comments
Add comments to your flowchart code (not rendered):
```mermaid
flowchart LR
%% This is a comment
A -- text --> B -- text2 --> C
%% Another comment
```
Comments must start with `%%` at the beginning of a line.
---
## Configuration
### Renderer Selection
Choose between rendering engines:
```mermaid
---
config:
flowchart:
defaultRenderer: "elk"
---
flowchart TD
A --> B
```
**Available renderers:**
- `dagre` (default) - Fast, suitable for most diagrams
- `elk` - Better for large/complex diagrams
### Width Adjustment
Control diagram width programmatically:
```javascript
mermaid.flowchartConfig = {
width: "100%"
}
```
### Markdown Auto-Wrap
Disable automatic text wrapping in markdown strings:
```mermaid
---
config:
markdownAutoWrap: false
---
flowchart LR
a("`The **cat**
in the hat`")
```
---
## Complete Example
Here's a comprehensive flowchart demonstrating multiple features:
```mermaid
flowchart TD
Start([Start Process]) --> Input[/Enter Data/]
Input --> Validate{Valid Data?}
Validate -->|Yes| Process[Process Data]
Validate -->|No| Error[Display Error]
Error --> Input
Process --> DB[(Save to Database)]
DB --> Check{Success?}
Check -->|Yes| Success([End Success])
Check -->|No| Retry{Retry?}
Retry -->|Yes| Process
Retry -->|No| Fail([End Failure])
style Start fill:#90EE90,stroke:#333,stroke-width:2px
style Success fill:#90EE90,stroke:#333,stroke-width:2px
style Fail fill:#FFB6C1,stroke:#333,stroke-width:2px
style Error fill:#FFB6C1,stroke:#333,stroke-width:2px
classDef decisionClass fill:#FFE4B5,stroke:#333,stroke-width:2px
class Validate,Check,Retry decisionClass
```
---
## Common Patterns
### Decision Tree
```mermaid
flowchart TD
A{Is it working?}
A -->|Yes| B[Don't touch it]
A -->|No| C{Did you touch it?}
C -->|Yes| D[Idiot!]
C -->|No| E{Does anyone know?}
E -->|Yes| F[You're screwed]
E -->|No| G[Hide it]
```
### Process Flow
```mermaid
flowchart LR
A([Start]) --> B[Initialize]
B --> C[Process Step 1]
C --> D[Process Step 2]
D --> E[Process Step 3]
E --> F([End])
```
### Approval Workflow
```mermaid
flowchart TD
Submit[Submit Request] --> Review{Manager Review}
Review -->|Approved| Finance{Finance Check}
Review -->|Rejected| Notify1[Notify Requester]
Finance -->|Approved| Execute[Execute]
Finance -->|Rejected| Notify2[Notify Requester]
Execute --> Complete([Complete])
```
---
## Important Warnings
### Reserved Words
- **"end" keyword**: Capitalize it (`End`, `END`) or wrap in quotes to avoid breaking diagrams
```mermaid
flowchart LR
A --> End
```
- **"o" and "x" at line start**: Add spaces or capitalize to prevent creating circle/cross edges
```mermaid
flowchart LR
A --> B
%% Not: o--> (creates circle edge)
%% Use: O--> or add space
```
### Security Considerations
- Click interactions are disabled with `securityLevel='strict'`
- Enable with `securityLevel='loose'` when needed (only in trusted environments)
---
## Troubleshooting
### Common Issues
**Node not appearing:**
- Verify node ID is defined before use
- Check for typos in node references
**Arrow not rendering:**
- Verify arrow syntax (`-->`, `---`, `-.->`, `==>`)
- Ensure both nodes exist
**Text not displaying:**
- Use quotes for special characters: `["text (with parens)"]`
- Escape markdown properly with backticks
**Subgraph not grouping:**
- Ensure subgraph is declared before nodes
- Check indentation and `end` keyword placement
**Styling not applying:**
- Verify style syntax (no spaces around `:`)
- Check class names match definitions
- Ensure classDef comes before class assignment
**Validation failures:**
- Run mermaid-cli to get specific error messages
- Check for reserved words (like "end")
- Verify all node IDs are properly defined
---
## Best Practices
1. **Keep it simple**: Limit to 10-15 nodes per diagram for clarity
2. **Use consistent shapes**: Follow standard conventions (diamonds for decisions, cylinders for databases)
3. **Label edges**: Add text to arrows for clarity in complex flows
4. **Group with subgraphs**: Organize related processes
5. **Apply styling**: Use colors to highlight important paths or states
6. **Test readability**: Ensure diagram is readable at documentation sizes
7. **Comment your code**: Use `%%` comments to explain complex sections
8. **Version control**: Treat diagrams as code and track changes
9. **Split large diagrams**: Create multiple focused diagrams instead of one complex diagram
10. **Validate syntax**: Always test with mermaid-cli before committing
---
This reference covers the complete Mermaid flowchart syntax. Use it to create professional process diagrams, decision trees, algorithm visualizations, and workflow documentation.

View File

@@ -0,0 +1,797 @@
# Sequence diagrams
> A Sequence diagram is an interaction diagram that shows how processes operate with one another and in what order.
Mermaid can render sequence diagrams.
```mermaid-example
sequenceDiagram
Alice->>John: Hello John, how are you?
John-->>Alice: Great!
Alice-)John: See you later!
```
```note
A note on nodes, the word "end" could potentially break the diagram, due to the way that the mermaid language is scripted.
If unavoidable, one must use parentheses(), quotation marks "", or brackets {},[], to enclose the word "end". i.e : (end), [end], {end}.
```
## Syntax
### Participants
The participants can be defined implicitly as in the first example on this page. The participants or actors are
rendered in order of appearance in the diagram source text. Sometimes you might want to show the participants in a
different order than how they appear in the first message. It is possible to specify the actor's order of
appearance by doing the following:
```mermaid-example
sequenceDiagram
participant Alice
participant Bob
Bob->>Alice: Hi Alice
Alice->>Bob: Hi Bob
```
### Actors
If you specifically want to use the actor symbol instead of a rectangle with text you can do so by using actor statements as per below.
```mermaid-example
sequenceDiagram
actor Alice
actor Bob
Alice->>Bob: Hi Bob
Bob->>Alice: Hi Alice
```
### Boundary
If you want to use the boundary symbol for a participant, use the JSON configuration syntax as shown below.
```mermaid-example
sequenceDiagram
participant Alice@{ "type" : "boundary" }
participant Bob
Alice->>Bob: Request from boundary
Bob->>Alice: Response to boundary
```
### Control
If you want to use the control symbol for a participant, use the JSON configuration syntax as shown below.
```mermaid-example
sequenceDiagram
participant Alice@{ "type" : "control" }
participant Bob
Alice->>Bob: Control request
Bob->>Alice: Control response
```
### Entity
If you want to use the entity symbol for a participant, use the JSON configuration syntax as shown below.
```mermaid-example
sequenceDiagram
participant Alice@{ "type" : "entity" }
participant Bob
Alice->>Bob: Entity request
Bob->>Alice: Entity response
```
### Database
If you want to use the database symbol for a participant, use the JSON configuration syntax as shown below.
```mermaid-example
sequenceDiagram
participant Alice@{ "type" : "database" }
participant Bob
Alice->>Bob: DB query
Bob->>Alice: DB result
```
### Collections
If you want to use the collections symbol for a participant, use the JSON configuration syntax as shown below.
```mermaid-example
sequenceDiagram
participant Alice@{ "type" : "collections" }
participant Bob
Alice->>Bob: Collections request
Bob->>Alice: Collections response
```
### Queue
If you want to use the queue symbol for a participant, use the JSON configuration syntax as shown below.
```mermaid-example
sequenceDiagram
participant Alice@{ "type" : "queue" }
participant Bob
Alice->>Bob: Queue message
Bob->>Alice: Queue response
```
### Aliases
The actor can have a convenient identifier and a descriptive label.
```mermaid-example
sequenceDiagram
participant A as Alice
participant J as John
A->>J: Hello John, how are you?
J->>A: Great!
```
### Actor Creation and Destruction (v10.3.0+)
It is possible to create and destroy actors by messages. To do so, add a create or destroy directive before the message.
```
create participant B
A --> B: Hello
```
Create directives support actor/participant distinction and aliases. The sender or the recipient of a message can be destroyed but only the recipient can be created.
```mermaid-example
sequenceDiagram
Alice->>Bob: Hello Bob, how are you ?
Bob->>Alice: Fine, thank you. And you?
create participant Carl
Alice->>Carl: Hi Carl!
create actor D as Donald
Carl->>D: Hi!
destroy Carl
Alice-xCarl: We are too many
destroy Bob
Bob->>Alice: I agree
```
#### Unfixable actor/participant creation/deletion error
If an error of the following type occurs when creating or deleting an actor/participant:
> The destroyed participant **participant-name** does not have an associated destroying message after its declaration. Please check the sequence diagram.
And fixing diagram code does not get rid of this error and rendering of all other diagrams results in the same error, then you need to update the mermaid version to (v10.7.0+).
### Grouping / Box
The actor(s) can be grouped in vertical boxes. You can define a color (if not, it will be transparent) and/or a descriptive label using the following notation:
```
box Aqua Group Description
... actors ...
end
box Group without description
... actors ...
end
box rgb(33,66,99)
... actors ...
end
box rgba(33,66,99,0.5)
... actors ...
end
```
```note
If your group name is a color you can force the color to be transparent:
```
```
box transparent Aqua
... actors ...
end
```
```mermaid-example
sequenceDiagram
box Purple Alice & John
participant A
participant J
end
box Another Group
participant B
participant C
end
A->>J: Hello John, how are you?
J->>A: Great!
A->>B: Hello Bob, how is Charley?
B->>C: Hello Charley, how are you?
```
## Messages
Messages can be of two displayed either solid or with a dotted line.
```
[Actor][Arrow][Actor]:Message text
```
Lines can be solid or dotted, and can end with various types of arrowheads, crosses, or open arrows.
#### Supported Arrow Types
**Standard Arrow Types**
| Type | Description |
| -------- | ---------------------------------------------------- |
| `->` | Solid line without arrow |
| `-->` | Dotted line without arrow |
| `->>` | Solid line with arrowhead |
| `-->>` | Dotted line with arrowhead |
| `<<->>` | Solid line with bidirectional arrowheads (v11.0.0+) |
| `<<-->>` | Dotted line with bidirectional arrowheads (v11.0.0+) |
| `-x` | Solid line with a cross at the end |
| `--x` | Dotted line with a cross at the end |
| `-)` | Solid line with an open arrow at the end (async) |
| `--)` | Dotted line with a open arrow at the end (async) |
**Half-Arrows (v<MERMAID_RELEASE_VERSION>+)**
The following half-arrow types are supported for more expressive sequence diagrams. Both solid and dotted variants are available by increasing the number of dashes (`-` → `--`).
---
| Type | Description |
| ------- | ---------------------------------------------------- |
| `-\|\` | Solid line with top half arrowhead |
| `--\|\` | Dotted line with top half arrowhead |
| `-\|/` | Solid line with bottom half arrowhead |
| `--\|/` | Dotted line with bottom half arrowhead |
| `/\|-` | Solid line with reverse top half arrowhead |
| `/\|--` | Dotted line with reverse top half arrowhead |
| `\\-` | Solid line with reverse bottom half arrowhead |
| `\\--` | Dotted line with reverse bottom half arrowhead |
| `-\\` | Solid line with top stick half arrowhead |
| `--\\` | Dotted line with top stick half arrowhead |
| `-//` | Solid line with bottom stick half arrowhead |
| `--//` | Dotted line with bottom stick half arrowhead |
| `//-` | Solid line with reverse top stick half arrowhead |
| `//--` | Dotted line with reverse top stick half arrowhead |
| `\\-` | Solid line with reverse bottom stick half arrowhead |
| `\\--` | Dotted line with reverse bottom stick half arrowhead |
## Central Connections (v<MERMAID_RELEASE_VERSION>+)
Mermaid sequence diagrams support **central lifeline connections** using a `()`.
This is useful to represent messages or signals that connect to a central point, rather than from one actor directly to another.
To indicate a central connection, append `()` to the arrow syntax.
#### Basic Syntax
```mermaid-example
sequenceDiagram
participant Alice
participant John
Alice->>()John: Hello John
Alice()->>John: How are you?
John()->>()Alice: Great!
```
## Activations
It is possible to activate and deactivate an actor. (de)activation can be dedicated declarations:
```mermaid-example
sequenceDiagram
Alice->>John: Hello John, how are you?
activate John
John-->>Alice: Great!
deactivate John
```
There is also a shortcut notation by appending `+`/`-` suffix to the message arrow:
```mermaid-example
sequenceDiagram
Alice->>+John: Hello John, how are you?
John-->>-Alice: Great!
```
Activations can be stacked for same actor:
```mermaid-example
sequenceDiagram
Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
John-->>-Alice: I feel great!
```
## Notes
It is possible to add notes to a sequence diagram. This is done by the notation
Note [ right of | left of | over ] [Actor]: Text in note content
See the example below:
```mermaid-example
sequenceDiagram
participant John
Note right of John: Text in note
```
It is also possible to create notes spanning two participants:
```mermaid-example
sequenceDiagram
Alice->John: Hello John, how are you?
Note over Alice,John: A typical interaction
```
## Line breaks
Line break can be added to Note and Message:
```mermaid-example
sequenceDiagram
Alice->John: Hello John,<br/>how are you?
Note over Alice,John: A typical interaction<br/>But now in two lines
```
Line breaks in Actor names requires aliases:
```mermaid-example
sequenceDiagram
participant Alice as Alice<br/>Johnson
Alice->John: Hello John,<br/>how are you?
Note over Alice,John: A typical interaction<br/>But now in two lines
```
## Loops
It is possible to express loops in a sequence diagram. This is done by the notation
```
loop Loop text
... statements ...
end
```
See the example below:
```mermaid-example
sequenceDiagram
Alice->John: Hello John, how are you?
loop Every minute
John-->Alice: Great!
end
```
## Alt
It is possible to express alternative paths in a sequence diagram. This is done by the notation
```
alt Describing text
... statements ...
else
... statements ...
end
```
or if there is sequence that is optional (if without else).
```
opt Describing text
... statements ...
end
```
See the example below:
```mermaid-example
sequenceDiagram
Alice->>Bob: Hello Bob, how are you?
alt is sick
Bob->>Alice: Not so good :(
else is well
Bob->>Alice: Feeling fresh like a daisy
end
opt Extra response
Bob->>Alice: Thanks for asking
end
```
## Parallel
It is possible to show actions that are happening in parallel.
This is done by the notation
```
par [Action 1]
... statements ...
and [Action 2]
... statements ...
and [Action N]
... statements ...
end
```
See the example below:
```mermaid-example
sequenceDiagram
par Alice to Bob
Alice->>Bob: Hello guys!
and Alice to John
Alice->>John: Hello guys!
end
Bob-->>Alice: Hi Alice!
John-->>Alice: Hi Alice!
```
It is also possible to nest parallel blocks.
```mermaid-example
sequenceDiagram
par Alice to Bob
Alice->>Bob: Go help John
and Alice to John
Alice->>John: I want this done today
par John to Charlie
John->>Charlie: Can we do this today?
and John to Diana
John->>Diana: Can you help us today?
end
end
```
## Critical Region
It is possible to show actions that must happen automatically with conditional handling of circumstances.
This is done by the notation
```
critical [Action that must be performed]
... statements ...
option [Circumstance A]
... statements ...
option [Circumstance B]
... statements ...
end
```
See the example below:
```mermaid-example
sequenceDiagram
critical Establish a connection to the DB
Service-->DB: connect
option Network timeout
Service-->Service: Log error
option Credentials rejected
Service-->Service: Log different error
end
```
It is also possible to have no options at all
```mermaid-example
sequenceDiagram
critical Establish a connection to the DB
Service-->DB: connect
end
```
This critical block can also be nested, equivalently to the `par` statement as seen above.
## Break
It is possible to indicate a stop of the sequence within the flow (usually used to model exceptions).
This is done by the notation
```
break [something happened]
... statements ...
end
```
See the example below:
```mermaid-example
sequenceDiagram
Consumer-->API: Book something
API-->BookingService: Start booking process
break when the booking process fails
API-->Consumer: show failure
end
API-->BillingService: Start billing process
```
## Background Highlighting
It is possible to highlight flows by providing colored background rects. This is done by the notation
```
rect COLOR
... content ...
end
```
The colors are defined using rgb and rgba syntax.
```
rect rgb(0, 255, 0)
... content ...
end
```
```
rect rgba(0, 0, 255, .1)
... content ...
end
```
See the examples below:
```mermaid-example
sequenceDiagram
participant Alice
participant John
rect rgb(191, 223, 255)
note right of Alice: Alice calls John.
Alice->>+John: Hello John, how are you?
rect rgb(200, 150, 255)
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
end
John-->>-Alice: I feel great!
end
Alice ->>+ John: Did you want to go to the game tonight?
John -->>- Alice: Yeah! See you there.
```
## Comments
Comments can be entered within a sequence diagram, which will be ignored by the parser. Comments need to be on their own line, and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax
```mermaid-example
sequenceDiagram
Alice->>John: Hello John, how are you?
%% this is a comment
John-->>Alice: Great!
```
## Entity codes to escape characters
It is possible to escape characters using the syntax exemplified here.
```mermaid-example
sequenceDiagram
A->>B: I #9829; you!
B->>A: I #9829; you #infin; times more!
```
Numbers given are base 10, so `#` can be encoded as `#35;`. It is also supported to use HTML character names.
Because semicolons can be used instead of line breaks to define the markup, you need to use `#59;` to include a semicolon in message text.
## sequenceNumbers
It is possible to get a sequence number attached to each arrow in a sequence diagram. This can be configured when adding mermaid to the website as shown below:
```html
<script>
mermaid.initialize({ sequence: { showSequenceNumbers: true } });
</script>
```
It can also be turned on via the diagram code as in the diagram:
```mermaid-example
sequenceDiagram
autonumber
Alice->>John: Hello John, how are you?
loop HealthCheck
John->>John: Fight against hypochondria
end
Note right of John: Rational thoughts!
John-->>Alice: Great!
John->>Bob: How about you?
Bob-->>John: Jolly good!
```
## Actor Menus
Actors can have popup-menus containing individualized links to external pages. For example, if an actor represented a web service, useful links might include a link to the service health dashboard, repo containing the code for the service, or a wiki page describing the service.
This can be configured by adding one or more link lines with the format:
```
link <actor>: <link-label> @ <link-url>
```
```mermaid
sequenceDiagram
participant Alice
participant John
link Alice: Dashboard @ https://dashboard.contoso.com/alice
link Alice: Wiki @ https://wiki.contoso.com/alice
link John: Dashboard @ https://dashboard.contoso.com/john
link John: Wiki @ https://wiki.contoso.com/john
Alice->>John: Hello John, how are you?
John-->>Alice: Great!
Alice-)John: See you later!
```
#### Advanced Menu Syntax
There is an advanced syntax that relies on JSON formatting. If you are comfortable with JSON format, then this exists as well.
This can be configured by adding the links lines with the format:
```
links <actor>: <json-formatted link-name link-url pairs>
```
An example is below:
```mermaid-example
sequenceDiagram
participant Alice
participant John
links Alice: {"Dashboard": "https://dashboard.contoso.com/alice", "Wiki": "https://wiki.contoso.com/alice"}
links John: {"Dashboard": "https://dashboard.contoso.com/john", "Wiki": "https://wiki.contoso.com/john"}
Alice->>John: Hello John, how are you?
John-->>Alice: Great!
Alice-)John: See you later!
```
## Styling
Styling of a sequence diagram is done by defining a number of css classes. During rendering these classes are extracted from the file located at src/themes/sequence.scss
### Classes used
| Class | Description |
| -------------- | -------------------------------------------------------------- |
| actor | Styles for the actor box. |
| actor-top | Styles for the actor figure/ box at the top of the diagram. |
| actor-bottom | Styles for the actor figure/ box at the bottom of the diagram. |
| text.actor | Styles for text of all of the actors. |
| text.actor-box | Styles for text of the actor box. |
| text.actor-man | Styles for text of the actor figure. |
| actor-line | The vertical line for an actor. |
| messageLine0 | Styles for the solid message line. |
| messageLine1 | Styles for the dotted message line. |
| messageText | Defines styles for the text on the message arrows. |
| labelBox | Defines styles label to left in a loop. |
| labelText | Styles for the text in label for loops. |
| loopText | Styles for the text in the loop box. |
| loopLine | Defines styles for the lines in the loop box. |
| note | Styles for the note box. |
| noteText | Styles for the text on in the note boxes. |
### Sample stylesheet
```css
body {
background: white;
}
.actor {
stroke: #ccccff;
fill: #ececff;
}
text.actor {
fill: black;
stroke: none;
font-family: Helvetica;
}
.actor-line {
stroke: grey;
}
.messageLine0 {
stroke-width: 1.5;
stroke-dasharray: '2 2';
marker-end: 'url(#arrowhead)';
stroke: black;
}
.messageLine1 {
stroke-width: 1.5;
stroke-dasharray: '2 2';
stroke: black;
}
#arrowhead {
fill: black;
}
.messageText {
fill: black;
stroke: none;
font-family: 'trebuchet ms', verdana, arial;
font-size: 14px;
}
.labelBox {
stroke: #ccccff;
fill: #ececff;
}
.labelText {
fill: black;
stroke: none;
font-family: 'trebuchet ms', verdana, arial;
}
.loopText {
fill: black;
stroke: none;
font-family: 'trebuchet ms', verdana, arial;
}
.loopLine {
stroke-width: 2;
stroke-dasharray: '2 2';
marker-end: 'url(#arrowhead)';
stroke: #ccccff;
}
.note {
stroke: #decc93;
fill: #fff5ad;
}
.noteText {
fill: black;
stroke: none;
font-family: 'trebuchet ms', verdana, arial;
font-size: 14px;
}
```
## Configuration
It is possible to adjust the margins for rendering the sequence diagram.
This is done by defining `mermaid.sequenceConfig` or by the CLI to use a json file with the configuration.
How to use the CLI is described in the [mermaidCLI](../config/mermaidCLI.md) page.
`mermaid.sequenceConfig` can be set to a JSON string with config parameters or the corresponding object.
```javascript
mermaid.sequenceConfig = {
diagramMarginX: 50,
diagramMarginY: 10,
boxTextMargin: 5,
noteMargin: 10,
messageMargin: 35,
mirrorActors: true,
};
```
### Possible configuration parameters:
| Parameter | Description | Default value |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |
| mirrorActors | Turns on/off the rendering of actors below the diagram as well as above it | false |
| bottomMarginAdj | Adjusts how far down the graph ended. Wide borders styles with css could generate unwanted clipping which is why this config param exists. | 1 |
| actorFontSize | Sets the font size for the actor's description | 14 |
| actorFontFamily | Sets the font family for the actor's description | "Open Sans", sans-serif |
| actorFontWeight | Sets the font weight for the actor's description | "Open Sans", sans-serif |
| noteFontSize | Sets the font size for actor-attached notes | 14 |
| noteFontFamily | Sets the font family for actor-attached notes | "trebuchet ms", verdana, arial |
| noteFontWeight | Sets the font weight for actor-attached notes | "trebuchet ms", verdana, arial |
| noteAlign | Sets the text alignment for text in actor-attached notes | center |
| messageFontSize | Sets the font size for actor<->actor messages | 16 |
| messageFontFamily | Sets the font family for actor<->actor messages | "trebuchet ms", verdana, arial |
| messageFontWeight | Sets the font weight for actor<->actor messages | "trebuchet ms", verdana, arial |