How simonhaenisch/md-to-pdf works
Project type and purpose
• This is a Node.js/TypeScript CLI tool (and library) called “md-to-pdf.”
• It ingests Markdown files (or stdin) and outputs PDF files by converting Markdown→HTML→PDF.
• Key libraries: Marked (Markdown→HTML), highlight.js (syntax‐highlighting), Puppeteer (headless‐Chrome→PDF), Chokidar (watch mode).
File structure
• Top‐level: package.json, tsconfig*.json, .github/CI, tests, README, etc.
• src/cli.ts: CLI entrypoint (argument parsing, watch‐mode orchestration).
• src/index.ts: programmatic API export.
• src/lib/: core modules—config management, file I/O, HTML generation, HTTP server, PDF rendering.
• src/test/: unit/integration tests and fixtures.
README for additional insights
• Describes features (concurrency, watch, custom styles/scripts, front-matter, headers/footers).
• Explains programmatic API.
• Documents dependencies and default behaviors (local file server on random/‐D port, CSS injection, MathJax support).
Main components and interactions
• CLI Layer (src/cli.ts)
– Parses CLI arguments (options, paths)
– Decides between one-off conversion or watch mode (uses Chokidar)
• Programmatic API (src/index.ts)
– Exposes mdToPdf({ path|content }, config) → Promise<{ filename, content }>
• Configuration Module (src/lib/config.ts)
– Merges defaults ← config file ← front-matter ← CLI args
• File I/O
– read-file.ts: read Markdown or HTML input
– get-output-file-path.ts: resolve destination path
• Markdown→HTML Conversion
– get-marked-with-highlighter.ts: configure Marked + highlight.js
– get-html.ts: wrap HTML document (styles, scripts, front-matter)
• Static File Server (src/lib/serve-dir.ts)
– Serves baseDir for Puppeteer when loading local assets (images, CSS)
• PDF Rendering (src/lib/md-to-pdf.ts & generate-output.ts)
– Launch Puppeteer (headless Chrome)
– page.setContent(HTML) → page.pdf(options)
• Output
– Write PDF bytes to disk (or return in memory)
• External Services & Libraries
– Marked, highlight.js, Puppeteer, Gray-Matter, Chokidar
1) CLI/API → Config Module
2) Config → File I/O (read Markdown)
3) Markdown + Highlight.js → HTML Generator
4) HTML → (optional) Static HTTP Server → Puppeteer
5) Puppeteer → PDF bytes
6) PDF bytes → File System or stdout
Architectural patterns and design principles
• Pipeline pattern: sequential transform steps (read → parse → render → output)
• Modular separation: CLI vs core library vs HTTP server
• Concurrency: Promise.all on multiple files
• Inversion of Control: core mdToPdf function accepts config and input, CLI and API layer simply call into it
• Single responsibility modules (one file = one concern)
Detail
• Module filenames or logical names in labels for accuracy.
• Front-matter and config sources as separate inputs.