From Fragmented Repositories to a Modern TypeScript Monorepo: The Evolution of md2docx

1. The Modularization Paradox in Document Compilers
Compiling unstructured or semi-structured markup into strict Office Open XML (OOXML / .docx) is fundamentally an Abstract Syntax Tree (AST) compilation problem. What begins as a seemingly modest utility—converting Markdown into Word documents—rapidly compounds into a high-complexity distributed domain:
- Parsing Markdown and GitHub Flavored Markdown into MDAST via Unified and Remark.
- Handling domain-specific AST branches: mathematical formulas (LaTeX via KaTeX / OMML), nested complex tables with cell spans, vector drawings (Mermaid.js), frontmatter metadata, and embedded HTML syntax trees.
- Rendering across dual execution environments: isomorphic browser contexts (client-side export blobs) versus high-throughput Node.js servers (streaming buffers, filesystem caching, and headless image rasterization via Sharp).
- Maintaining integration adapters across downstream frameworks: CLI utilities, TipTap rich text editors, and React markdown rendering components.
In the earliest iterations of the project, we pursued an ideological doctrine of hyper-modularization. The core converter (mdast2docx) lived in an isolated repository. Each specialized capability—image processing, HTML sanitization, table layout calculation—lived in independent satellite repositories or decoupled npm packages.
Hyper-modularization across independent repositories creates the illusion of clean decoupling. In practice, it shifts architectural complexity into operational debt: version matrix mismatches, broken diamond dependencies, out-of-sync linting standards, and multi-hour release cascades.
When an architectural enhancement touched the core visitor pattern in the AST walker, landing that change across downstream plugins required:
- Submitting a pull request in the core engine repository.
- Waiting for CI, tagging a release, and publishing to npm.
- Manually updating
package.jsondependency pins across five distinct plugin repositories. - Triaging subtle dependency drift caused by mismatched TypeScript versions, divergent ESLint configs, or differing bundler output targets.
- Manually synchronizing changelogs and documentation.
The operational overhead of sustaining multiple independent repositories eclipsed the time spent advancing the compiler engine itself. We needed a unified monorepo. But conventional monorepo templates introduced an equally insidious problem: template drift.
2. The Upstream Template Trap and the Turboforge Solution
Monorepo scaffolds have an unwritten expiration date: the exact moment you run git init.
Historically, scaffolding an open-source monorepo meant executing a generator—such as npx create-turbo or a bespoke repository template—and embarking on local customizations. Within three months, the upstream starter would release improvements: a faster linter, stricter TypeScript configurations, optimized GitHub Actions caching rules, or improved packaging tooling.
At that juncture, maintainers face two equally unappealing options:
- Long-Term Divergence: Abandon upstream improvements entirely, allowing build tooling and developer ergonomics to steadily decay into legacy technical debt.
- Manual Cherry-Picking: Painstakingly diffing commits between template repositories, manually resolving configuration merge conflicts, and risking that local custom scripts are inadvertently broken.
flowchart TD subgraph Traditional["Traditional Scaffolding Lifecycle"] A1["Upstream Template v1.0"] --> B1["Monorepo Initialized"] B1 --> C1["Local Customizations Applied"] A1 --> D1["Upstream Template v2.0 (Biome, Node 24, Turbo 2.11)"] C1 -.->|"Divergence Gap (Manual Cherry-Picking / Drift)"| E1["Tooling Stagnation & Config Rot"] end subgraph Turboforge["The Turboforge Paradigm"] A2["Upstream Turboforge Template"] --> B2["md2docx Monorepo"] B2 --> C2["Domain Architecture & Packages"] A2 --> D2["Upstream Engine Upgrades"] D2 -->|"@turboforge/sync (forge-sync)"| E2[".forge-meta.json Tracking"] E2 -->|"AST-Aware Config & Manifest Merges"| B2 end
To resolve this sustainably for md2docx, we adopted Turboforge (turboforge-dev/turboforge). Turboforge treats template updates as a continuous synchronization workflow rather than a one-off scaffolding event—an architectural paradigm directly reusable by any open-source maintainer facing template drift.
Why Maintainers Need Continuous Synchronization
Open-source maintainers managing multi-package TypeScript projects face continuous ecosystem churn: Node runtimes evolve, bundlers shift, linters migrate from ESLint to Biome, and CI security standards tighten. Scaffolding tools solve initialization, but offer no mechanism for evolution.
Turboforge decouples base monorepo mechanics (tooling, CI workflows, linting, release automation) from domain-specific library code through an upstream synchronization engine:
- Deterministic Upstream Tracking: The project root maintains
.forge-meta.json, which tracks the upstream template repository, the exact base commit, and the target synchronization ref:
{
"lastSyncedCommit": "b568041797d57631ba4c5f0d5a7e2cb0896ee56d",
"baseRef": "2b6fbc1edfae264ed3228cb88f7b1a6e380cf330",
"targetRef": "main",
"generatedAt": "2026-10-26T01:50:04.853Z"
}
- Package-Aware AST Merging via
@turboforge/sync: Runningpnpm sync(which invokesforge-sync) computes a three-way reconciliation between the last synchronized upstream commit, incoming upstream template improvements, and the local working tree.
Unlike naive line-based three-way merge tools (such as standard git diff3) that blindly compare text and trigger spurious conflicts on reordered keys or adjacent lines, @turboforge/sync parses configuration files and package manifests directly into Abstract Syntax Trees (ASTs) and structured object graphs:
- Package Manifests (
package.json,pnpm-workspace.yaml): Manifests are parsed into JSON/YAML ASTs. It reconciles upstream template dependency upgrades and baseline scripts while preserving downstream repository modifications—such as local package links (workspace:*), custom dependencies, domain-specific scripts, and scoped metadata. - Linter & Tooling Configurations (
biome.json,tsconfig.json): Instead of textual collisions over formatting presets or path mappings,@turboforge/syncwalks configuration trees. It incorporates upstream rule updates, schema migrations, and compiler target adjustments without overwriting downstream path aliases or custom overrides. - CI & Workflow Templates: CI configurations (
.github/workflows/) are parsed and merged by workflow job and step identities rather than rigid line positions, ensuring upstream security hardening and caching strategies flow seamlessly into customized deployment pipelines.
By adopting Turboforge, maintainers systematically mitigate the recurring maintenance overhead of manual configuration cherry-picking, keeping their monorepos modern over multi-year lifecycles without naive merge collisions.
3. Monorepo Topology: Layered Architecture
Consolidating our ecosystem into a unified workspace under pnpm (version 12.9.0) and turbo (2.11.10) allowed us to cleanly partition 20+ packages into distinct architectural layers.
flowchart TD subgraph Apps["Applications (apps/*)"] Web["@app/web<br/>(Next.js 16 + React 19 + Fumadocs + Playground)"] end subgraph Adapters["Framework & UI Adapters (packages/*)"] ReactMd["@m2d/react-markdown"] TipTap["@m2d/tiptap"] Cli["@m2d/cli"] RemarkDocx["@m2d/remark-docx"] RemarkDocxNode["@m2d/remark-docx-node"] end subgraph Entrypoints["High-Level Facades (packages/*)"] Md2Docx["@m2d/md2docx<br/>(Batteries-Included All-in-One)"] Mdast2Docx["mdast2docx<br/>(Core AST Pipeline)"] end subgraph Extensions["Modular Domain Extensions (packages/*)"] Frontmatter["@m2d/frontmatter"] Table["@m2d/table"] MathPkg["@m2d/math"] ImagePkg["@m2d/image"] ImageNode["@m2d/image-node"] HtmlPkg["@m2d/html"] HtmlNode["@m2d/html-node"] MermaidPkg["@m2d/mermaid"] MermaidNode["@m2d/mermaid-node"] ListPkg["@m2d/list"] CachePkg["@m2d/cache"] end subgraph Foundation["Core Engine & Types (packages/*)"] Core["@m2d/core"] Mdast["@m2d/mdast"] end Web --> Md2Docx Web --> TipTap Web --> ReactMd Cli --> Md2Docx ReactMd --> Core TipTap --> Frontmatter TipTap --> Core Md2Docx --> Core Md2Docx --> RemarkDocx Mdast2Docx --> Core Mdast2Docx --> Table Mdast2Docx --> MathPkg Mdast2Docx --> ImagePkg Mdast2Docx --> HtmlPkg Mdast2Docx --> MermaidPkg Mdast2Docx --> Frontmatter Mdast2Docx --> ListPkg Mdast2Docx --> CachePkg Table --> Core MathPkg --> Core ImagePkg --> Core HtmlPkg --> Core MermaidPkg --> Core Frontmatter --> Core ListPkg --> Core CachePkg --> Core
Architectural Separation: Isomorphic vs. Node-Specific Runtimes
Notice the deliberate split between base packages and their -node counterparts (such as @m2d/image vs @m2d/image-node, @m2d/html vs @m2d/html-node, and @m2d/mermaid vs @m2d/mermaid-node):
- Isomorphic Base Packages (
@m2d/image,@m2d/html): Contain no direct Node.js filesystem (node:fs) or native binary bindings. They operate reliably in modern browser runtimes, Cloudflare Workers, and Edge compute environments using pure AST transformations and standard Web APIs (fetch,Blob,Canvas). - Node Extensions (
@m2d/image-node,@m2d/html-node): Declared as optional peer dependencies withinmdast2docx. They layer on native acceleration—such assharpfor rapid image resizing and format transcoding (WEBP/AVIF to PNG/JPEG for Word compatibility) or local disk caching for downloaded assets.
In pnpm-workspace.yaml, we strictly gate build scripts to prevent arbitrary native execution vulnerabilities across third-party dependencies:
packages:
- apps/*
- packages/*
- tooling/*
- examples/*
allowBuilds:
esbuild: true
sharp: true
onlyBuiltDependencies:
- "@parcel/watcher"
- esbuild
- sharp
overrides:
lodash@>=4.0.0 <=4.17.22: ">=4.17.23"
tmp@<=0.2.3: ">=0.2.4"
typescript: "^6.0.3"
4. Node 24 Native Type-Stripping: Direct Tooling Execution Without Intermediate Transpilation
One of the most persistent drains on monorepo performance is the proliferation of bundlers and transpilers used solely to run internal tooling scripts. Maintainers routinely install ts-node, tsx, babel-node, or create synthetic tsconfig targets just to execute a post-install script or repository housekeeping utility.
With Node.js 24 (where Node.js 24.12 stabilized type stripping and enabled it by default), the runtime natively executes TypeScript files directly without requiring flags like --experimental-strip-types. We leveraged native type stripping across our entire tooling infrastructure.
Every tooling script in oss/md2docx/package.json runs directly via Node without an intermediate compilation step:
{
"scripts": {
"debug:info": "node ./tooling/scripts/debug-info.ts",
"postinstall": "node ./tooling/scripts/postinstall.ts",
"rebrand": "node ./tooling/scripts/rebrand.ts",
"release:aliases": "node ./tooling/scripts/publish-aliases.ts",
"docs": "node ./tooling/scripts/generate-api-docs.ts"
}
}
Node's native execution relies strictly on erasable types—removing TypeScript syntax that carries no runtime semantics, such as type annotations, type aliases, and interfaces.
Maintainers must plan around two operational realities:
- No Runtime Type Checking: Node does not validate types before execution. Syntax errors halt execution, but type mismatches pass silently until a runtime exception occurs. Type checking remains the explicit responsibility of
tsc --noEmitin CI workflows and pre-commit hooks. - Erasable Syntax Only: Node does not perform complex tsconfig code transformations that output runtime JavaScript (such as legacy
enum,namespace, or constructor parameter properties). Scripts using these features must either adopt modern erasable TypeScript idioms (such asas constobject maps and explicit property declarations) or retain a standardtscbuild pass.
The Tooling Execution Comparison
| Tooling Aspect | Legacy Transpiled Setup (tsx / ts-node) | Modern Node 24 (Native Type Stripping) |
|---|---|---|
| Startup Overhead | ~400ms – 1,200ms JIT compilation | < 35ms native startup |
| Dependency Surface | Transpilers, SWC, esbuild binaries | No external runner dependencies |
| CI Cache Invalidation | Frequent (transpiler cache directories) | Minimal (executed directly as raw source) |
| ESM / Type Compatibility | Interop friction (commonjs vs module) | Native ESM-first runtime |
Note: Execution benchmarks measured on an Apple M3 Max (64GB RAM) developer laptop comparing warm Node 24.12 startup against tsx JIT cold transpilation across equivalent CLI utilities.
Paired with Biome 2.6.3, which handles linting, formatting, and import organization across ~1,200 source files in under 120 milliseconds (measured with warm filesystem cache on modern multi-core developer hardware), local developer iteration latency dropped drastically.
5. Granular Multi-Package Coverage: The split-lcov Architecture
Monorepos introduce a well-known dilemma for code coverage. Running test runners package-by-package incurs substantial process startup overhead, degrading CI throughput. Running Vitest once at the monorepo root (vitest run --coverage) yields rapid parallel execution, but produces a single monolithic coverage/lcov.info file.
When uploaded to Codecov or enterprise auditing tools, this monolithic file cannot generate per-package coverage badges or path-accurate coverage flags. Furthermore, absolute paths recorded on CI workers mismatch repository-relative git tree structures.
To solve this cleanly, we engineered tooling/scripts/split-lcov.ts.
flowchart LR A["Vitest Root Runner<br/>(vitest run --coverage)"] --> B["coverage/lcov.info<br/>(Monolithic Absolute Paths)"] B --> C["split-lcov.ts Engine"] D[".forge-cache/packages.json<br/>(Workspace Registry)"] --> C C --> E["coverage/table.lcov"] C --> F["coverage/math.lcov"] C --> G["coverage/core.lcov"] C --> H["coverage/image.lcov"]
The Core Path Transformation Principle
Rather than running complex multi-step test aggregations, the script maps workspace package prefixes from .forge-cache/packages.json to normalize source file paths (SF:) into repository-relative coordinates, partitioning the monolithic LCOV stream into package-specific files:
// Core LCOV transformation logic in tooling/scripts/split-lcov.ts
for (let record of lcovRecords) {
const sfLine = record.find((l) => l.startsWith("SF:"));
if (!sfLine) continue;
const absolutePath = sfLine.slice(3);
const matchedPkg = packages.find((p) => absolutePath.includes(`${p.dir}/`));
if (!matchedPkg) continue;
// Remap CI absolute path to repository-relative path (e.g., packages/table/src/index.ts)
const repoRelativePath = absolutePath.slice(absolutePath.indexOf(matchedPkg.dir));
const normalizedRecord = record.replace(sfLine, `SF:${repoRelativePath}`);
packageRecords.get(matchedPkg.dir)?.push(normalizedRecord);
}
In .github/workflows/ci.yml, the pipeline executes as a unified step:
- name: Build & Test
run: |
pnpm turbo telemetry disable
pnpm build
pnpm test
node ./tooling/scripts/split-lcov.ts
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
- name: Upload Coverage to Codecov
if: env.CODECOV_TOKEN != ''
run: node ./tooling/scripts/upload-coverage.ts
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
This delivers an effective balance: single-pass parallel Vitest execution completed in under 15 seconds (measured across 20+ packages with ~450 unit and integration tests on an Apple M3 Max developer laptop with warm module cache), coupled with individual package coverage flags and badges across Codecov.
6. Frictionless Discoverability: Automated Alias Publishing
When evolving an open-source project, renaming packages or unifying scopes introduces an adoption challenge.
Historically, developers installed mdast2docx, mdast-to-docx, or md-to-docx. When we standardized our scoped architecture under @m2d/* (e.g. @m2d/md2docx), requiring existing users to immediately refactor their import statements would fracture our ecosystem reach and break downstream CI pipelines.
Publishing duplicate source packages introduces maintenance divergence: an alias might lag behind a patch release, or ship with mismatched dependencies. In md2docx, we solved this via declarative metadata and runtime alias synthesis.
Declarative Aliases in package.json
Each package defines its recognized aliases directly inside its own package.json:
{
"name": "mdast2docx",
"version": "1.7.1",
"forge": {
"aliases": [
"md-to-docx",
"mdast-to-docx"
],
"icon": "FileOutput",
"description": "Complete Markdown to DOCX"
}
}
The Synthesis Pipeline: publish-aliases.ts
During automated release workflows (.github/workflows/release.yml), right after Changesets publishes canonical packages, CI triggers publish-aliases.ts:
- name: Publish Aliases
if: steps.changesets.outputs.published == 'true'
run: node ./tooling/scripts/publish-aliases.ts --published-packages '${{ steps.changesets.outputs.publishedPackages }}'
env:
NPM_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
The script dynamically constructs lightweight ESM proxy packages inside a temporary dist-aliases staging area:
- It injects a standardized documentation callout explaining that the package is an official alias.
- It sets up strict dependency delegation: the alias package lists the canonical package as its sole dependency (
dependencies: { [canonical]: pkgJson.version }). - It re-exports all entrypoints directly from the canonical target.
- It publishes the alias under the matching version tag.
sequenceDiagram autonumber actor Dev as Developer / Downstream Project participant npm as npm Registry participant Alias as mdast-to-docx (Alias) participant Canonical as mdast2docx (Canonical Source) Dev->>npm: pnpm add mdast-to-docx@1.7.1 npm->>Alias: Resolves Alias Package Note over Alias: Pure ESM Proxy (Minimal Footprint) Alias->>Canonical: Resolves Dependency @ 1.7.1 npm-->>Dev: Installs Canonical Engine
The result: Preserved ecosystem discoverability, unified version alignment, and minimal manual maintenance overhead.
7. Automated Documentation: TypeDoc to Fumadocs Pipeline
For an AST compiler with 20+ packages, documentation drift poses significant operational risk. If an engineer adds an option to @m2d/table or alters the AST node visitor signature in @m2d/core, updating documentation manually in a disconnected system routinely leads to out-of-date guides.
We engineered a continuous documentation compiler in tooling/scripts/generate-api-docs.ts.
flowchart LR A["packages/*/src/index.ts"] --> B["TypeDoc 0.28 + typedoc-plugin-markdown"] C["typedoc.base.config.ts"] --> B B --> D["Markdown AST Sanitizer & MDX Formatter"] E["packages/*/README.md"] --> F["apps/web/content/docs/[pkg]/v[major]/overview.mdx"] D --> G["apps/web/content/docs/[pkg]/v[major]/api/*.mdx"] H["package.json (forge metadata)"] --> I["apps/web/content/docs/[pkg]/meta.json"]
Key Highlights of the Documentation Engine:
- Versioned API Trees: The script extracts the major semver digit from each package's
package.jsonand compiles API reference documents intoapps/web/content/docs/${pkgDir}/v${major}/api/. - README Projection: The package root
README.mdis automatically copied asoverview.mdx, ensuring npm READMEs and web documentation remain strictly aligned. - Fumadocs Metadata Generation: It generates
meta.jsonfiles complete with Lucide icons (derived from the package'sforge.iconconfig) and navigation titles. - Git Automation: During releases, if documentation changes are detected, CI automatically commits them with
[skip ci], keeping the live Next.js documentation portal (apps/web) perpetually synchronized with released source code.
8. Hardened CI/CD with Cryptographic Provenance
A modern open-source supply chain demands verifiable security. Following recent high-profile registry attacks, simply publishing tarballs with an API token is insufficient for enterprise infrastructure.
In .github/workflows/release.yml, we configure GitHub Actions OIDC permissions to generate signed npm provenance:
permissions:
contents: write
pull-requests: write
id-token: write # Mandatory for npm cryptographic provenance
In root package.json:
{
"publishConfig": {
"access": "public",
"provenance": true
}
}
Whenever @changesets/action executes pnpm release, npm cryptographically verifies the build environment against the GitHub Actions runner identity via Sigstore. Developers adopting mdast2docx or @m2d/md2docx can inspect npm registry metadata and verify:
- The exact commit hash that produced the tarball.
- The workflow run URL on GitHub that executed the build.
- The cryptographic signature proving no intermediate machine tampered with the artifact.
9. Architectural Balance Sheet: Measurable Dividends
Migrating md2docx from fragmented repositories into a modern TypeScript monorepo yielded measurable architectural dividends across velocity, stability, and maintenance overhead:
| Metric | Before (Fragmented Multi-Repo) | After (Unified Monorepo + Turboforge) |
|---|---|---|
| Release Lead Time | ~45 minutes manual cascade | < 3 minutes automated Changesets release |
| Lint & Format Time | 22 seconds across repos (ESLint + Prettier) | < 120ms workspace-wide (Biome 2.6) |
| Tooling Runner Startup | 800ms+ per script (tsx) | ~30ms native Node 24 type stripping |
| Template Drift | High (stagnant configs over 6 months) | Resolved continuously via forge-sync |
| Test Execution | Sequential, disjointed coverage reports | Parallelized Vitest + split-lcov.ts |
| Supply Chain Security | Basic npm token auth | OIDC-backed npm provenance signatures |
Benchmark context: Metrics reflect empirical averages observed across the 20+ package
md2docxworkspace. Local benchmarks (linting, test execution, script startup) were captured on a modern developer workstation (Apple M3 Max, 64GB RAM, Node.js 24.12, warm filesystem cache). Release lead time represents GitHub Actions workflow execution on standardubuntu-latestrunners.
The Core Architectural Insight
A monorepo is not merely a file organization strategy; it is a compiler for engineering velocity. By consolidating our ecosystem under Turboforge and backing it with modern primitives—Node 24 native type stripping, Biome, Vitest split coverage, and automated alias synthesis—we transformed md2docx from a collection of disconnected packages into an enterprise-ready document generation platform.
In Part 2, we will examine client-side document export in Building a Modern Tiptap-to-DOCX Integration, exploring how browser-native OpenXML generation removes reliance on heavyweight server-side conversion containers.
The md2docx Engineering Series
This post is Part 1 of our 7-part deep dive into building an enterprise-ready document compilation platform:
- Part 1: (You are here) From Fragmented Repositories to a Modern Monorepo - Unifying 20+ packages with Turboforge, Node 24 native type-stripping, and automated release pipelines.
- Part 2: Building a Modern Tiptap-to-DOCX Integration - Browser-native OpenXML generation and WYSIWYG export.
- Part 3: Building a Markdown-to-DOCX Compiler - Compiling MDAST visitor passes into strictly validated OpenXML structures.
- Part 4: Rendering Mermaid Diagrams Across Runtimes - Headless SVG rasterization and dimension preservation in browser and Node.js.
- Part 5: Designing an Extensible Plugin Ecosystem - Decoupling AST transformations from OpenXML packing with typed plugins.
- Part 6: Beyond Basic Markdown: Word MathML, Tables, & Metadata - Compiling LaTeX to native
<m:oMath>, nested tables, and frontmatter. - Part 7: Markdown-to-DOCX for GenAI Applications - Deterministic document generation for LLM pipelines and automated enterprise-ready reports.
Did you enjoy this post?
Give it a like to let me know!


