Skip to main content
Background Image
  1. Projects/

Mermaid-Sonar - Diagram Complexity Analyzer

Author
Glen Baker
Building tech startups and open source tooling
Table of Contents

Detect hidden complexity in your Mermaid diagrams before they confuse readers

npm version
GitHub

Links: GitHub | npm

Overview
#

Mermaid-sonar is a complexity analyzer and readability linter for Mermaid diagrams in documentation. While traditional Mermaid validation tools only check syntax, mermaid-sonar validates both syntax and readability using research-backed metrics from cognitive load studies and graph theory.

What it does:

  • Syntax validation - Uses the official Mermaid parser to catch rendering errors
  • Complexity analysis - Measures nodes, edges, density, branching, cyclomatic complexity
  • Research-backed thresholds - Based on cognitive load research (50/100 node limits)
  • Actionable recommendations - Specific fixes like “use LR layout” or “split into sub-diagrams”
  • Machine-readable output - JSON format enables automated fixes in CI/CD workflows

Read more: Why mermaid-sonar exists and how it solves AI documentation challenges

Key Features
#

Static Analysis Engine
#

Pure Static Analysis: No browser, no rendering, no dependencies. Parses diagram source code and calculates graph metrics:

  • Node count: Total diagram elements
  • Edge count: Total connections
  • Graph density: edges / (nodes × (nodes-1))
  • Max branch width: Largest number of parallel branches
  • Average degree: Average connections per node
  • Cyclomatic complexity: Code complexity metric adapted for diagrams
# Fast analysis without rendering
mermaid-sonar docs/ --strict

Research-Backed Rules
#

All thresholds based on published research, not arbitrary limits:

RuleThresholdResearch Basis
max-nodes50 (high-density)
100 (low-density)
Cognitive load research
max-edges100Mermaid O(n²) docs
graph-density0.3Graph theory best practices
cyclomatic-complexity15Software engineering standards
max-branch-width8Visual hierarchy research

Actionable Feedback
#

Instead of just “too complex,” provides specific fixes:

❌ docs/architecture.md:42
   Wide tree diagram with 12 parallel branches (>8 max)
   → Consider using 'graph LR' or split into multiple diagrams

⚠️  docs/workflow.md:156
   Complex diagram with 85 nodes
   → Consider breaking into focused sub-diagrams

✓ docs/overview.md:15 - Valid and readable

Each issue includes:

  • Severity: error, warning, or info
  • Location: File path and line number
  • Specific problem: What rule was violated and by how much
  • Fix suggestion: Concrete action to resolve the issue
  • Research citation: Link to supporting research (when applicable)

Multiple Output Formats
#

Different formats for different use cases:

# Terminal output with colors
mermaid-sonar docs/

# JSON for CI/CD integration
mermaid-sonar --format json docs/ > report.json

# Markdown report
mermaid-sonar --format markdown -o report.md docs/

# GitHub-flavored markdown with collapsible sections
mermaid-sonar --format github docs/

# JUnit XML for test integration
mermaid-sonar --format junit -o junit.xml docs/

CI/CD Integration
#

Designed for automated workflows with proper exit codes:

  • 0: All diagrams valid and readable
  • 1: Errors or warnings (with --strict)
  • 2: Tool execution error

GitHub Actions Example:

name: Validate Diagrams
on: [pull_request]
jobs:
  validate-diagrams:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npx mermaid-sonar docs/ --strict

Real-World Impact
#

When run on AI-generated documentation with 87 diagrams:

  • Syntax errors found: 8 diagrams (build failures prevented)
  • Complexity issues found: 12 diagrams (readability improved)
  • Total issues caught: 20 out of 87 diagrams

See the full case study for details.

How It Works
#

1. Diagram Discovery
#

Scans markdown files for Mermaid code blocks (```mermaid ... ```)

2. Syntax Validation
#

Parses with official Mermaid parser, reports exact errors:

❌ docs/example.md:3
   Syntax error: Parse error on line 2:
   A B
   ---^
   Expecting 'SEMI', 'NEWLINE', 'EOF', 'AMP', 'START_LINK', 'LINK', got 'ALPHA'

3. Complexity Analysis
#

Calculates graph metrics and checks against thresholds:

{
  "metrics": {
    "nodeCount": 55,
    "edgeCount": 78,
    "graphDensity": 0.026,
    "maxBranchWidth": 12,
    "averageDegree": 2.84
  },
  "issues": [
    {
      "rule": "max-branch-width",
      "severity": "error",
      "message": "Wide tree diagram with 12 parallel branches (>8 max)",
      "suggestion": "Consider using 'graph LR' or split into multiple diagrams"
    }
  ]
}

4. Actionable Output
#

Reports issues with context and suggestions for fixing.

Technical Stack
#

  • Language: TypeScript (npm ecosystem integration)
  • Parser: Official Mermaid.js parser (100% compatibility)
  • Analysis: Graph theory metrics + cognitive load research
  • Architecture: Pure static analysis (no rendering dependencies)
  • Performance: Analyzes hundreds of diagrams in seconds
  • Integration: JSON output for CI/CD automation

Configuration & Customization
#

Create .sonarrc.json to adjust thresholds:

{
  "rules": {
    "max-nodes": {
      "enabled": true,
      "high-density": 50,
      "low-density": 100,
      "severity": "error"
    },
    "max-edges": {
      "enabled": true,
      "limit": 100,
      "severity": "warning"
    },
    "graph-density": {
      "enabled": true,
      "threshold": 0.3,
      "severity": "warning"
    },
    "cyclomatic-complexity": {
      "enabled": true,
      "limit": 15,
      "severity": "warning"
    },
    "max-branch-width": {
      "enabled": true,
      "limit": 8,
      "severity": "error"
    }
  }
}

You can:

  • Enable/disable specific rules
  • Adjust thresholds for your use case
  • Set severity levels (error, warning, info)
  • Add custom rules (via TypeScript API)

Installation
#

# Global installation
npm install -g mermaid-sonar

# Project dependency
npm install --save-dev mermaid-sonar

# Using npx (no installation)
npx mermaid-sonar docs/

Quick Start
#

# Analyze diagrams in your docs
mermaid-sonar docs/

# With strict mode (fail on warnings)
mermaid-sonar docs/ --strict

# Custom config
mermaid-sonar --config .sonarrc.json docs/

# JSON output for CI
mermaid-sonar --format json docs/ > report.json

Commands
#

Basic Analysis
#

# Analyze single file
mermaid-sonar README.md

# Analyze multiple files
mermaid-sonar README.md docs/architecture.md

# Analyze directory recursively
mermaid-sonar -r docs/

# Glob patterns
mermaid-sonar "docs/**/*.md"

CI/CD Usage
#

# Strict mode - fail on any warning
mermaid-sonar --strict docs/

# Allow up to 5 warnings
mermaid-sonar --max-warnings 5 docs/

# Quiet mode for CI logs
mermaid-sonar --quiet --format json -o report.json docs/

# Verbose mode for debugging
mermaid-sonar --verbose docs/

Output Formats
#

# JSON output for CI/CD
mermaid-sonar --format json docs/ > report.json

# Markdown report
mermaid-sonar --format markdown -o report.md docs/

# GitHub-flavored markdown
mermaid-sonar --format github docs/

# JUnit XML for test integration
mermaid-sonar --format junit -o junit.xml docs/

Integration with Prodigy Workflows
#

Mermaid-sonar integrates seamlessly with Prodigy AI workflows:

# Validate diagrams in documentation workflow
- shell: "mermaid-sonar $DOCS_DIR --strict"
  on_failure:
    claude: "/prodigy-fix-mermaid-diagrams ${shell.output}"

The workflow automatically:

  1. Detects syntax and complexity issues
  2. Provides quantitative feedback to AI agents
  3. Agents fix issues based on specific recommendations
  4. Re-validates until all diagrams pass

See the MkDocs drift automation workflow for a complete example.

Use Cases
#

  • AI-Generated Documentation - Automated quality gates for agent-created diagrams
  • PR Review Automation - Enforce diagram standards in pull requests
  • Large Documentation Sites - Validate 100+ diagrams in seconds
  • CI/CD Pipelines - Fast validation without rendering overhead
  • Documentation Maintenance - Track diagram quality over time

Comparison with Other Tools
#

ToolSyntax CheckComplexity AnalysisStatic AnalysisCI/CD Ready
@mermaid-js/mermaid-cli❌ (renders)⚠️ (slow)
mermaid.parse()
mermaid-sonar

Key differences:

  • mermaid-cli: Full rendering validation but requires browser, slow for CI/CD
  • mermaid.parse(): Fast syntax checking but no complexity analysis
  • mermaid-sonar: Syntax + complexity + readability, optimized for automation

Status
#

Production-ready, actively maintained, available on npm.

Current capabilities:

  • Syntax validation with official Mermaid parser
  • Research-backed complexity rules
  • Multiple output formats (console, JSON, markdown, GitHub, JUnit)
  • CI/CD integration with proper exit codes
  • Configurable thresholds and rules

Links#

Related

Debtmap - Rust Technical Debt Analyzer
Prodigy - AI Workflow Orchestration for Claude
Transforming ripgrep's Documentation with AI Automation and MkDocs
Automating Documentation Maintenance with Prodigy: A Real-World Case Study