npm package: @pilaniaanand/mermaid-codegen
Description: Generate beautiful Mermaid diagrams from source code with a built-in web UI
Author: Anand Pilania
Latest version: 0.0.1

# Mermaid CodeGen CLI 🎨

Generate beautiful Mermaid diagrams from your source code automatically. Supports JavaScript, TypeScript, React, Vue, PHP, Laravel, and more!

## ✨ Features

- 🔍 **Multi-language Support**: JavaScript, TypeScript, React, Vue, PHP, Laravel
- 🎨 **Beautiful Diagrams**: Flowcharts, Class Diagrams, Sequence Diagrams, Architecture Views
- 🖥️ **Built-in Web UI**: React-based editor with live preview (powered by shadcn/ui)
- 📁 **File System Integration**: Browser-based file management
- 🔄 **Hot Reload**: Watch mode for automatic diagram regeneration
- 🌈 **Multiple Themes**: Default, Dark, Forest, Neutral
- 📦 **Multiple Formats**: Export as Mermaid, SVG, or PNG
- 🔧 **Project Isolation**: Per-project or global configuration
- 🚀 **Cross-Platform**: Windows, macOS, Linux support

## 🚀 Installation

### Global Installation

```bash
npm install -g @mermaid-codegen/cli
# or
yarn global add @mermaid-codegen/cli
```

### Local Installation (per-project)

```bash
npm install --save-dev @mermaid-codegen/cli
# or
yarn add -D @mermaid-codegen/cli
```

## 📖 Quick Start

### 1. Initialize in Your Project

```bash
# Navigate to your project
cd /path/to/your/project

# Initialize mermaid-codegen
mcg init

# Or for global configuration
mcg init --global
```

This creates a `.mermaid-codegen.json` configuration file.

### 2. Generate Diagrams

```bash
# Generate diagrams from current directory
mcg generate

# Generate from specific directory
mcg generate --dir ./src

# Watch for changes and auto-regenerate
mcg generate --watch

# Generate only specific diagram types
mcg generate --type flowchart class

# Specify output formats
mcg generate --format svg png
```

### 3. Launch Web UI

```bash
# Start the web UI on default port (3456)
mcg serve

# Use custom port
mcg serve --port 8080

# Auto-open browser
mcg serve --open
```

## 🎯 CLI Commands

### `mcg init`

Initialize mermaid-codegen configuration.

```bash
mcg init [options]

Options:
  -g, --global    Initialize globally (default: project-level)
```

### `mcg generate`

Generate Mermaid diagrams from source code.

```bash
mcg generate [options]

Options:
  -d, --dir <directory>          Source directory (default: ".")
  -o, --output <directory>       Output directory (default: "./mermaid-diagrams")
  -w, --watch                    Watch for file changes
  -f, --format <format>          Output format: mermaid|svg|png|all (default: "all")
  -t, --type <types...>          Diagram types (default: ["flowchart", "class", "sequence"])
  --include <patterns...>        File patterns to include
  --exclude <patterns...>        File patterns to exclude
```

**Examples:**

```bash
# Generate all diagram types in all formats
mcg generate

# Only generate flowcharts as SVG
mcg generate --type flowchart --format svg

# Generate from src directory, exclude tests
mcg generate --dir ./src --exclude "**/*.test.js" "**/*.spec.ts"

# Watch mode with custom output
mcg generate --watch --output ./docs/diagrams
```

### `mcg serve`

Start the web UI server.

```bash
mcg serve [options]

Options:
  -p, --port <port>              Server port (default: 3456)
  -o, --open                     Open browser automatically
  -d, --diagrams <directory>     Diagrams directory (default: "./mermaid-diagrams")
```

**Examples:**

```bash
# Start on default port
mcg serve

# Custom port with auto-open
mcg serve --port 8080 --open

# Serve diagrams from custom directory
mcg serve --diagrams ./docs/diagrams
```

### `mcg config`

Manage configuration.

```bash
mcg config [options]

Options:
  --show     Show current configuration
  --reset    Reset to default configuration
```

## ⚙️ Configuration

### Configuration File: `.mermaid-codegen.json`

```json
{
  "outputDir": "./mermaid-diagrams",
  "formats": ["mermaid", "svg", "png"],
  "diagramTypes": ["flowchart", "class", "sequence"],
  "include": ["**/*.{js,ts,jsx,tsx,php,vue}"],
  "exclude": ["node_modules/**", "dist/**", "build/**", "vendor/**"],
  "styling": {
    "theme": "default"
  },
  "analysis": {
    "maxDepth": 5,
    "includePrivate": false,
    "includeTests": true
  },
  "server": {
    "port": 3456,
    "host": "0.0.0.0"
  }
}
```

### Configuration Options

- **outputDir**: Where to save generated diagrams
- **formats**: Output formats (`mermaid`, `svg`, `png`)
- **diagramTypes**: Types to generate (`flowchart`, `class`, `sequence`, `architecture`)
- **include**: File patterns to analyze
- **exclude**: File patterns to ignore
- **styling.theme**: Mermaid theme (`default`, `dark`, `forest`, `neutral`)
- **analysis.maxDepth**: Maximum analysis depth for nested structures
- **analysis.includePrivate**: Include private methods/properties
- **analysis.includeTests**: Analyze test files
- **server.port**: Web UI server port
- **server.host**: Server host address

## 🖥️ Web UI Features

The built-in web UI provides a comprehensive diagram management interface:

### Features

1. **Diagram Browser**
   - View all generated diagrams
   - Filter by type and date
   - Quick search

2. **Live Editor**
   - Split view: Code + Preview
   - Syntax highlighting
   - Real-time rendering
   - Multiple themes

3. **Export Options**
   - Download as SVG
   - Download as PNG
   - Copy to clipboard
   - Share link

4. **File Management**
   - Create new diagrams
   - Edit existing diagrams
   - Delete diagrams
   - Real-time sync via WebSocket

5. **Keyboard Shortcuts**
   - `Ctrl/Cmd + S`: Save
   - `Ctrl/Cmd + E`: Toggle editor
   - `Ctrl/Cmd + P`: Toggle preview

## 📊 Diagram Types

### Flowchart Diagrams

Generated for functions and control flow.

```javascript
// Your code
async function processOrder(orderId) {
  const order = await fetchOrder(orderId);
  if (order.isValid) {
    await fulfillOrder(order);
  } else {
    await cancelOrder(order);
  }
}
```

Generates:
```mermaid
graph TD
    Start([processOrder]) --> Fetch[Fetch Order]
    Fetch --> Valid{Is Valid?}
    Valid -->|Yes| Fulfill[Fulfill Order]
    Valid -->|No| Cancel[Cancel Order]
    Fulfill --> End([End])
    Cancel --> End
```

### Class Diagrams

Generated for classes and their relationships.

```javascript
// Your code
class Animal {
  constructor(name) {
    this.name = name;
  }

  makeSound() {}
}

class Dog extends Animal {
  bark() {
    console.log('Woof!');
  }
}
```

Generates:
```mermaid
classDiagram
    class Animal {
        +String name
        +makeSound() void
    }
    class Dog {
        +bark() void
    }
    Animal <|-- Dog
```

### Sequence Diagrams

Generated for function call sequences.

```javascript
// Your code
class UserService {
  async login(credentials) {
    const user = await this.authenticate(credentials);
    await this.createSession(user);
    return user;
  }
}
```

Generates:
```mermaid
sequenceDiagram
    participant User
    participant System
    User->>+System: login(credentials)
    System->>System: authenticate
    System->>System: createSession
    System-->>-User: user
```

### Architecture Diagrams

Shows project structure and dependencies.

```
src/
├── components/
│   ├── Button.tsx
│   └── Card.tsx
├── services/
│   └── api.ts
└── utils/
    └── helpers.ts
```

Generates dependency graph showing module relationships.

## 🔧 Advanced Usage

### Custom File Patterns

```bash
# Only analyze React components
mcg generate --include "**/*.jsx" "**/*.tsx"

# Exclude vendor and test files
mcg generate --exclude "vendor/**" "**/*.test.*"
```

### Watch Mode

Perfect for development:

```bash
# Watch and regenerate on changes
mcg generate --watch

# Combine with web UI
mcg generate --watch &
mcg serve --open
```

### CI/CD Integration

```yaml
# GitHub Actions Example
name: Generate Diagrams

on: [push]

jobs:
  diagrams:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
      - run: npm install -g @mermaid-codegen/cli
      - run: mcg generate
      - uses: actions/upload-artifact@v2
        with:
          name: diagrams
          path: mermaid-diagrams/
```

## 🌐 File System Access API

The web UI uses the File System Access API for seamless file management:

```javascript
// Automatically handles:
- Reading diagram files
- Saving changes
- Creating new diagrams
- Exporting to various formats
```

**Browser Compatibility:**
- Chrome/Edge: Full support
- Firefox: Partial support
- Safari: Limited support

## 🎨 Theming

### Available Themes

1. **Default**: Clean, professional look
2. **Dark**: Dark mode for late-night coding
3. **Forest**: Green, nature-inspired palette
4. **Neutral**: Minimalist grayscale

### Custom Styling

Add custom styles in your config:

```json
{
  "styling": {
    "theme": "default",
    "customStyles": {
      "primaryColor": "#3b82f6",
      "secondaryColor": "#8b5cf6",
      "fontFamily": "Inter, sans-serif"
    }
  }
}
```

## 🚧 Supported Languages

| Language   | Support Level | Features                      |
| ---------- | ------------- | ----------------------------- |
| JavaScript | ✅ Full        | Classes, functions, imports   |
| TypeScript | ✅ Full        | Types, interfaces, decorators |
| React      | ✅ Full        | Components, hooks, props      |
| Vue        | ✅ Full        | Components, composables       |
| PHP        | 🟡 Partial     | Classes, methods, namespaces  |
| Laravel    | 🟡 Partial     | Controllers, models, routes   |

## 📝 Examples

### Example 1: React Project

```bash
cd my-react-app
mcg init
mcg generate --dir ./src --type flowchart class
mcg serve --open
```

### Example 2: PHP/Laravel Project

```bash
cd my-laravel-app
mcg init
mcg generate --dir ./app --include "**/*.php" --exclude "vendor/**"
mcg serve
```

### Example 3: Monorepo

```bash
cd my-monorepo
mcg generate --dir ./packages --output ./docs/diagrams
```

## 🐛 Troubleshooting

### Diagrams Not Generating?

1. Check file patterns: `mcg config --show`
2. Verify source directory: `ls -la src/`
3. Check for syntax errors in source files

### Web UI Not Starting?

1. Check port availability: `lsof -i :3456`
2. Try different port: `mcg serve --port 8080`
3. Check firewall settings

### SVG/PNG Export Failing?

1. Ensure Puppeteer is installed: `npm list puppeteer`
2. Install system dependencies (Linux):
   ```bash
   sudo apt-get install -y chromium-browser
   ```

## 🤝 Contributing

Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md).

## 📄 License

MIT © Mermaid CodeGen

## 🔗 Links

- [Documentation](https://github.com/anandpilania/mermaid-codegen)
- [Examples](https://github.com/anandpilania/mermaid-codegen/examples)
- [Issue Tracker](https://github.com/anandpilania/mermaid-codegen/issues)

## ⭐ Show Your Support

If you find this tool helpful, please consider giving it a star on GitHub!

---

Made with ❤️ by the Mermaid CodeGen team