Building a Markdown-to-DOCX Compiler: ASTs over String Hacks

Series Navigation: This is Part 3 in our 7-part engineering deep-dive on
md2docx, our universal AST document compiler:
- Part 1: From Fragmented Repositories to a Modern Monorepo — Consolidating packages into a unified TypeScript monorepo.
- Part 2: Building a Modern Tiptap-to-DOCX Integration — Browser-native, client-side Word export for rich-text editors.
- Part 3: Building a Markdown-to-DOCX Compiler (You are here) — Canonical deep-dive on the MDAST-to-OpenXML compiler architecture.
- Part 4: Rendering Mermaid Diagrams Across Runtimes — Browser canvas vs. headless Node.js vector rasterization.
- Part 5: Designing an Extensible Plugin Ecosystem — Architecture of the lifecycle hooks and plugin system.
- Part 6: Beyond Basic Markdown: Word MathML, Tables, & Metadata — Native formulas, complex tables, and frontmatter.
- Part 7: Markdown-to-DOCX for GenAI Applications — Resilient document compilation for LLM-generated content.
1. The Siren Song of the String Hack
Every engineering team tasked with exporting Markdown to Microsoft Word inevitably encounters the same seductive proposal:
"Word documents are just XML packaged inside a ZIP file. We can write a few regex passes, interpolate XML strings into a template, and zip it up."
On a whiteboard, this appears deceptively simple. A heading # Title maps to <w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Title</w:t></w:r></w:p>. An inline bold span **text** translates to <w:r><w:rPr><w:b/></w:rPr><w:t>text</w:t></w:r>. A quick prototype handles twenty words of sample text, Microsoft Word opens the file without protest, and the task is declared complete.
Production environments swiftly shatter this illusion.
The moment real-world Markdown enters the system—nested formatting such as **Caution: *Do not* restart the node.**, multi-line lists, GitHub Flavored Markdown (GFM) tables, or inline code containing XML-reserved characters—string replacement collapses. Regex engines lack the pushdown automata required to track nested scopes across arbitrary line breaks. String interpolation easily produces misnested tags or emits table cells lacking mandatory structural wrappers.
When an enterprise customer or executive attempts to open the resulting file, Microsoft Word halts with an explicit schema validation failure:
┌────────────────────────────────────────────────────────────────────────┐
│ Microsoft Word │
├────────────────────────────────────────────────────────────────────────┤
│ Word found unreadable content in "Q3-Infrastructure-Report.docx". │
│ Do you want to recover the contents of this document? If you trust │
│ the source of this document, click Yes. │
│ │
│ [ Yes ] [ No ] │
│ │
│ Location: Part: /word/document.xml, Line: 2, Column: 14820 │
└────────────────────────────────────────────────────────────────────────┘
Document corruption in enterprise software directly damages product trust. In regulated banking, legal, and healthcare workflows, a corrupted audit report or executive summary halts operations.
To produce reliable, schema-conformant Word documents at scale, text-level substitution must give way to structured compilation. Document translation is not a string formatting exercise; it is a compiler problem.
2. Anatomy of the Target: ISO/IEC 29500 (OpenXML)
To understand why string manipulation fails, one must examine the target architecture: Office Open XML (OOXML), standardized under ISO/IEC 29500.
A .docx file is an Open Packaging Conventions (OPC) ZIP archive containing a multi-part graph of XML files, media blobs, and relationship manifests:
document.docx (ZIP Package)
├── [Content_Types].xml <- MIME type registry for package parts
├── _rels/
│ └── .rels <- Root relationship graph
├── word/
│ ├── document.xml <- Main document story (body content)
│ ├── styles.xml <- Paragraph and run style definitions
│ ├── numbering.xml <- Abstract list hierarchies and overrides
│ ├── footnotes.xml <- Footnote body definitions
│ └── _rels/
│ └── document.xml.rels <- Target URIs, images, and hyperlink IDs
Inside word/document.xml, Word enforces an uncompromising, deeply nested, strictly ordered schema:
┌───────────────────────────────────────────────────────────┐
│ <w:document> │
│ └── <w:body> │
│ ├── <w:p> (Paragraph) │
│ │ ├── <w:pPr> (Paragraph Properties) │
│ │ │ ├── <w:pStyle w:val="Heading1"/> │
│ │ │ └── <w:jc w:val="center"/> │
│ │ └── <w:r> (Run) │
│ │ ├── <w:rPr> (Run Properties) │
│ │ │ ├── <w:b/> │
│ │ │ └── <w:color w:val="003366"/> │
│ │ └── <w:t>Text content</w:t> │
│ └── <w:tbl> (Table) │
│ ├── <w:tblPr> │
│ └── <w:tr> (Table Row) │
│ └── <w:tc> (Table Cell) │
│ ├── <w:tcPr/> │
│ └── <w:p> (Mandatory Child) │
└───────────────────────────────────────────────────────────┘
Why OpenXML Constraints Demand an Intermediate Tree
Three structural properties of OpenXML make ad-hoc text substitution uniquely error-prone:
1. Flat Run Fracturing vs. Nested Markup
In HTML and Markdown, formatting is tree-like and composable via nested tags:
<p>This is <strong>bold and <em>italicized</em></strong> text.</p>
In OpenXML, runs cannot nest. A run (<w:r>) is a flat, contiguous leaf node of text that shares an identical set of run properties (<w:rPr>). Any variation in bold, italic, strikethrough, font size, or color forces an immediate fracture into a new sibling run:
<w:p>
<w:r>
<w:t xml:space="preserve">This is </w:t>
</w:r>
<w:r>
<w:rPr><w:b/></w:rPr>
<w:t xml:space="preserve">bold and </w:t>
</w:r>
<w:r>
<w:rPr><w:b/><w:i/></w:rPr>
<w:t>italicized</w:t>
</w:r>
<w:r>
<w:t xml:space="preserve"> text.</w:t>
</w:r>
</w:p>
Resolving overlapping inline styles into a sequence of fractured sibling runs requires computing the exact set of active formatting flags across all token boundaries. Without a structured state stack, string operations routinely invert or miss closing markers.
2. Strict Child Ordering Requirements
OpenXML XML Schema Definition (XSD) rules enforce sequence ordering. Within <w:p>, <w:pPr> must precede all <w:r> runs. Inside <w:r>, <w:rPr> must precede <w:t>. Inside <w:tc>, at least one <w:p> is syntactically mandatory—an empty table cell (<w:tc/> or <w:tc><w:tcPr/></w:tc>) violates the schema and prompts Word's recovery dialog.
3. Dedicated Coordinate Physics
OpenXML operates entirely in specialized non-metric, non-pixel coordinate systems:
- Twips (Twentieth of an Imperial Point): ; ; . Page margins, table cell paddings, and column widths must be calculated in integer twips.
- Half-Points: Font sizes (
<w:sz w:val="24"/>) are specified in half-points (). - EMUs (English Metric Units): Images and vector drawings must be positioned in EMUs (; ).
Managing twip conversions, relationship ID mappings (r:id="rId5"), and XML namespace bindings requires a compiler pipeline with structured intermediate models.
3. The Canonical Compiler Architecture: The MDAST-to-OpenXML Pipeline
In md2docx, document generation is organized as a classical multi-stage compiler pipeline. Rather than manipulating text, we parse Markdown into a Markdown Abstract Syntax Tree (MDAST), traverse the tree with dedicated visitor passes, project semantic nodes into validated in-memory OpenXML document primitives (docx.js), and serialize the package deterministically.
flowchart TD subgraph Frontend ["1. Frontend: Lexical Analysis & Grammar Parsing"] A["Raw Markdown Input"] --> B["unified() Pipeline"] B --> C["remark-parse<br/>(CommonMark Parser)"] B --> D["remark-gfm<br/>(Tables, Task Lists, Strikethrough)"] B --> E["remark-math<br/>(LaTeX Math Syntaxes)"] B --> F["remark-frontmatter<br/>(YAML / TOML Metadata)"] end subgraph IR ["2. Intermediate Representation (MDAST)"] C & D & E & F --> G["Unist MDAST Tree<br/>(Typed Node Graph)"] end subgraph MidEnd ["3. Middle-End: Visitor & Transformation Engine (@m2d/core)"] G --> H["Pass 1: Preprocessing & Hoisting<br/>(Link Defs, Footnotes, Frontmatter Metadata)"] H --> I["Pass 2: Hierarchical Traversal"] I --> J["processBlockNodeChildren<br/>(Headings, Paragraphs, Blockquotes, Lists)"] I --> K["processInlineNodeChildren<br/>(Run Property Accumulator Stack)"] I --> L["Plugin Interception Layer<br/>(@m2d/table, @m2d/code, custom hooks)"] end subgraph Backend ["4. Backend: OpenXML Model & Serialization (docx.js)"] J & K & L --> M["Typed OpenXML DOM Primitives<br/>(Document, Section, Paragraph, Table, Run)"] M --> N["Packer Serialization<br/>(Packer.toBlob / Packer.toBuffer)"] N --> O["Conformant .docx Package<br/>(ISO/IEC 29500 OPC ZIP)"] end
The Intermediate AST Representation
When the unified parser processes a Markdown snippet:
# Infrastructure
Deploy the **cluster** using [Terraform](#deploy).
It emits an unambiguous syntax tree conforming to the unist specification:
{
"type": "root",
"children": [
{
"type": "heading",
"depth": 1,
"children": [{ "type": "text", "value": "Infrastructure" }]
},
{
"type": "paragraph",
"children": [
{ "type": "text", "value": "Deploy the " },
{
"type": "strong",
"children": [{ "type": "text", "value": "cluster" }]
},
{ "type": "text", "value": " using " },
{
"type": "link",
"url": "#deploy",
"children": [{ "type": "text", "value": "Terraform" }]
},
{ "type": "text", "value": "." }
]
}
]
}
This structural representation delivers three foundational compiler properties:
- Syntax Tokens Discarded: Hashes, asterisks, brackets, and escapes are resolved into typed AST nodes (
heading,strong,link). - Explicit Nesting Hierarchy: The
strongnode encloses its children directly, making formatting inheritance a deterministic tree walk. - Static Analysis & Extensibility: Plugins can inspect, mutate, reorder, or enrich nodes before emitting OpenXML primitives.
4. Architectural Implementation: Inside packages/core
To maintain clean separation of concerns, the compiler is partitioned across focused workspace packages:
| Package | Role in Architecture |
|---|---|
@m2d/core | The visitor engine, section orchestrator, default inline/block walkers, and plugin hook dispatcher. |
@m2d/remark-docx | The Unified.js plugin bridging remark processors to toDocx. |
@m2d/md2docx | The client-side entry point pre-configured with GFM, math, and frontmatter. |
@m2d/table | The table visitor handling twip margins, alignments, zebra shading, and cell wrapping. |
The Unified Pipeline Entry Point
In packages/md2docx/src/md2docx.ts, document generation is composed via standard Unified plugin chaining:
// packages/md2docx/src/md2docx.ts
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import remarkFrontmatter from "remark-frontmatter";
import { remarkDocx } from "@m2d/remark-docx";
import type { OutputType } from "docx";
export const md2docx = async (
md: string,
docxProps: IDocxProps = {},
sectionProps?: ISectionProps,
outputType: OutputType = "blob",
pluginProps?: Mdast2DocxPluginProps,
) => {
const processor = unified().use([
remarkParse,
remarkGfm,
remarkMath,
remarkFrontmatter,
[remarkDocx, outputType, docxProps, sectionProps, pluginProps],
]);
const res = await processor.process(md);
return res.result;
};
When processor.process(md) executes:
remarkParsetokenizes the Markdown string into a core MDAST.remarkGfmextends the grammar with tables, strikethrough, task lists, and autolinks.remarkMathcaptures LaTeX math blocks ($and$$).remarkFrontmatterextracts YAML/TOML metadata headers.remarkDocxacts as the compiler terminal, invokingtoDocx()on the completed tree.
5. Walking the Tree: The Two-Pass Visitor Pattern
Transforming an arbitrary AST into a valid OpenXML document requires two distinct phases: Definition Hoisting and Hierarchical Traversal.
flowchart TD subgraph Pass1 ["Pass 1: Definition Hoisting & Pre-Processing"] P1A["Scan Root Children"] --> P1B["Collect Link Definitions<br/>id -> target URI"] P1A --> P1C["Index Footnote Definitions<br/>identifier -> footnote body"] P1A --> P1D["Extract YAML/TOML Frontmatter<br/>Page setup, margins, headers"] P1B & P1C & P1D --> P1E["Execute Plugin preprocess() Hooks"] end subgraph Pass2 ["Pass 2: Recursive Block & Inline Visitors"] P2A["toSection()"] --> P2B["processBlockNodeChildren()"] P2B -->|Block: Heading| P2C["new Paragraph + Bookmark"] P2B -->|Block: Paragraph| P2D["new Paragraph"] P2B -->|Block: Table| P2E["tablePlugin.block -> new Table"] P2D --> P2F["processInlineNodeChildren()"] P2F -->|Inline: Text| P2G["new TextRun(value)"] P2F -->|Inline: Strong| P2H["runProps.bold = true -> recurse"] P2F -->|Inline: Link| P2I["new ExternalHyperlink / InternalHyperlink"] end Pass1 --> Pass2
Pass 1: Hoisting Definitions and Footnotes
In Markdown, reference definitions and footnotes can appear anywhere in the source document—often at the very end of the file:
Here is a reference to [Monorepo Architecture Documentation][arch-ref] and a footnote[^1].
[arch-ref]: /blog/from-fragmented-repositories-to-modern-monorepo
[^1]: Verified against ISO/IEC 29500-1:2016.
A single-pass streaming parser would encounter [arch-ref] before knowing its target URI.
In packages/core/src/index.ts, toDocx executes pre-flight definition indexing before visiting document body nodes:
// packages/core/src/index.ts (extract)
const processedAstInputs = await Promise.all(
(Array.isArray(astInputs) ? astInputs : [{ ast: astInputs }]).map(
async ({ ast, props }) => {
// 1. Scan tree for link & footnote definitions
const { definitions, footnoteDefinitions } = getDefinitions(
ast.children as RootContent[],
);
// 2. Pre-compile footnotes into dedicated section models
await Promise.all(
Object.values(footnoteDefinitions).map(async (footnote, index) => {
const footnoteId = index + 1;
footnote.id = footnoteId;
footnotes[footnoteId] = (await toSection(
{ type: "root", children: footnote.children },
definitions,
{},
{ footnoteProps },
)) as { children: Paragraph[] };
}),
);
return { ast, props: sectionProps, definitions, footnoteDefinitions };
},
),
);
Pass 2: The Inline Node Processor & Property Stacking
Inline formatting in Markdown represents a state machine where properties inherit down the tree. When visiting strong, emphasis, or delete, formatting flags accumulate until a leaf text node is materialized.
Here is the exact implementation from packages/core/src/section.ts:
// packages/core/src/section.ts (extract)
const createInlineProcessor = (
definitions: Definitions,
footnoteDefinitions: FootnoteDefinitions,
plugins: IPlugin[],
trimInnerSpaces: boolean,
) => {
const normalizeText = (text: string) =>
trimInnerSpaces ? text.replace(/ +/g, " ") : text;
const processInlineNodeChildren: InlineChildrenProcessor = (
node,
runProps = {},
) =>
(
node.children?.map((child) => {
// Allow plugins to intercept inline rendering
const docxNodes: InlineDocxNodes[] = plugins.flatMap(
(plugin) =>
plugin.inline?.(
docx,
child,
runProps,
definitions,
footnoteDefinitions,
processInlineNodeChildren,
) ?? [],
);
// Inherit styling properties from parent context
const newRunProps = Object.assign({}, runProps, child.data);
const url = child.url ?? definitions[child.identifier?.toUpperCase()];
switch (child.type) {
case "text":
return [
...docxNodes,
new TextRun({
text: normalizeText(child.value),
...newRunProps,
}),
];
case "emphasis":
newRunProps.italics = true;
return [
...docxNodes,
...processInlineNodeChildren(child, newRunProps),
];
case "strong":
newRunProps.bold = true;
return [
...docxNodes,
...processInlineNodeChildren(child, newRunProps),
];
case "delete":
newRunProps.strike = true;
return [
...docxNodes,
...processInlineNodeChildren(child, newRunProps),
];
case "inlineCode":
return [
...docxNodes,
new TextRun({
text: normalizeText(child.value),
...newRunProps,
style: "code",
font: { name: "Consolas" },
}),
];
case "link":
case "linkReference":
newRunProps.underline = {};
return [
...docxNodes,
url.startsWith("#")
? new InternalHyperlink({
anchor: url.slice(1),
children: processInlineNodeChildren(child, newRunProps),
})
: new ExternalHyperlink({
link: url,
children: processInlineNodeChildren(child, newRunProps),
}),
];
case "footnoteReference":
return [
...docxNodes,
new FootnoteReferenceRun(
footnoteDefinitions[child.identifier]?.id ?? 0,
),
];
default:
return [...docxNodes];
}
}) ?? []
).flat();
return processInlineNodeChildren;
};
How State Accumulation Prevents Tag-Nesting Inversions
Consider how processInlineNodeChildren evaluates nested styles such as **bold *and italic***:
- The
strongnode receives an emptyrunPropsobject ({}). It assignsnewRunProps.bold = trueand recurses into its children. - The first child is a
textnode ("bold "). It creates aTextRun({ text: "bold ", bold: true }). - The second child is an
emphasisnode. It receives{ bold: true }, assignsnewRunProps.italics = true, and recurses. - The leaf
textnode ("and italic") receives{ bold: true, italics: true }. It creates aTextRun({ text: "and italic", bold: true, italics: true }).
The recursive walk flattens hierarchical styling into an array of concrete OpenXML <w:r> runs.
AST traversal enforces structural sequence invariants and tag nesting hierarchies required by the ISO/IEC 29500 specification (such as wrapping text in paragraphs and cells in tables), which significantly minimizes the risk of producing corrupted documents compared to string concatenation. However, AST traversal does not by itself ensure complete document validity: custom user plugins that inject malformed raw XML fragments or invalid font references can still trigger Word recovery prompts if not properly checked before serialization.
6. Transforming Complex Blocks: Tables and Margins
Tables in OpenXML require careful coordinate calculation. In Markdown, a table is simply lines of pipe-delimited text:
| Service | Latency (p99) | Status |
| :--- | :---: | ---: |
| Gateway | 1.2ms | Operational |
| Database | 4.8ms | Degraded |
In OpenXML, table generation involves several strict schema requirements:
- Calculating explicit twip margins for cell padding.
- Resolving column-level alignment rules (
:---:vs---:). - Applying borders (
<w:tblBorders>) and zebra shading (<w:shd>). - Mandatory Block Wrapping: Every
<w:tc>must contain at least one block element (<w:p>). Placing a raw run (<w:r>) directly inside a table cell produces an invalid schema and triggers a document repair dialog.
In @m2d/table, we handle this via wrapInBlockNodeIfNeeded and deterministic twip margin mapping:
// packages/table/src/index.ts (extract)
const border = { style: BorderStyle.SINGLE, color: "auto", size: 1 };
export const defaultTableOptions: IDefaultTablePluginProps = {
tableProps: {
width: { size: 100, type: WidthType.PERCENTAGE },
margins: {
top: convertMillimetersToTwip(2),
right: convertMillimetersToTwip(4),
bottom: convertMillimetersToTwip(2),
left: convertMillimetersToTwip(4),
},
borders: {
top: border,
right: border,
bottom: border,
left: border,
insideHorizontal: border,
insideVertical: border,
},
},
// ...
};
// Inside tablePlugin.block visitor:
const wrapInBlockNodeIfNeeded = (cell: { children: RootContent[] }) => {
const children: RootContent[] = [];
const tmp: PhrasingContent[] = [];
for (const cellNode of cell.children) {
if (blockNodeTypesThatCanComeInCell.includes(cellNode.type)) {
if (tmp.length > 0) {
children.push({ type: "paragraph", children: [...tmp] });
tmp.length = 0;
}
children.push(cellNode);
} else {
tmp.push(cellNode as PhrasingContent);
}
}
if (tmp.length > 0) {
children.push({ type: "paragraph", children: tmp });
}
cell.children = children;
};
When building each row, the table plugin extracts alignment indicators from the MDAST node.align array and maps them directly to docx.AlignmentType:
const align = (node.align as (string | null)[] | null)?.map((a) => {
switch (a) {
case "left":
return docx.AlignmentType.LEFT;
case "right":
return docx.AlignmentType.RIGHT;
case "center":
return docx.AlignmentType.CENTER;
default:
return undefined;
}
});
Operating on the AST ensures that cells with complex contents (such as bold links or footnote references) inherit column alignment deterministically without breaking cell layout.
7. The Sentinel Pattern: Preventing Re-Processing
A subtle architectural challenge in AST-to-OpenXML compilation is avoiding double processing when plugins handle compound nodes.
When the tablePlugin encounters a table node, it consumes the node, constructs a complete docx.Table with all its rows and cells, and returns it. However, if the main tree walker continues traversing children naively, it might re-visit individual tableRow or tableCell nodes, causing duplicate or fragmented text runs.
To solve this cleanly, md2docx uses the EmptyNode Sentinel Pattern:
// packages/table/src/index.ts (extract)
const rows = node.children.map(createRow);
// Record original type for debugging/inspection
(node as unknown as EmptyNode)._type = node.type;
// Nullify type to signal to subsequent visitor passes that this subtree is resolved
// @ts-expect-error - Setting type to empty string prevents re-processing
node.type = "";
return [
new Table({
...tableProps,
rows,
}),
];
By transitioning the node's type to an empty string (""), the outer visitor pass immediately skips the node on subsequent traversal cycles. This ensures that plugin transformations remain strictly idempotent.
8. Architectural Comparison: Regex vs. Headless Office vs. AST Compiler
When choosing a document generation architecture for enterprise-ready production systems, engineering teams must evaluate schema compliance, operational overhead, resource footprint, and portability:
| Evaluation Dimension | Naive Regex / String Templating | Headless Office / LibreOffice Clusters | md2docx AST Compiler Engine |
|---|---|---|---|
| Output Validity | Fragile; frequently triggers schema validation errors on nested markup. | High fidelity; uses native Office rendering engine. | High structural determinism governed by typed AST schemas; conforms to ISO/IEC 29500. |
| Runtime Dependencies | None (pure JavaScript string operations). | Heavy (LibreOffice binary, Java runtime, MS Core Fonts, OS packages). | None (pure TypeScript; no native binary dependencies). |
| Cold Start Latency | (container & process spawn overhead) | (in-process parse & serialize) | |
| Memory Footprint | per worker container / process | peak heap for typical multi-page reports | |
| Client-Side Execution | Yes (in-browser string operations). | Unsupported (requires Linux server binaries and filesystem access). | Full support (compiles in browser via Web Workers and Blobs). |
| Nested Structure Support | Fails on nested lists, overlapping formatting, and multi-run tables. | Full support. | Full support via AST visitor property stacks. |
| Operational Attack Surface | Risk of XML injection via unsanitized strings. | High (CVEs in C++ document parsers, font renderers, macro handlers). | In-process memory allocation; significantly reduces binary subprocess attack surface. |
Benchmark Methodology:
- Hardware: Modern 8-core CPU workstation (e.g. Apple M-series / Intel Core i7).
- Runtime: Node.js 24 runtime, warm JIT execution.
- Document: 15-page mixed report containing 8 tables, 12 equations, headings, and nested lists.
- Measurement: Mean of 50 runs, measuring V8 heap delta and wall-clock execution time.
The Operational Trade-Off
The critical operational distinction lies in process boundaries.
Headless LibreOffice clusters require managing external OS-level subprocesses, mounting fonts into container images, and provisioning multi-gigabyte server instances. In serverless or containerized environments (AWS Lambda, Cloudflare Workers, Kubernetes pods), these heavy binaries introduce substantial cold-start penalties, high idle memory costs, and process management headaches under burst concurrency.
Conversely, string templating avoids binary overhead but cannot reliably produce valid OpenXML for non-trivial documents.
The AST compiler pattern provides the balanced path: the lightweight, in-process agility of pure TypeScript paired with the structural correctness of a formal compiler.
9. What’s Next in the Engineering Series
This is Part 3 of our 7-part deep dive into the engineering principles behind md2docx:
- Part 1: From Fragmented Repositories to a Modern Monorepo — Consolidating packages into a unified TypeScript monorepo.
- Part 2: Building a Modern Tiptap-to-DOCX Integration — Browser-native, client-side Word export for rich-text editors.
- Part 3: (You are here) Building a Markdown-to-DOCX Compiler — Canonical deep-dive on the MDAST-to-OpenXML compiler architecture.
- Part 4: Rendering Mermaid Diagrams Across Runtimes — Browser canvas vs. headless Node.js vector rasterization.
- Part 5: Designing an Extensible Plugin Ecosystem — Architecture of the lifecycle hooks and plugin system.
- Part 6: Beyond Basic Markdown: Word MathML, Tables, & Metadata — Native formulas, complex tables, and frontmatter.
- Part 7: Markdown-to-DOCX for GenAI Applications — Resilient document compilation for LLM-generated content.
10. Key Takeaways for Systems Architects
- Treat Documents as Code Targets: A Word document is not a text file with formatting tags; it is an interconnected graph of XML structures governed by a strict schema. Treat document generators as compilers with formal frontends (lexers/parsers), intermediate representations, and backends (code generators).
- Avoid String Interpolation on XML: Direct string replacement cannot reliably track state transitions across overlapping formatting boundaries. Always represent intermediate state as an Abstract Syntax Tree.
- Isolate Visitor Passes: Decouple link/footnote hoisting, block layout, and inline property stacking into independent, testable passes. This allows plugins to hook into lifecycle events (
preprocess,inline,block,postprocess) without destabilizing the core pipeline. - Compile Everywhere: By avoiding binary dependencies (LibreOffice, Pandoc), your document generation pipeline runs identically inside a browser Web Worker, a Node.js microservice, a Bun CLI, or an edge function.
Explore the complete open-source codebase or integrate the engine into your own pipelines:
Did you enjoy this post?
Give it a like to let me know!


