mdast2docx logo Md2Docx
Version 1.3.0

Auto-Fixing & Error Fallbacks

Updated 5 min ago

Self-healing syntax repairs and Word code block fallback behavior.

Mermaid diagram syntax written by users or generated by LLMs often contains minor syntax imperfections (such as unquoted colons, slashes in labels, or missing arrows). @m2d/mermaid provides built-in self-healing capabilities alongside robust error fallbacks.

Best-Effort Auto-Fixer (defaultMermaidFixer)

When an initial render attempt fails, @m2d/mermaid automatically runs a repair pass on the diagram code before giving up:

  • Unquoted Node Labels: Quotes node labels containing punctuation characters (:, /, (, )) that would otherwise cause syntax errors:
    • A[Init: /api/v1/auth] --> B becomes A["Init: /api/v1/auth"] --> B
  • Markdown Headers & Code Fences: Strips accidental wrapping backticks or leading markdown headings injected by LLMs.
  • HTML Labels: Enforces htmlLabels: false for strict SVG text compliance across document viewers.

Custom Fixer (fixMermaid)

You can provide a custom fixer function to apply heuristic repairs or invoke an AI model:

import { mermaidPlugin } from "@m2d/mermaid";

const plugin = mermaidPlugin({
  fixMermaid: (brokenCode, error) => {
    // Custom regex fixes or AI prompt
    return brokenCode.replace(/-->/g, "---");
  },
});

Integration with @m2d/image Fallbacks

When a diagram cannot be rendered even after fixing, @m2d/mermaid preserves the original source in data.mermaid. When processed by @m2d/image:

  1. It avoids emitting corrupt or broken SVG drawings into the Word document.
  2. It transforms the failed diagram into a clean, authentic Word code block (lang: "mermaid").
  3. It places a collapsible H6 heading (###### ⚠️ Mermaid Diagram Source (Render Fallback)) above the block, keeping it collapsible in Word and completely out of default 1–3 level Tables of Contents.

On this page