CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mermaid-js--mermaid-cli

Command-line interface for converting Mermaid diagrams to SVG, PNG, and PDF formats

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

nodejs-api.mddocs/

Node.js API

The Node.js API provides programmatic access to Mermaid diagram rendering capabilities. It offers both high-level functions for common operations and low-level functions for fine-grained control over the rendering process.

Capabilities

High-Level Rendering Function

The primary function for rendering Mermaid diagrams from Node.js applications.

/**
 * Renders a mermaid diagram or processes a markdown file
 * @param input - Input file path, undefined for stdin
 * @param output - Output file path or "/dev/stdout" for stdout
 * @param options - Optional configuration
 * @returns Promise that resolves when rendering is complete
 */
async function run(
  input: string | undefined,
  output: string,
  options?: RunOptions
): Promise<void>;

interface RunOptions {
  puppeteerConfig?: LaunchOptions;
  quiet?: boolean;
  outputFormat?: "svg" | "png" | "pdf";
  parseMMDOptions?: ParseMDDOptions;
  artefacts?: string;
}

Usage Examples:

import { run } from "@mermaid-js/mermaid-cli";

// Basic diagram rendering
await run("diagram.mmd", "output.svg");

// Render to PNG with custom options
await run("flowchart.mmd", "flowchart.png", {
  outputFormat: "png",
  parseMMDOptions: {
    backgroundColor: "transparent",
    mermaidConfig: { theme: "dark" }
  }
});

// Process markdown file
await run("README.md", "README-processed.md", {
  artefacts: "./diagrams"
});

// Read from stdin equivalent (input = undefined)
await run(undefined, "output.svg", {
  quiet: true
});

// Render with custom Puppeteer config
await run("input.mmd", "output.pdf", {
  puppeteerConfig: {
    headless: "shell",
    args: ["--no-sandbox"]
  },
  parseMMDOptions: {
    pdfFit: true
  }
});

Low-Level Rendering Function

Direct rendering function that works with an existing Puppeteer browser instance for better performance when rendering multiple diagrams.

/**
 * Render a single mermaid diagram using an existing browser instance
 * @param browser - Puppeteer browser or browser context
 * @param definition - Mermaid diagram definition string
 * @param outputFormat - Output format
 * @param options - Rendering options
 * @returns Promise with rendered data and metadata
 */
async function renderMermaid(
  browser: Browser | BrowserContext,
  definition: string,
  outputFormat: "svg" | "png" | "pdf",
  options?: ParseMDDOptions
): Promise<RenderResult>;

interface RenderResult {
  title: string | null;    // SVG title element content
  desc: string | null;     // SVG description element content  
  data: Uint8Array;        // Rendered diagram data
}

Usage Examples:

import { renderMermaid } from "@mermaid-js/mermaid-cli";
import puppeteer from "puppeteer";
import fs from "fs/promises";

const browser = await puppeteer.launch({ headless: "shell" });

try {
  // Render multiple diagrams with same browser instance
  const diagram1 = `
    graph TD
    A[Start] --> B[Process]
    B --> C[End]
  `;
  
  const diagram2 = `
    sequenceDiagram
    Alice->>Bob: Hello
    Bob-->>Alice: Hi there
  `;

  const result1 = await renderMermaid(browser, diagram1, "svg", {
    backgroundColor: "white",
    mermaidConfig: { theme: "default" }
  });

  const result2 = await renderMermaid(browser, diagram2, "png", {
    backgroundColor: "transparent",
    viewport: { width: 1200, height: 800, deviceScaleFactor: 2 }
  });

  // Save results
  await fs.writeFile("diagram1.svg", result1.data);
  await fs.writeFile("diagram2.png", result2.data);

  // Access metadata
  console.log("Diagram 1 title:", result1.title);
  console.log("Diagram 1 description:", result1.desc);
  
} finally {
  await browser.close();
}

CLI Function

Programmatically invoke the CLI functionality.

/**
 * Main CLI function that parses command line arguments and executes rendering
 * Reads from process.argv and handles all CLI options
 * @returns Promise that resolves when CLI execution is complete
 */
async function cli(): Promise<void>;

Usage Examples:

import { cli } from "@mermaid-js/mermaid-cli";

// Programmatically invoke CLI (reads from process.argv)
// Useful for custom CLI wrappers
await cli();

Error Handling Function

Utility function for consistent error handling and process termination.

/**
 * Prints error message to stderr and exits with code 1
 * @param message - Error message to display (string or any value)
 * @returns Never returns (exits process)
 */
function error(message: any): never;

Usage Examples:

import { error } from "@mermaid-js/mermaid-cli";

// Handle custom validation errors
if (!inputFile.endsWith('.mmd')) {
  error("Input file must have .mmd extension");
}

// Handle caught exceptions
try {
  await someOperation();
} catch (err) {
  error(`Operation failed: ${err.message}`);
}

Configuration Types

Core Types

// Puppeteer types used by the API
interface Browser {
  // Puppeteer browser instance
  close(): Promise<void>;
  newPage(): Promise<Page>;
}

interface BrowserContext {
  // Puppeteer browser context instance
  close(): Promise<void>;
  newPage(): Promise<Page>;
}

interface LaunchOptions {
  // Puppeteer launch configuration
  headless?: boolean | "shell";
  args?: string[];
  timeout?: number;
  executablePath?: string;
  [key: string]: any;
}

interface Viewport {
  width: number;
  height: number;
  deviceScaleFactor?: number;
}

ParseMDDOptions

Comprehensive options for controlling diagram rendering behavior.

interface ParseMDDOptions {
  /** Viewport settings for browser rendering */
  viewport?: Viewport;
  
  /** Background color for PNG/SVG outputs */
  backgroundColor?: string | "transparent";
  
  /** Mermaid configuration object */
  mermaidConfig?: {
    theme?: "default" | "forest" | "dark" | "neutral";
    themeVariables?: object;
    flowchart?: object;
    sequence?: object;
    gantt?: object;
    [key: string]: any;
  };
  
  /** Custom CSS to inject into the diagram */
  myCSS?: string;
  
  /** Scale PDF output to fit chart dimensions */
  pdfFit?: boolean;
  
  /** SVG element ID attribute */
  svgId?: string;
  
  /** Icon packs to load (Iconify NPM package names) */
  iconPacks?: string[];
}

Usage Examples:

const options = {
  viewport: {
    width: 1600,
    height: 1200,
    deviceScaleFactor: 2
  },
  backgroundColor: "#f8f9fa",
  mermaidConfig: {
    theme: "dark",
    themeVariables: {
      primaryColor: "#ff6b6b",
      primaryTextColor: "#ffffff"
    },
    flowchart: {
      useMaxWidth: true,
      htmlLabels: true
    }
  },
  myCSS: `
    .node rect {
      stroke-width: 3px;
      border-radius: 8px;
    }
  `,
  pdfFit: true,
  svgId: "my-custom-diagram",
  iconPacks: ["@iconify-json/logos", "@iconify-json/mdi"]
};

await run("input.mmd", "output.png", { parseMMDOptions: options });

Markdown Processing Types

Types related to markdown file processing and image generation.

interface MarkdownImageProps {
  /** Path to the generated image file */
  url: string;
  
  /** Alt text for the image (required for accessibility) */
  alt: string;
  
  /** Optional title text for the image */
  title?: string | null;
}

Error Handling

The Node.js API throws standard JavaScript errors that should be caught and handled appropriately.

Common Error Scenarios:

import { run, renderMermaid } from "@mermaid-js/mermaid-cli";

try {
  await run("nonexistent.mmd", "output.svg");
} catch (error) {
  if (error.code === 'ENOENT') {
    console.error("Input file not found");
  } else {
    console.error("Rendering failed:", error.message);
  }
}

// Handle invalid Mermaid syntax
try {
  const result = await renderMermaid(browser, "invalid syntax", "svg");
} catch (error) {
  console.error("Invalid Mermaid diagram:", error.message);
}

// Handle Puppeteer launch failures
try {
  await run("input.mmd", "output.svg", {
    puppeteerConfig: { executablePath: "/invalid/path" }
  });
} catch (error) {
  console.error("Browser launch failed:", error.message);
}

Performance Considerations

When rendering multiple diagrams, reuse the browser instance for better performance:

import { renderMermaid } from "@mermaid-js/mermaid-cli";
import puppeteer from "puppeteer";
import fs from "fs/promises";

const browser = await puppeteer.launch();

// Efficient batch processing
const diagrams = ["diagram1.mmd", "diagram2.mmd", "diagram3.mmd"];
const results = await Promise.all(
  diagrams.map(async (diagramPath) => {
    const definition = await fs.readFile(diagramPath, "utf8");
    return renderMermaid(browser, definition, "svg");
  })
);

await browser.close();

Use the high-level run function for simple one-off operations:

// For single diagram conversions
await run("simple-diagram.mmd", "output.svg");

docs

cli.md

index.md

nodejs-api.md

tile.json