Mayank Chaudhari
Back to Blog
•

Rendering Mermaid Diagrams Across Runtimes: Browser Canvas vs. Headless Node.js

Rendering Mermaid Diagrams Across Runtimes: Browser Canvas vs. Headless Node.js
Engineering
#Mermaid#SVG#Nodejs#Browser#Architecture#OpenXML

Series Navigation: This is Part 4 in the 7-part engineering deep-dive on md2docx, our universal AST document compiler.


1. The OpenXML Vector Graphics Dilemma

Enterprise documentation lives in Microsoft Word, but developer and GenAI documentation lives in Markdown. When LLMs generate architecture proposals, technical post-mortems, or compliance reports, their diagrams are delivered as raw Mermaid.js code blocks (```mermaid ... ```).

Here lies the fundamental architectural clash: Microsoft Word OpenXML (OOXML) has no native support for Mermaid syntax, dynamic JavaScript layout scripts, or raw SVG elements.

If you inject an <svg> tag or raw Mermaid syntax into an OpenXML package, Word treats it as unparsed text or flags the package as corrupt. To render a visual diagram inside a .docx file, that diagram must be compiled into an OpenXML DrawingML container (<w:drawing>), pointing to a rasterized image part (PNG/JPEG) or a packaged vector part via OpenXML relationship manifests (word/_rels/document.xml.rels).

Furthermore, Word demands explicit physical dimensions computed in EMUs (English Metric Units) before the document ever opens on a user's machine.

┌────────────────────────────────────────────────────────────────────────┐
│                  THE OPENXML DRAWINGML CONTAINER                       │
├────────────────────────────────────────────────────────────────────────┤
│ <w:p>                                                                  │
│   <w:r>                                                                │
│     <w:drawing>                                                        │
│       <wp:inline>                                                      │
│         <!-- Extent attributes MUST be calculated in EMUs -->          │
│         <wp:extent cx="5715000" cy="3810000" />                        │
│         <a:graphic>                                                    │
│           <a:graphicData uri="http://.../picture">                     │
│             <pic:pic>                                                  │
│               <!-- Blip references image part in word/media/image1.png -->│
│               <pic:blipFill>                                           │
│                 <a:blip r:embed="rId7" />                              │
│               </pic:blipFill>                                          │
│             </pic:pic>                                                 │
│           </a:graphicData>                                             │
│         </a:graphic>                                                   │
│       </wp:inline>                                                     │
│     </w:drawing>                                                       │
│   </w:r>                                                               │
│ </w:p>                                                                 │
└────────────────────────────────────────────────────────────────────────┘

The Physics of English Metric Units (EMUs)

In standard web layouts, bounding boxes are fluid and computed asynchronously by the browser's layout engine via CSS and device pixels. In OpenXML, geometry is absolute. Word requires dimensions in EMUs:

1 Inch=914,400 EMUs\text{1 Inch} = 914,400\text{ EMUs}

1 Point (pt)=12,700 EMUs\text{1 Point (pt)} = 12,700\text{ EMUs}

1 Pixel (at standard 96 DPI)=914,40096=9,525 EMUs\text{1 Pixel (at standard } 96\text{ DPI)} = \frac{914,400}{96} = 9,525\text{ EMUs}

If the compiler fails to compute precise bounding boxes, or if it outputs 0×00 \times 0 dimensions, Word either collapses the diagram into a flat, clipped line or permanently truncates outer node labels and arrows.

The Runtime Tension: Client vs. Headless Server

To produce these DrawingML containers, our document compiler must perform two operations:

  1. Layout & Render: Parse Mermaid code into an SVG vector graph.
  2. Measure & Rasterize: Calculate exact bounding box dimensions in EMUs and rasterize the SVG into a high-DPI raster buffer (docx.ImageRun).

In web applications, this must happen across two fundamentally different runtime environments:

Engineering DimensionIn-Browser Client (@m2d/mermaid)Headless Server / CLI (@m2d/mermaid-node)
Execution ContextModern Browser Sandbox (Chrome, Safari, Firefox)Headless Node.js, Bun, AWS Lambda, @m2d/cli
DOM DependencyFull DOM (document, window, Canvas API)Headless (No DOM, no canvas emulator)
Layout EngineOfficial mermaid.js + D3.jsbeautiful-mermaid (Pure TypeScript + ELK.js)
Diagram CatalogFull official catalog (flowchart, sequence, class, state, er, gitGraph, mindmap, gantt, pie, timeline, etc.)Curated subset (flowchart, sequence, class, state, er, gitGraph; fallback for others)
Rasterization DriverIn-Memory <canvas> & Canvas.toBlob()sharp (libvips + librsvg C++ bindings)
CSS HandlingBrowser CSS engine + computed stylesStatic variable inlining (inlineSvgCssVariables for librsvg)
Resource FootprintEphemeral browser tab memory (~15MB)Lightweight serverless process (~30MB cold start)
Failure PolicyReal-time DOM retry + client auto-repairPre-layout normalization + fallback monospace blocks

A common historical approach for server-side diagram rendering has been spawning headless Chromium via Puppeteer or Playwright. Headless browsers have legitimate and valuable use cases—particularly when rendering full browser DOM fidelity, evaluating complex client scripts, or capturing dynamic web application state.

However, in focused document compilation pipelines, headless browsers introduce substantial operational trade-offs: container image sizes often exceeding 1GB (due to Chromium binaries and required font packages), 300–500MB baseline memory footprints per worker process, fragile sandbox dependencies on minimal Linux distributions, and 2-to-4-second cold-start latencies in serverless container environments.

In md2docx, we favored an in-process headless layout pipeline via beautiful-mermaid and ELK.js, avoiding external browser process dependencies on the server. Here is how we architected a dual-runtime pipeline that produces high-fidelity diagrams with minimal execution latency.


2. Dual-Pipeline Architecture: Client vs. Server

As detailed in Part 3: Building a Markdown-to-DOCX Compiler, the core compiler parses Markdown into an Abstract Syntax Tree (MDAST) and walks the tree via typed visitor hooks. When the AST walker encounters a code block with lang: "mermaid", lang: "mmd", or lang: "mindmap", it intercepts the node and delegates rendering to the active runtime driver:

  • @m2d/mermaid: Client-side plugin leveraging the browser's native DOM, Canvas rasterization, and official mermaid.js.
  • @m2d/mermaid-node: Headless server-side plugin powered by beautiful-mermaid (ELK.js layout) and sharp.
flowchart TD subgraph ASTPass ["1. AST Interception"] AST["MDAST Code Node<br/>(lang === 'mermaid' | 'mmd')"] end subgraph BrowserPipeline ["2. Browser Client Pipeline (@m2d/mermaid)"] AST -->|"Browser Runtime"| MMD_Client["mermaid.render(id, code)"] MMD_Client -->|"Syntax Error?"| Fixer["defaultMermaidFixer<br/>(Auto-Heal Regex Engine)"] Fixer -->|Retry| MMD_Client MMD_Client --> SVG_DOM["DOM SVGSVGElement"] SVG_DOM --> Crop["tightlyCropSvg()<br/>(getBBox() + Margin Safety)"] Crop --> Canvas["Canvas.drawImage() + toBlob()"] Canvas --> BlobBuffer["PNG ArrayBuffer + Scale Factor"] end subgraph NodePipeline ["3. Headless Node.js Pipeline (@m2d/mermaid-node)"] AST -->|"Node / Bun / CLI Runtime"| Normalize["normalizeSequenceDiagram()<br/>(Multi-word Actor Parsing)"] Normalize --> BM["beautiful-mermaid<br/>(ELK.js Headless Layout)"] BM -->|"Unsupported Syntax / Type?"| Fallback["Monospace Code Fallback<br/>(Warning Header + Raw Syntax)"] BM --> RawSVG["Raw SVG (CSS Variables)"] RawSVG --> Inline["inlineSvgCssVariables()<br/>(Color Token Resolution)"] Inline --> Sharp["sharp(buffer).png()"] Sharp --> NodeBuffer["PNG Buffer + Metadata Dimensions"] end subgraph Packing ["4. OpenXML Emission"] BlobBuffer --> OpenXML["docx.ImageRun<br/>(EMU Conversion: px * 9,525)"] NodeBuffer --> OpenXML Fallback --> CodeBlock["docx.Paragraph Monospace Block"] OpenXML --> DOCX["Final .docx Artifact"] CodeBlock --> DOCX end

Regardless of whether the diagram compiles inside a user's browser tab or in a 128MB AWS Lambda function, the emitted DrawingML node is structurally consistent: an inline raster run calibrated to page margins and pixel-ratio boundaries.


3. The Browser Pipeline: DOM Measurement & Canvas Rasterization

When running in the browser (such as in rich-text web editors or client-side export dashboards like @m2d/tiptap), @m2d/mermaid takes advantage of the browser's graphics stack.

Deterministic Geometry Measurement: tightlyCropSvg

A frequent defect in web-to-Word converters is excessive whitespace surrounding diagrams. Standard mermaid.js output often assigns generous viewBox margins designed for full-viewport web pages, which wastes horizontal real estate on 8.5" ×\times 11" Word pages.

In @m2d/image/src/svg-utils.ts, we solve this by injecting the generated SVG into a hidden, off-screen singleton DOM container, allowing the browser's layout engine to compute the exact bounding box (getBBox()) before rasterizing:

let globalContainer: HTMLDivElement;

const getContainer = (options: IDefaultImagePluginOptions): HTMLDivElement => {
  if (!globalContainer) {
    globalContainer = document.createElement("div");
    globalContainer.style.cssText = `
      height:${options.maxH}in;
      width:${options.maxW}in;
      position:absolute;
      visibility:hidden;
      pointer-events:none;
    `;
    document.body.appendChild(globalContainer);

    const width = parseFloat(getComputedStyle(globalContainer).width);
    if (!Number.isNaN(width)) {
      options.dpi = width / options.maxW;
    }
  }
  return globalContainer;
};

Using this container, tightlyCropSvg calculates the content bounds, adds a 4px safety bleed, clamps outer boundaries, and rewrites the viewBox:

const tightlyCropSvg = (
  svgRaw: string,
  container: HTMLDivElement,
): Promise<{ svg: string; scale: number }> =>
  new Promise((resolve, reject) => {
    const svgEl = parseSvg(svgRaw) as SVGSVGElement;
    container.appendChild(svgEl);

    requestAnimationFrame(() => {
      try {
        const bbox = svgEl.getBBox();
        const origW = parseFloat(getComputedStyle(svgEl).width) || bbox.width;
        const origH = parseFloat(getComputedStyle(svgEl).height) || bbox.height;

        const margin = 4;
        const croppedW = bbox.width + margin * 2;
        const croppedH = bbox.height + margin * 2;

        const finalW = origW > 0 ? Math.min(croppedW, origW) : croppedW;
        const finalH = origH > 0 ? Math.min(croppedH, origH) : croppedH;

        const clone = svgEl.cloneNode(true) as SVGSVGElement;
        clone.setAttribute(
          "viewBox",
          `${bbox.x - margin} ${bbox.y - margin} ${croppedW} ${croppedH}`,
        );
        clone.setAttribute("width", `${finalW}`);
        clone.setAttribute("height", `${finalH}`);
        clone.removeAttribute("style");

        const serialized = new XMLSerializer().serializeToString(clone);
        svgEl.remove();

        const scale =
          origW && origH ? Math.min(croppedW / origW, croppedH / origH, 1) : 1;

        resolve({ svg: serialized, scale });
      } catch (err) {
        svgEl.remove();
        reject(err);
      }
    });
  });

Once cropped, the SVG is drawn to an offscreen <canvas> at 3×3\times scale to ensure crisp, 300+ DPI print typography inside Microsoft Word, converted to a PNG Blob, and extracted as an ArrayBuffer for docx.ImageRun.


4. The Auto-Healing Syntax Repair Engine

In enterprise applications powered by LLMs (GPT-4o, Claude 3.5 Sonnet, Gemini 1.5 Pro), raw Mermaid output fails to parse approximately 12% to 18% of the time.

LLMs frequently generate unquoted node labels containing special syntax characters like colons, slashes, email addresses, hyphens, and nested parentheses (e.g., A[Order Service (v2.1)] --> B[(Postgres: Primary)]). While humans understand the diagram's intent, the official mermaid.js lexer throws an unrecoverable ParseError: syntax error.

Rather than failing document generation, @m2d/mermaid embeds an Auto-Healing Syntax Repair Engine (defaultMermaidFixer). When mermaid.render() fails on the first pass, the engine intercepts the exception, applies structural AST regular expression transformations, and re-renders:

const quoteLabel = (text: string): string => {
  const trimmed = text.trim();
  if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
    return trimmed;
  }
  return `"${trimmed.replace(/"/g, "'")}"`;
};

export const defaultMermaidFixer = (value: string, _error?: Error): string => {
  return (
    value
      // 1. Stadium shape: ID([ ... ])
      .replace(
        /\b([a-zA-Z0-9_-]+)\(\[\s*([^"\r\n\]]+?)\s*\]\)/g,
        (_match, id, text) => `${id}([${quoteLabel(text)}])`,
      )
      // 2. Cylinder shape: ID[( ... )]
      .replace(
        /\b([a-zA-Z0-9_-]+)\[\(\s*([^"\r\n)]+?)\s*\)\]/g,
        (_match, id, text) => `${id}[(${quoteLabel(text)})]`,
      )
      // 3. Subroutine shape: ID[[ ... ]]
      .replace(
        /\b([a-zA-Z0-9_-]+)\[\[\s*([^"\r\n\]]+?)\s*\]\]/g,
        (_match, id, text) => `${id}[[${quoteLabel(text)}]]`,
      )
      // 4. Circle shape: ID(( ... ))
      .replace(
        /\b([a-zA-Z0-9_-]+)\(\(\s*([^"\r\n)]+?)\s*\)\)/g,
        (_match, id, text) => `${id}((${quoteLabel(text)}))`,
      )
      // 5. Rhombus / Decision shape: ID{ ... }
      .replace(
        /\b([a-zA-Z0-9_-]+)\{\s*([^"\r\n}]+?)\s*\}/g,
        (_match, id, text) => `${id}{${quoteLabel(text)}}`,
      )
      // 6. Standard Rectangle shape: ID[ ... ]
      .replace(
        /\b([a-zA-Z0-9_-]+)\[\s*([^"\r\n\]]+?)\s*\]/g,
        (_match, id, text) => `${id}[${quoteLabel(text)}]`,
      )
      // 7. Rounded shape: ID( ... )
      .replace(
        /\b([a-zA-Z0-9_-]+)\(\s*([^"\r\n)]+?)\s*\)/g,
        (_match, id, text) => `${id}(${quoteLabel(text)})`,
      )
      // 8. Pipe edge labels: -->| ... |
      .replace(
        /(\|)([^"\r\n|]+?)(\|)/g,
        (_match, _p1, text) => `|${quoteLabel(text)}|`,
      )
  );
};

The Two-Stage Execution Lifecycle

In packages/mermaid/src/index.ts, rendering executes as a resilient fallback loop:

const renderMermaidDiagram = async (
  value: string,
  options?: IMermaidPluginOptions,
): Promise<RenderResult | undefined> => {
  const mId = `m${crypto.randomUUID()}`; // Must not start with a digit

  try {
    return await mermaid.render(mId, value);
  } catch (error) {
    // Stage 1: Check for user-provided custom AST fixer
    if (options?.fixMermaid) {
      try {
        return await mermaid.render(
          mId,
          options.fixMermaid(value, error as Error),
        );
      } catch (error1) {
        console.warn("[m2d/mermaid] Custom fixMermaid attempt failed:", error1);
      }
    }

    // Stage 2: Execute built-in auto-healing fixer
    const autoFixEnabled = options?.autoFix ?? true;
    if (autoFixEnabled) {
      try {
        const autoFixed = defaultMermaidFixer(value, error as Error);
        if (autoFixed !== value) {
          return await mermaid.render(mId, autoFixed);
        }
      } catch (error2) {
        console.warn("[m2d/mermaid] Built-in auto-fixer attempt failed:", error2);
      }
    }

    return undefined;
  }
};

This auto-healing loop recovers the vast majority of syntax discrepancies in LLM-generated markdown, significantly increasing compilation reliability without requiring human intervention.


5. The Headless Server Pipeline: beautiful-mermaid and sharp

On the server, in CI/CD pipelines (@m2d/cli), or in background worker microservices, browser APIs do not exist. While orchestrating headless browser pools can achieve high DOM parity, doing so solely to rasterize static diagram blocks introduces significant resource footprint and cold-start latency.

In @m2d/mermaid-node, we adopted a headless architecture powered by beautiful-mermaid and sharp.

Why beautiful-mermaid Over JSDOM and Headless Browsers

Evaluating server-side Mermaid rendering yields three architectural paths:

  1. Headless Browsers (Puppeteer / Playwright): Launching Chromium provides full browser DOM fidelity and client script evaluation, but incurs operational trade-offs: 1GB+ Docker image sizes (with Chromium and font libraries), 300–500MB baseline memory per worker, 2-to-4-second cold starts, and complex /dev/shm shared memory configs in containerized environments.
  2. DOM Emulators (JSDOM / HappyDOM + official mermaid.js): At first glance, running mermaid.js inside JSDOM appears lightweight. However, mermaid.js relies deeply on browser layout metrics: calling element.getBBox(), getComputedTextLength(), and measuring rendered font glyphs. JSDOM does not implement a layout engine. Calls to getBBox() either throw errors or return 0×00 \times 0 dimensions, causing text labels to collapse, node boundaries to shrink to empty boxes, and edge connectors to misalign.
  3. Pure TypeScript Layout (beautiful-mermaid): beautiful-mermaid uses the Eclipse Layout Kernel (ELK.js), transpiled directly into pure JavaScript and TypeScript. It computes graph topologies, hierarchical layers, port placement, and edge routings through algorithmic geometry without requiring any DOM nodes, JSDOM instances, or native canvas emulators.
┌────────────────────────────────────────────────────────────────────────┐
│                   SERVER-SIDE MERMAID ARCHITECTURES                    │
├────────────────────────────────────────────────────────────────────────┤
│ 1. Headless Browser (Puppeteer/Playwright):                            │
│    Node.js ──(WebSocket CDP)──> Chromium Process (400MB) ──> Screenshot│
│    [Heavy cold-starts (2-4s), complex container dependencies]          │
│                                                                        │
│ 2. DOM Emulation (JSDOM + mermaid.js):                                 │
│    Node.js ──> JSDOM ──> mermaid.render()                              │
│    [Fails: getBBox() returns 0x0; text bounds and arrows collapse]    │
│                                                                        │
│ 3. Headless ELK.js (beautiful-mermaid + sharp):                        │
│    Node.js ──> beautiful-mermaid (Pure TS + ELK) ──> Raw SVG           │
│            ──> inlineSvgCssVariables() ──> sharp (librsvg) ──> PNG     │
│    [Sub-15ms execution, ~25MB memory, no browser binaries]             │
└────────────────────────────────────────────────────────────────────────┘

By choosing beautiful-mermaid, @m2d/mermaid-node achieves:

  • Cold Start Latency: Under 15ms (compared to ~2.8s cold start for a spawned Chromium instance).
  • Memory Footprint: Approximately 15MB to 25MB total memory consumption (compared to 300–500MB baseline for headless browser workers).
  • Container Packaging: A pure npm dependency with native sharp bindings (~30MB), avoiding 1GB+ Docker image overhead with Chromium and system fonts.

[!NOTE] Benchmark Methodology Performance figures represent an illustrative comparison between an official node:22-bullseye-slim + puppeteer Docker container and an in-process Node.js 24 execution of beautiful-mermaid + ELK.js and sharp. Test workload: synthetic 20-node flowchart with nested subgraphs and labeled edges, averaged over 50 consecutive iterations on an isolated 2 vCPU / 4GB RAM Linux test runner.

However, moving to beautiful-mermaid and headless vector rendering exposed a critical graphics challenge.

The librsvg / sharp CSS Variable Blackout

beautiful-mermaid generates modern SVG 2.0 markup that relies on CSS custom properties (variables) declared on the root <svg> tag:

<svg style="--bg:#FFFFFF; --fg:#27272A; --line:#71717A;">
  <rect fill="var(--_node-fill)" stroke="var(--_node-stroke)" />
  <text fill="var(--_text)">Payment Gateway</text>
</svg>

When this SVG is passed directly to sharp (which relies on librsvg under the hood for C++ vector rasterization), an immediate rendering failure occurs: librsvg does not evaluate CSS custom properties (var(...)) or dynamic CSS color functions like color-mix().

Because var(--_node-fill) and var(--_text) fail to resolve, librsvg defaults all fills and strokes to the SVG fallback initial color: solid black (#000000). The diagram renders with opaque black fills and dark text, obscuring diagram content completely.

The Solution: Pre-Flight Color Inlining (inlineSvgCssVariables)

To solve this, @m2d/mermaid-node implements inlineSvgCssVariables. Before passing the SVG buffer to sharp, it parses the root <svg style="..."> declarations, extracts color tokens, executes sRGB color blending calculations in software, and replaces all CSS variable references with absolute hexadecimal values:

const hexToRgb = (hex: string): [number, number, number] => {
  let c = hex.replace("#", "");
  if (c.length === 3) {
    c = c.split("").map((x) => x + x).join("");
  }
  const num = Number.parseInt(c, 16);
  return [(num >> 16) & 255, (num >> 8) & 255, num & 255];
};

const rgbToHex = ([r, g, b]: [number, number, number]): string =>
  `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;

const mixColors = (color1Hex: string, color2Hex: string, pct1: number): string => {
  const [r1, g1, b1] = hexToRgb(color1Hex);
  const [r2, g2, b2] = hexToRgb(color2Hex);
  const factor = pct1 / 100;
  return rgbToHex([
    Math.round(r1 * factor + r2 * (1 - factor)),
    Math.round(g1 * factor + g2 * (1 - factor)),
    Math.round(b1 * factor + b2 * (1 - factor)),
  ]);
};

export const inlineSvgCssVariables = (
  svg: string,
  transparent = true,
): string => {
  const styleMatch = svg.match(/style="([^"]+)"/);
  if (!styleMatch) return svg;

  const vars: Record<string, string> = {};
  for (const part of styleMatch[1].split(";")) {
    const [k, v] = part.split(":").map((s) => s?.trim());
    if (k && v) vars[k] = v;
  }

  const bg = vars["--bg"] || "#FFFFFF";
  const fg = vars["--fg"] || "#27272A";
  const darkTheme = (hexToRgb(bg)[0] * 299 + hexToRgb(bg)[1] * 587 + hexToRgb(bg)[2] * 114) / 1000 < 128;

  const defaultNodeFill = darkTheme
    ? transparent ? mixColors(fg, bg, 12) : mixColors(fg, bg, 5)
    : transparent ? "#FFFFFF" : mixColors(fg, bg, 3);

  const colorMap: Record<string, string> = {
    "var(--_text)": fg,
    "var(--_text-sec)": vars["--muted"] || mixColors(fg, bg, 60),
    "var(--_line)": vars["--line"] || mixColors(fg, bg, 50),
    "var(--_arrow)": vars["--accent"] || mixColors(fg, bg, 85),
    "var(--_node-fill)": vars["--surface"] || defaultNodeFill,
    "var(--_node-stroke)": vars["--border"] || (darkTheme ? mixColors(fg, bg, 30) : mixColors(fg, bg, 20)),
    "var(--_group-fill)": transparent ? "none" : bg,
    "var(--bg)": bg,
    "var(--fg)": fg,
  };

  let inlined = svg;
  for (const [varRef, resolvedHex] of Object.entries(colorMap)) {
    inlined = inlined.replaceAll(varRef, resolvedHex);
  }

  // Dual-contrast halo strokes for pseudostates (crisp visibility on light & dark page backgrounds)
  const haloStroke = darkTheme ? "rgba(0,0,0,0.4)" : "rgba(255,255,255,0.8)";
  inlined = inlined.replace(
    /(<g class="node" [^>]*data-shape="state-start"[^>]*>[\s\S]*?<circle [^>]*stroke=")(none)(")/g,
    `$1${haloStroke}$3 stroke-width="1"`,
  );

  return inlined;
};

With inlineSvgCssVariables, sharp receives fully qualified hex fills and strokes, producing clean vector-to-raster output with sub-millisecond conversion speeds.

Sequence Diagram Normalization

beautiful-mermaid's parser uses a strict regex for actor tokens that expects non-whitespace identifiers. If an LLM generates a sequence diagram with natural space-separated names like Client UI->>Payment Gateway: Process Auth, the parser drops the interaction.

In packages/mermaid-node/src/mermaid-node.ts, normalizeSequenceDiagram inspects the AST string before layout, extracts multi-word actors, and automatically synthesizes explicit alias declarations:

export const normalizeSequenceDiagram = (code: string): string => {
  const lines = code.split("\n");
  if (!/^sequenceDiagram/i.test(lines[0].trim())) return code;

  const msgRe = /^(\s*)(.+?)\s*(--?>?>|--?[)x]|--?>>|--?>)\s*([+-]?)(.+?)\s*:\s*(.+)$/;
  const participantsWithSpaces = new Map<string, string>();

  for (const line of lines) {
    const trimmed = line.trim();
    if (trimmed.startsWith("participant ") || trimmed.startsWith("actor ")) continue;
    const m = trimmed.match(msgRe);
    if (m) {
      const from = m[2].trim();
      const to = m[5].trim();
      if (from.includes(" ")) participantsWithSpaces.set(from, from.replace(/\s+/g, "_"));
      if (to.includes(" ")) participantsWithSpaces.set(to, to.replace(/\s+/g, "_"));
    }
  }

  if (participantsWithSpaces.size === 0) return code;

  const participantDecls = Array.from(participantsWithSpaces.entries())
    .map(([name, id]) => `    participant ${id} as ${name}`);

  const newLines = [lines[0], ...participantDecls];
  for (let i = 1; i < lines.length; i++) {
    let line = lines[i];
    const m = line.match(msgRe);
    if (m) {
      const from = participantsWithSpaces.get(m[2].trim()) ?? m[2].trim();
      const to = participantsWithSpaces.get(m[5].trim()) ?? m[5].trim();
      line = `${m[1]}${from} ${m[3]} ${m[4]}${to}: ${m[6]}`;
    }
    newLines.push(line);
  }
  return newLines.join("\n");
};

6. Supported Matrix & Graceful Fallbacks

Because browser and Node.js pipelines rely on different underlying layout engines, their diagram capabilities differ significantly.

Capability Comparison Across Runtimes

Diagram Type / CapabilityIn-Browser Client (@m2d/mermaid)Headless Node.js (@m2d/mermaid-node)
Flowcharts & Graphs (graph, flowchart)Supported (Full D3 engine)Supported (ELK.js layout)
Sequence Diagrams (sequenceDiagram)SupportedSupported (with multi-word normalization)
Class Diagrams (classDiagram)SupportedSupported
State Diagrams (stateDiagram-v2)SupportedSupported
Entity Relationship (erDiagram)SupportedSupported
Git Graphs (gitGraph)SupportedSupported
XY Charts (xychart-beta)SupportedSupported
Mindmaps (mindmap)SupportedFallback to code block
Gantt Charts (gantt)SupportedFallback to code block
Pie & Quadrant Charts (pie, quadrantChart)SupportedFallback to code block
Timelines & User Journeys (timeline, journey)SupportedFallback to code block
C4 Architecture Diagrams (C4Context)SupportedFallback to code block
Custom CSS Theme EngineFull dynamic CSS & class stylingPre-set palettes via inlineSvgCssVariables

In the browser, the official mermaid.js library handles the full spectrum of Mermaid diagrams. In headless Node.js, beautiful-mermaid targets the core structural diagram types that represent the vast majority of architecture documentation.

The Graceful Fallback Policy

What happens when an author includes an unsupported diagram type (such as a Gantt chart or Mindmap) on the server, or provides completely unparseable syntax?

In an unhedged pipeline, the conversion crashes and throws an unhandled rejection, aborting a 100-page document export.

In md2docx, failed diagram nodes automatically trigger @m2d/image-node's graceful fallback policy. The unrendered diagram is transformed into an OpenXML styled monospace code block preceded by a warning header:

###### ⚠️ Diagram Source (Render Fallback)
```mermaid
pie title Pets Adopted
    "Dogs" : 386
    "Cats" : 85
    "Rats" : 15

This ensures that **document exports complete reliably even when encountering charting syntax errors**, and the raw diagram definition is preserved for the end user to inspect or correct.

---

## 7. Two-Tier Persistent Caching (`@m2d/cache`)

Mermaid diagram layouts require matrix calculations, text metrics, and graph topology traversal. Even with `beautiful-mermaid`'s 10–15ms speed, compiling a technical specification containing 40 architecture diagrams adds noticeable latency.

In `@m2d/cache`, we implemented a **Two-Tier Persistent Cache**:

1. **Tier 1 (In-Memory Microtask Cache):** Deduplicates identical diagram nodes evaluated in parallel during asynchronous AST visitor passes.
2. **Tier 2 (IndexedDB Persistent Cache):** Retains compiled SVGs and raster buffers across browser sessions, reloads, and tab lifetimes under the `m2d-cache` database.

### 64-Bit Non-Cryptographic Hashing via `xxhash-wasm`

Standard stringification or cryptographic hashes (like SHA-256) are either non-deterministic with object key ordering or incur unnecessary CPU overhead. We utilize **`xxhash-wasm`** to generate 64-bit non-cryptographic hashes over stably serialized AST inputs:

```typescript
import xxhash from "xxhash-wasm";

export const stableSerialize = (obj: unknown, ignoreKeys: string[] = []): string => {
  if (Array.isArray(obj)) {
    return `[${obj.map((item) => stableSerialize(item, ignoreKeys)).join(",")}]`;
  }
  if (typeof obj !== "object" || obj === null) {
    return String(obj);
  }
  const copy: Record<string, unknown> = { ...obj };
  return Object.keys(copy)
    .filter((k) => !ignoreKeys.includes(k) && copy[k] !== undefined)
    .sort()
    .map((k) => `${k}:${stableSerialize(copy[k], ignoreKeys)}`)
    .join("|");
};

export const generateCacheKey = async (
  ignoreKeys: string[],
  namespace: string,
  ...args: unknown[]
): Promise<string> => {
  const { h64ToString } = await xxhash();
  const serialized = `${namespace}:${args
    .map((arg) => stableSerialize(arg, ignoreKeys))
    .join(",")}`;
  return h64ToString(serialized);
};

When a user repeatedly exports or modifies a long document, diagram cache hits resolve in sub-millisecond time, bypassing the layout engine, color inliner, and rasterizer completely.


8. Production Implementation: Client vs. Server Setup

Here is how to configure and execute both pipelines in production.

Browser Client Setup (@m2d/mermaid + @m2d/image)

import { toDocx } from "@m2d/core";
import { imagePlugin } from "@m2d/image";
import { mermaidPlugin } from "@m2d/mermaid";

const markdown = `
# System Architecture

\`\`\`mermaid
flowchart LR
    Client([Client Browser]) --> API[(REST Gateway)]
    API --> DB[(Primary Postgres)]
\`\`\`
`;

export async function exportInBrowser(): Promise<Blob> {
  const docxBlob = await toDocx(markdown, {
    plugins: [
      mermaidPlugin({
        autoFix: true, // Enables auto-healing for LLM syntax errors
        mermaidConfig: {
          theme: "neutral",
          fontFamily: "Inter, sans-serif",
        },
      }),
      imagePlugin({
        scale: 3, // 3x oversampling for 300 DPI print clarity
        maxW: 6.5, // 6.5 inches (fits standard 8.5" page with 1" margins)
        maxH: 9.0,
      }),
    ],
  });

  return docxBlob;
}

Headless Server Setup (@m2d/mermaid-node + @m2d/image-node)

import fs from "node:fs/promises";
import { toDocx } from "@m2d/core";
import { imageNodePlugin } from "@m2d/image-node";
import { mermaidNodePlugin } from "@m2d/mermaid-node";

export async function exportOnServer(markdownPath: string, outputPath: string): Promise<void> {
  const markdown = await fs.readFile(markdownPath, "utf-8");

  const docxBuffer = await toDocx(markdown, {
    plugins: [
      mermaidNodePlugin({
        theme: "zinc-light", // Clean executive monochrome theme
        transparent: true,
      }),
      imageNodePlugin({
        dpi: 96,
        maxW: 6.5,
        maxH: 9.0,
        mermaidFallback: "code", // Graceful fallback for unsupported diagram types
      }),
    ],
  });

  await fs.writeFile(outputPath, Buffer.from(docxBuffer));
}

9. Architectural Takeaways & What's Next

Compiling modern vector graphics into enterprise-ready Word documents requires respecting the constraints of both worlds:

  1. Word OpenXML is rigid: It requires explicit raster runs, strict relationship manifests, and coordinate bounds pre-computed in English Metric Units.
  2. Browsers are rich but stateful: Leveraging hidden singleton DOM containers and offscreen Canvas APIs yields high-resolution print assets, with auto-healing syntax repair assisting with common LLM syntax variances.
  3. Servers benefit from in-process layout: While headless browsers excel at general DOM rendering and script evaluation, document compilation services operate far more efficiently with in-process layout. Coupling beautiful-mermaid's ELK layout engine with CSS variable inlining and sharp delivers fast, reliable diagrams with a minimal container footprint.

In Part 5, we explore Designing an Extensible Plugin Ecosystem, dissecting the micro-kernel architecture and lifecycle hooks that keep the @m2d compiler modular. In Part 6, we examine Beyond Basic Markdown: Word MathML, Tables, & Metadata, followed by Part 7 on Markdown-to-DOCX for GenAI Applications.

Did you enjoy this post?

Give it a like to let me know!

Recommended Posts