@markdown-viewer/documd 5.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +99 -0
  2. package/browser-renderer.js +12638 -0
  3. package/documd.js +1050 -0
  4. package/package.json +51 -0
  5. package/stencils/alibaba_cloud.json +1 -0
  6. package/stencils/android.json +1 -0
  7. package/stencils/arrows.json +1 -0
  8. package/stencils/atlassian.json +1 -0
  9. package/stencils/aws.json +1 -0
  10. package/stencils/aws2.json +1 -0
  11. package/stencils/aws3.json +1 -0
  12. package/stencils/aws3d.json +1 -0
  13. package/stencils/aws4.json +1 -0
  14. package/stencils/azure.json +1 -0
  15. package/stencils/basic.json +1 -0
  16. package/stencils/bootstrap.json +1 -0
  17. package/stencils/bpmn.json +1 -0
  18. package/stencils/cabinets.json +1 -0
  19. package/stencils/cisco.json +1 -0
  20. package/stencils/cisco19.json +1 -0
  21. package/stencils/cisco_safe.json +1 -0
  22. package/stencils/citrix.json +1 -0
  23. package/stencils/citrix2.json +1 -0
  24. package/stencils/eip.json +1 -0
  25. package/stencils/electrical.json +1 -0
  26. package/stencils/floorplan.json +1 -0
  27. package/stencils/flowchart.json +1 -0
  28. package/stencils/fluid_power.json +1 -0
  29. package/stencils/gcp.json +1 -0
  30. package/stencils/gcp2.json +1 -0
  31. package/stencils/gmdl.json +1 -0
  32. package/stencils/ibm.json +1 -0
  33. package/stencils/ibm_cloud.json +1 -0
  34. package/stencils/index.json +298 -0
  35. package/stencils/ios7.json +1 -0
  36. package/stencils/kubernetes.json +1 -0
  37. package/stencils/kubernetes2.json +1 -0
  38. package/stencils/lean_mapping.json +1 -0
  39. package/stencils/mockup.json +1 -0
  40. package/stencils/mscae.json +1 -0
  41. package/stencils/networks.json +1 -0
  42. package/stencils/networks2.json +1 -0
  43. package/stencils/office.json +1 -0
  44. package/stencils/openstack.json +1 -0
  45. package/stencils/pid.json +1 -0
  46. package/stencils/rack.json +1 -0
  47. package/stencils/salesforce.json +1 -0
  48. package/stencils/signs.json +1 -0
  49. package/stencils/sitemap.json +1 -0
  50. package/stencils/veeam.json +1 -0
  51. package/stencils/vvd.json +1 -0
  52. package/stencils/webicons.json +1 -0
  53. package/stencils/weblogos.json +1 -0
  54. package/styles.css +1 -0
  55. package/themes/code-themes/business-contrast.json +31 -0
  56. package/themes/code-themes/colorful.json +32 -0
  57. package/themes/code-themes/cool-modern.json +31 -0
  58. package/themes/code-themes/dracula-code.json +31 -0
  59. package/themes/code-themes/light-clean.json +31 -0
  60. package/themes/code-themes/midnight-code.json +31 -0
  61. package/themes/code-themes/nord-code.json +31 -0
  62. package/themes/code-themes/solarized-dark-code.json +31 -0
  63. package/themes/code-themes/vscode-dark-code.json +31 -0
  64. package/themes/code-themes/vscode-light-code.json +31 -0
  65. package/themes/code-themes/warm-book.json +31 -0
  66. package/themes/color-schemes/candy.json +37 -0
  67. package/themes/color-schemes/carbon.json +37 -0
  68. package/themes/color-schemes/cool.json +37 -0
  69. package/themes/color-schemes/dracula-soft.json +37 -0
  70. package/themes/color-schemes/draft.json +37 -0
  71. package/themes/color-schemes/forest.json +37 -0
  72. package/themes/color-schemes/gruvbox-dark.json +37 -0
  73. package/themes/color-schemes/ink.json +37 -0
  74. package/themes/color-schemes/midnight.json +37 -0
  75. package/themes/color-schemes/neutral.json +37 -0
  76. package/themes/color-schemes/nord-dark.json +37 -0
  77. package/themes/color-schemes/obsidian.json +37 -0
  78. package/themes/color-schemes/ocean.json +37 -0
  79. package/themes/color-schemes/rainbow.json +46 -0
  80. package/themes/color-schemes/sakura.json +37 -0
  81. package/themes/color-schemes/sepia.json +37 -0
  82. package/themes/color-schemes/slate.json +37 -0
  83. package/themes/color-schemes/solarized-dark.json +37 -0
  84. package/themes/color-schemes/vscode-dark.json +45 -0
  85. package/themes/color-schemes/vscode-light.json +45 -0
  86. package/themes/color-schemes/warm.json +37 -0
  87. package/themes/font-config.json +211 -0
  88. package/themes/layout-schemes/book.json +40 -0
  89. package/themes/layout-schemes/compact.json +40 -0
  90. package/themes/layout-schemes/display.json +40 -0
  91. package/themes/layout-schemes/editorial.json +40 -0
  92. package/themes/layout-schemes/formal-paper.json +40 -0
  93. package/themes/layout-schemes/formal.json +40 -0
  94. package/themes/layout-schemes/magazine.json +40 -0
  95. package/themes/layout-schemes/regular.json +40 -0
  96. package/themes/layout-schemes/standard.json +40 -0
  97. package/themes/layout-schemes/vscode.json +62 -0
  98. package/themes/presets/academic.json +27 -0
  99. package/themes/presets/business.json +22 -0
  100. package/themes/presets/candy.json +23 -0
  101. package/themes/presets/carbon.json +18 -0
  102. package/themes/presets/century.json +22 -0
  103. package/themes/presets/default.json +29 -0
  104. package/themes/presets/dracula.json +18 -0
  105. package/themes/presets/elegant.json +22 -0
  106. package/themes/presets/forest.json +22 -0
  107. package/themes/presets/garamond.json +22 -0
  108. package/themes/presets/gruvbox.json +18 -0
  109. package/themes/presets/handwritten.json +23 -0
  110. package/themes/presets/heiti.json +22 -0
  111. package/themes/presets/magazine.json +24 -0
  112. package/themes/presets/manuscript.json +22 -0
  113. package/themes/presets/midnight.json +18 -0
  114. package/themes/presets/minimal.json +22 -0
  115. package/themes/presets/mixed.json +24 -0
  116. package/themes/presets/newspaper.json +24 -0
  117. package/themes/presets/nord.json +18 -0
  118. package/themes/presets/obsidian.json +18 -0
  119. package/themes/presets/ocean.json +22 -0
  120. package/themes/presets/official.json +29 -0
  121. package/themes/presets/palatino.json +22 -0
  122. package/themes/presets/rainbow.json +23 -0
  123. package/themes/presets/slate.json +18 -0
  124. package/themes/presets/solarized-dark.json +18 -0
  125. package/themes/presets/swiss.json +22 -0
  126. package/themes/presets/technical.json +22 -0
  127. package/themes/presets/typewriter.json +23 -0
  128. package/themes/presets/verdana.json +22 -0
  129. package/themes/presets/vscode-dark.json +24 -0
  130. package/themes/presets/vscode.json +24 -0
  131. package/themes/presets/water.json +22 -0
  132. package/themes/registry.json +116 -0
  133. package/themes/table-styles/academic.json +30 -0
  134. package/themes/table-styles/borderless.json +26 -0
  135. package/themes/table-styles/compact.json +24 -0
  136. package/themes/table-styles/grid.json +22 -0
  137. package/themes/table-styles/high-contrast.json +22 -0
  138. package/themes/table-styles/minimal-gray.json +26 -0
  139. package/themes/table-styles/modern-tech.json +34 -0
  140. package/themes/table-styles/professional.json +34 -0
  141. package/themes/table-styles/vscode-clean.json +26 -0
  142. package/themes/table-styles/zebra.json +22 -0
package/documd.js ADDED
@@ -0,0 +1,1050 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs/promises';
6
+ import http from 'node:http';
7
+ import path from 'node:path';
8
+ import process from 'node:process';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ import { chromium } from 'playwright-core';
12
+
13
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
14
+ // When installed/published from dist/cli, the renderer assets live next to
15
+ // this file; in development the script runs from scripts/ and the built
16
+ // assets live in ../dist/cli.
17
+ const cliAssetDir = existsSync(path.join(scriptDir, 'browser-renderer.js'))
18
+ ? scriptDir
19
+ : path.resolve(scriptDir, '..', 'dist', 'cli');
20
+
21
+ // Version comes from the package.json that ships next to this file (dist/cli)
22
+ // or the repository root in development.
23
+ const CLI_PKG_PATH = existsSync(path.join(scriptDir, 'package.json'))
24
+ ? path.join(scriptDir, 'package.json')
25
+ : path.resolve(scriptDir, '..', 'package.json');
26
+ const CLI_PKG = JSON.parse(readFileSync(CLI_PKG_PATH, 'utf8'));
27
+ const CLI_VERSION = CLI_PKG.version;
28
+ const CLI_HOMEPAGE = 'https://docu.md';
29
+
30
+ const HELP = `documd v${CLI_VERSION} — ${CLI_HOMEPAGE}
31
+ Render Markdown / diagrams / books with headless Chrome
32
+
33
+ Usage:
34
+ documd <input> [--format <f>] [-o <output>] [options]
35
+
36
+ Output formats (--format; inferred from the output extension when omitted):
37
+ html, epub, docx, pdf markdown / SUMMARY.md (--book) documents
38
+ svg, png, drawio diagram sources (PlantUML/Mermaid/DOT/Vega/...)
39
+
40
+ Options:
41
+ -o, --output <file> Output path
42
+ --format <f> html, epub, docx, pdf, svg, png or drawio
43
+ -b, --book Whole-book export: input is a GitBook SUMMARY.md
44
+ --diagram-type <t> Diagram renderer (default: inferred from the extension)
45
+ -t, --theme <id> Viewer theme (default: default)
46
+ --title <text> Override the document title
47
+ --language <code> Document language code (default: en)
48
+ --frontmatter <mode> hide, table, or raw (default: hide)
49
+ --table-layout <mode> left, center, or center-full-width
50
+ --image-layout <mode> left or center (default: center)
51
+ --diagram-layout <mode> left or center (default: center)
52
+ --merge-empty-cells Merge empty Markdown table cells
53
+ --chrome <path> Explicit Chrome executable path
54
+ --timeout <seconds> Overall render timeout (default: 120)
55
+ -v, --version Print the version and exit
56
+ -h, --help Show this help
57
+
58
+ Website: ${CLI_HOMEPAGE}
59
+ `;
60
+
61
+ function takeValue(args, index, option) {
62
+ const value = args[index + 1];
63
+ if (!value || value.startsWith('-')) throw new Error(`${option} requires a value`);
64
+ return value;
65
+ }
66
+
67
+ const OUTPUT_FORMATS = ['html', 'epub', 'docx', 'pdf', 'svg', 'png', 'drawio'];
68
+ const DIAGRAM_FORMATS = ['svg', 'png', 'drawio'];
69
+ const OUTPUT_EXT_FORMATS = {
70
+ '.html': 'html',
71
+ '.epub': 'epub',
72
+ '.docx': 'docx',
73
+ '.pdf': 'pdf',
74
+ '.svg': 'svg',
75
+ '.png': 'png',
76
+ '.drawio': 'drawio',
77
+ };
78
+ const DIAGRAM_EXT_TYPES = {
79
+ '.puml': 'plantuml',
80
+ '.plantuml': 'plantuml',
81
+ '.wsd': 'plantuml',
82
+ '.mmd': 'mermaid',
83
+ '.mermaid': 'mermaid',
84
+ '.dot': 'dot',
85
+ '.gv': 'dot',
86
+ '.vega': 'vega',
87
+ '.vl': 'vega-lite',
88
+ '.drawio': 'drawio',
89
+ '.echarts': 'echarts',
90
+ '.svg': 'svg',
91
+ '.infographic': 'infographic',
92
+ '.canvas': 'canvas',
93
+ };
94
+
95
+ function isDiagramInput(inputPath) {
96
+ return Boolean(DIAGRAM_EXT_TYPES[path.extname(inputPath).toLowerCase()]);
97
+ }
98
+
99
+ function inferDiagramType(inputPath) {
100
+ return DIAGRAM_EXT_TYPES[path.extname(inputPath).toLowerCase()] || null;
101
+ }
102
+
103
+ export function parseArgs(args) {
104
+ const options = {
105
+ theme: 'default',
106
+ language: 'en',
107
+ frontmatterDisplay: 'hide',
108
+ tableLayout: 'center',
109
+ imageLayout: 'center',
110
+ diagramLayout: 'center',
111
+ tableMergeEmpty: false,
112
+ timeoutMs: 120_000,
113
+ };
114
+ const positional = [];
115
+
116
+ for (let i = 0; i < args.length; i += 1) {
117
+ const arg = args[i];
118
+ if (arg === '-h' || arg === '--help') {
119
+ options.help = true;
120
+ } else if (arg === '-v' || arg === '--version') {
121
+ options.version = true;
122
+ } else if (arg === '-b' || arg === '--book') {
123
+ options.bookMode = true;
124
+ } else if (arg === '--diagram-type') {
125
+ options.diagramType = takeValue(args, i, arg);
126
+ i += 1;
127
+ } else if (arg === '--format') {
128
+ options.format = takeValue(args, i, arg);
129
+ i += 1;
130
+ } else if (arg === '-o' || arg === '--output') {
131
+ options.output = takeValue(args, i, arg);
132
+ i += 1;
133
+ } else if (arg === '-t' || arg === '--theme') {
134
+ options.theme = takeValue(args, i, arg);
135
+ i += 1;
136
+ } else if (arg === '--title') {
137
+ options.title = takeValue(args, i, arg);
138
+ i += 1;
139
+ } else if (arg === '--language') {
140
+ options.language = takeValue(args, i, arg);
141
+ i += 1;
142
+ } else if (arg === '--frontmatter') {
143
+ options.frontmatterDisplay = takeValue(args, i, arg);
144
+ i += 1;
145
+ } else if (arg === '--table-layout') {
146
+ options.tableLayout = takeValue(args, i, arg);
147
+ i += 1;
148
+ } else if (arg === '--image-layout') {
149
+ options.imageLayout = takeValue(args, i, arg);
150
+ i += 1;
151
+ } else if (arg === '--diagram-layout') {
152
+ options.diagramLayout = takeValue(args, i, arg);
153
+ i += 1;
154
+ } else if (arg === '--merge-empty-cells') {
155
+ options.tableMergeEmpty = true;
156
+ } else if (arg === '--chrome') {
157
+ options.chromePath = takeValue(args, i, arg);
158
+ i += 1;
159
+ } else if (arg === '--timeout') {
160
+ const seconds = Number(takeValue(args, i, arg));
161
+ if (!Number.isFinite(seconds) || seconds <= 0) {
162
+ throw new Error('--timeout must be a positive number of seconds');
163
+ }
164
+ options.timeoutMs = seconds * 1000;
165
+ i += 1;
166
+ } else if (arg.startsWith('-')) {
167
+ throw new Error(`Unknown option: ${arg}`);
168
+ } else {
169
+ positional.push(arg);
170
+ }
171
+ }
172
+
173
+ if (!options.help && !options.version && positional.length !== 1) {
174
+ throw new Error('Exactly one input Markdown file is required');
175
+ }
176
+ if (!['hide', 'table', 'raw'].includes(options.frontmatterDisplay)) {
177
+ throw new Error('--frontmatter must be hide, table, or raw');
178
+ }
179
+ if (!['left', 'center', 'center-full-width'].includes(options.tableLayout)) {
180
+ throw new Error('--table-layout must be left, center, or center-full-width');
181
+ }
182
+ if (!['left', 'center'].includes(options.imageLayout)) {
183
+ throw new Error('--image-layout must be left or center');
184
+ }
185
+ if (!['left', 'center'].includes(options.diagramLayout)) {
186
+ throw new Error('--diagram-layout must be left or center');
187
+ }
188
+ if (options.format && !OUTPUT_FORMATS.includes(options.format)) {
189
+ throw new Error('--format must be html, epub, docx, pdf, svg, png or drawio');
190
+ }
191
+
192
+ options.input = positional[0];
193
+
194
+ // help/version need no input or format inference.
195
+ if (options.help || options.version) {
196
+ return options;
197
+ }
198
+
199
+ // Infer the output format when --format is omitted.
200
+ if (!options.format) {
201
+ if (options.output) {
202
+ const ext = path.extname(options.output).toLowerCase();
203
+ options.format = OUTPUT_EXT_FORMATS[ext];
204
+ if (!options.format) {
205
+ throw new Error(`Cannot infer --format from output "${options.output}"; use --format html|epub|docx|pdf|svg|png|drawio`);
206
+ }
207
+ } else if (options.bookMode) {
208
+ options.format = 'epub';
209
+ } else if (isDiagramInput(options.input)) {
210
+ options.format = 'svg';
211
+ } else {
212
+ options.format = 'html';
213
+ }
214
+ }
215
+
216
+ const diagramInput = isDiagramInput(options.input);
217
+ if (DIAGRAM_FORMATS.includes(options.format)) {
218
+ if (!diagramInput) {
219
+ throw new Error(`Format "${options.format}" requires a diagram input (PlantUML/Mermaid/DOT/Vega/...); "${options.input}" is not one`);
220
+ }
221
+ options.diagramMode = true;
222
+ } else if (diagramInput) {
223
+ throw new Error(`Diagram input "${options.input}" cannot be exported as ${options.format}; use --format svg, png or drawio`);
224
+ }
225
+
226
+ if (options.bookMode) {
227
+ if (!['epub', 'docx', 'pdf'].includes(options.format)) {
228
+ throw new Error('--book requires --format epub, docx or pdf');
229
+ }
230
+ }
231
+
232
+ return options;
233
+ }
234
+
235
+ /**
236
+ * Parse a GitBook SUMMARY.md into book pages (same format as the viewer's
237
+ * GitBook panel): `- [Title](relative-link)` with indentation depth.
238
+ */
239
+ export function parseSummaryPages(summaryContent, summaryDir) {
240
+ const pages = [];
241
+ for (const line of summaryContent.split(/\r?\n/)) {
242
+ const match = line.match(/^(\s*)(?:[-*+]|\d+\.)\s+\[([^\]]+)\]\(([^)]+)\)\s*$/);
243
+ if (!match) continue;
244
+ const indent = match[1] || '';
245
+ const title = match[2].trim();
246
+ const target = match[3].trim();
247
+ if (!target || /^(?:mailto:|javascript:|#)/i.test(target)) continue;
248
+ let href = target;
249
+ if (!href.startsWith('http')) {
250
+ href = href.replace(/^\.?\//, '');
251
+ if (summaryDir) {
252
+ href = path.posix.join(summaryDir.replace(/\\/g, '/'), href);
253
+ }
254
+ }
255
+ const depth = Math.floor(indent.replace(/\t/g, ' ').length / 2);
256
+ pages.push({ href, title, depth });
257
+ }
258
+ return pages;
259
+ }
260
+
261
+ function outputPathFor(inputPath, requestedOutput, format) {
262
+ if (requestedOutput) return path.resolve(requestedOutput);
263
+ const parsed = path.parse(inputPath);
264
+ const extension = format === 'epub' ? '.epub' : format === 'docx' ? '.docx' : format === 'pdf' ? '.pdf' : DIAGRAM_FORMATS.includes(format) ? `.${format}` : '.html';
265
+ return path.join(parsed.dir, `${parsed.name}${extension}`);
266
+ }
267
+
268
+ export async function ensureOutputDirectory(outputPath) {
269
+ const outputDirectory = path.dirname(outputPath);
270
+ try {
271
+ const stats = await fs.stat(outputDirectory);
272
+ if (!stats.isDirectory()) {
273
+ throw new Error(`Output parent is not a directory: ${outputDirectory}`);
274
+ }
275
+ } catch (error) {
276
+ if (error?.code !== 'ENOENT') throw error;
277
+ await fs.mkdir(outputDirectory, { recursive: true });
278
+ }
279
+ }
280
+
281
+ function mimeType(filePath) {
282
+ const extension = path.extname(filePath).toLowerCase();
283
+ return {
284
+ '.css': 'text/css; charset=utf-8',
285
+ '.gif': 'image/gif',
286
+ '.html': 'text/html; charset=utf-8',
287
+ '.jpeg': 'image/jpeg',
288
+ '.jpg': 'image/jpeg',
289
+ '.js': 'text/javascript; charset=utf-8',
290
+ '.json': 'application/json; charset=utf-8',
291
+ '.png': 'image/png',
292
+ '.svg': 'image/svg+xml; charset=utf-8',
293
+ '.webp': 'image/webp',
294
+ '.woff': 'font/woff',
295
+ '.woff2': 'font/woff2',
296
+ }[extension] || 'application/octet-stream';
297
+ }
298
+
299
+ function isWithin(root, candidate) {
300
+ const relative = path.relative(root, candidate);
301
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
302
+ }
303
+
304
+ async function sendFile(response, filePath) {
305
+ try {
306
+ const data = await fs.readFile(filePath);
307
+ response.writeHead(200, {
308
+ 'content-type': mimeType(filePath),
309
+ 'cache-control': 'no-store',
310
+ });
311
+ response.end(data);
312
+ } catch (error) {
313
+ response.writeHead(error?.code === 'ENOENT' ? 404 : 500);
314
+ response.end(error?.code === 'ENOENT' ? 'Not found' : 'Unable to read file');
315
+ }
316
+ }
317
+
318
+ function rendererHtml(basePath) {
319
+ return `<!doctype html>
320
+ <html lang="en">
321
+ <head>
322
+ <meta charset="utf-8">
323
+ <meta name="viewport" content="width=device-width, initial-scale=1">
324
+ <link rel="icon" href="data:,">
325
+ <link rel="stylesheet" href="${basePath}/styles.css">
326
+ </head>
327
+ <body>
328
+ <div id="markdown-page"><div id="markdown-content"></div></div>
329
+ <script src="${basePath}/browser-renderer.js"></script>
330
+ </body>
331
+ </html>`;
332
+ }
333
+
334
+ function virtualDocumentDirectory(documentDir) {
335
+ const normalized = documentDir.replace(/\\/g, '/');
336
+ if (normalized.startsWith('/')) return `__root__${normalized}`;
337
+ return normalized;
338
+ }
339
+
340
+ function localPathFromVirtual(value) {
341
+ if (value.startsWith('__root__/')) return `/${value.slice('__root__/'.length)}`;
342
+ return value.replace(/\//g, path.sep);
343
+ }
344
+
345
+ async function startAssetServer(documentDir) {
346
+ const token = crypto.randomBytes(18).toString('hex');
347
+ const basePath = `/__documd/${token}`;
348
+ const virtualDirectory = virtualDocumentDirectory(documentDir);
349
+ const rendererPath = `${basePath}/fs/${virtualDirectory}/__documd_renderer__.html`;
350
+
351
+ const server = http.createServer(async (request, response) => {
352
+ try {
353
+ const url = new URL(request.url || '/', 'http://127.0.0.1');
354
+ const decodedPathname = decodeURIComponent(url.pathname);
355
+ if (decodedPathname === rendererPath) {
356
+ response.writeHead(200, {
357
+ 'content-type': 'text/html; charset=utf-8',
358
+ 'cache-control': 'no-store',
359
+ });
360
+ response.end(rendererHtml(basePath));
361
+ return;
362
+ }
363
+
364
+ if (url.pathname === `${basePath}/file`) {
365
+ const requestedPath = url.searchParams.get('path');
366
+ if (!requestedPath) {
367
+ response.writeHead(400).end('Missing path');
368
+ return;
369
+ }
370
+ let localPath = requestedPath;
371
+ if (localPath.toLowerCase().startsWith('file:')) {
372
+ localPath = fileURLToPath(localPath);
373
+ } else if (!path.isAbsolute(localPath)) {
374
+ localPath = path.resolve(documentDir, localPath);
375
+ }
376
+ await sendFile(response, localPath);
377
+ return;
378
+ }
379
+
380
+ if (url.pathname.startsWith(`${basePath}/document/`)) {
381
+ const relativePath = decodeURIComponent(url.pathname.slice(`${basePath}/document/`.length));
382
+ const localPath = path.resolve(documentDir, relativePath);
383
+ if (!isWithin(documentDir, localPath)) {
384
+ response.writeHead(403).end('Outside document directory');
385
+ return;
386
+ }
387
+ await sendFile(response, localPath);
388
+ return;
389
+ }
390
+
391
+ if (decodedPathname.startsWith(`${basePath}/fs/`)) {
392
+ const virtualPath = decodedPathname.slice(`${basePath}/fs/`.length);
393
+ await sendFile(response, localPathFromVirtual(virtualPath));
394
+ return;
395
+ }
396
+
397
+ const assetPrefix = `${basePath}/`;
398
+ if (url.pathname.startsWith(assetPrefix)) {
399
+ const relativePath = decodeURIComponent(url.pathname.slice(assetPrefix.length));
400
+ const localPath = path.resolve(cliAssetDir, relativePath);
401
+ if (!isWithin(cliAssetDir, localPath)) {
402
+ response.writeHead(403).end('Outside asset directory');
403
+ return;
404
+ }
405
+ await sendFile(response, localPath);
406
+ return;
407
+ }
408
+
409
+ response.writeHead(404).end('Not found');
410
+ } catch {
411
+ response.writeHead(500).end('Internal server error');
412
+ }
413
+ });
414
+
415
+ await new Promise((resolve, reject) => {
416
+ server.once('error', reject);
417
+ server.listen(0, '127.0.0.1', resolve);
418
+ });
419
+
420
+ const address = server.address();
421
+ if (!address || typeof address === 'string') {
422
+ server.close();
423
+ throw new Error('Unable to determine renderer server address');
424
+ }
425
+
426
+ const origin = `http://127.0.0.1:${address.port}`;
427
+ return {
428
+ pageUrl: `${origin}${rendererPath}`,
429
+ documentBaseUrl: `${origin}${basePath}/fs/${virtualDirectory}`,
430
+ fileReadUrl: `${origin}${basePath}/file`,
431
+ resourceBaseUrl: `${origin}${basePath}/`,
432
+ close: () => new Promise((resolve) => server.close(resolve)),
433
+ };
434
+ }
435
+
436
+ async function withTimeout(promise, timeoutMs) {
437
+ let timeout;
438
+ try {
439
+ return await Promise.race([
440
+ promise,
441
+ new Promise((_, reject) => {
442
+ timeout = setTimeout(
443
+ () => reject(new Error(`Render timed out after ${timeoutMs / 1000} seconds`)),
444
+ timeoutMs,
445
+ );
446
+ }),
447
+ ]);
448
+ } finally {
449
+ clearTimeout(timeout);
450
+ }
451
+ }
452
+
453
+ export async function renderMarkdownFile(options) {
454
+ const inputPath = path.resolve(options.input);
455
+ const outputPath = outputPathFor(inputPath, options.output, options.format);
456
+ const markdown = await fs.readFile(inputPath, 'utf8');
457
+
458
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
459
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
460
+ });
461
+
462
+ const server = await startAssetServer(path.dirname(inputPath));
463
+ let browser;
464
+ try {
465
+ browser = await chromium.launch({
466
+ headless: true,
467
+ ...(options.chromePath
468
+ ? { executablePath: path.resolve(options.chromePath) }
469
+ : { channel: 'chrome' }),
470
+ });
471
+
472
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
473
+ const browserErrors = [];
474
+ page.on('console', (message) => {
475
+ if (message.type() === 'error') browserErrors.push(message.text());
476
+ });
477
+ page.on('pageerror', (error) => browserErrors.push(error.message));
478
+
479
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
480
+ await page.waitForFunction(() => typeof window.markdownCli?.render === 'function');
481
+
482
+ const html = await withTimeout(page.evaluate((request) => {
483
+ return window.markdownCli.render(request);
484
+ }, {
485
+ markdown,
486
+ filename: path.basename(inputPath),
487
+ title: options.title,
488
+ theme: options.theme,
489
+ language: options.language,
490
+ frontmatterDisplay: options.frontmatterDisplay,
491
+ tableMergeEmpty: options.tableMergeEmpty,
492
+ tableLayout: options.tableLayout,
493
+ imageLayout: options.imageLayout,
494
+ diagramLayout: options.diagramLayout,
495
+ documentPath: inputPath,
496
+ documentDir: path.dirname(inputPath),
497
+ documentBaseUrl: server.documentBaseUrl,
498
+ fileReadUrl: server.fileReadUrl,
499
+ resourceBaseUrl: server.resourceBaseUrl,
500
+ }), options.timeoutMs);
501
+
502
+ await ensureOutputDirectory(outputPath);
503
+ await fs.writeFile(outputPath, html, 'utf8');
504
+ return { outputPath, browserErrors };
505
+ } finally {
506
+ await browser?.close();
507
+ await server.close();
508
+ }
509
+ }
510
+
511
+ export async function snapshotMarkdownFile(options) {
512
+ const inputPath = path.resolve(options.input);
513
+ const markdown = await fs.readFile(inputPath, 'utf8');
514
+
515
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
516
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
517
+ });
518
+
519
+ const server = await startAssetServer(path.dirname(inputPath));
520
+ let browser;
521
+ try {
522
+ browser = await chromium.launch({
523
+ headless: true,
524
+ ...(options.chromePath
525
+ ? { executablePath: path.resolve(options.chromePath) }
526
+ : { channel: 'chrome' }),
527
+ });
528
+
529
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
530
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
531
+ await page.waitForFunction(() => typeof window.markdownCli?.snapshotDom === 'function');
532
+
533
+ return await withTimeout(page.evaluate((request) => {
534
+ return window.markdownCli.snapshotDom(request);
535
+ }, {
536
+ markdown,
537
+ filename: path.basename(inputPath),
538
+ title: options.title,
539
+ theme: options.theme,
540
+ language: options.language,
541
+ frontmatterDisplay: options.frontmatterDisplay,
542
+ tableMergeEmpty: options.tableMergeEmpty,
543
+ tableLayout: options.tableLayout,
544
+ documentPath: inputPath,
545
+ documentDir: path.dirname(inputPath),
546
+ documentBaseUrl: server.documentBaseUrl,
547
+ fileReadUrl: server.fileReadUrl,
548
+ resourceBaseUrl: server.resourceBaseUrl,
549
+ }), options.timeoutMs);
550
+ } finally {
551
+ await browser?.close();
552
+ await server.close();
553
+ }
554
+ }
555
+
556
+ function base64ToBuffer(base64) {
557
+ // The page serializes bytes with String.fromCharCode, so the base64 payload
558
+ // must be decoded as latin1 to recover the original binary bytes.
559
+ return Buffer.from(Buffer.from(base64, 'base64').toString('latin1'), 'binary');
560
+ }
561
+
562
+ /**
563
+ * Run the REAL single-document EPUB export pipeline (same code path as the
564
+ * extension: HTML staticizing -> collectEpubCss -> JSZip packaging) and write
565
+ * the generated .epub to disk.
566
+ */
567
+ export async function exportMarkdownEpub(options) {
568
+ const inputPath = path.resolve(options.input);
569
+ const outputPath = outputPathFor(inputPath, options.output, 'epub');
570
+ const markdown = await fs.readFile(inputPath, 'utf8');
571
+
572
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
573
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
574
+ });
575
+
576
+ const server = await startAssetServer(path.dirname(inputPath));
577
+ let browser;
578
+ try {
579
+ browser = await chromium.launch({
580
+ headless: true,
581
+ ...(options.chromePath
582
+ ? { executablePath: path.resolve(options.chromePath) }
583
+ : { channel: 'chrome' }),
584
+ });
585
+
586
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
587
+ const browserErrors = [];
588
+ page.on('console', (message) => {
589
+ if (message.type() === 'error') browserErrors.push(message.text());
590
+ });
591
+ page.on('pageerror', (error) => browserErrors.push(error.message));
592
+
593
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
594
+ await page.waitForFunction(() => typeof window.markdownCli?.renderEpub === 'function');
595
+
596
+ const result = await withTimeout(page.evaluate((request) => {
597
+ return window.markdownCli.renderEpub(request);
598
+ }, {
599
+ markdown,
600
+ filename: path.basename(inputPath),
601
+ title: options.title,
602
+ theme: options.theme,
603
+ language: options.language,
604
+ frontmatterDisplay: options.frontmatterDisplay,
605
+ tableMergeEmpty: options.tableMergeEmpty,
606
+ tableLayout: options.tableLayout,
607
+ imageLayout: options.imageLayout,
608
+ diagramLayout: options.diagramLayout,
609
+ documentPath: inputPath,
610
+ documentDir: path.dirname(inputPath),
611
+ documentBaseUrl: server.documentBaseUrl,
612
+ fileReadUrl: server.fileReadUrl,
613
+ resourceBaseUrl: server.resourceBaseUrl,
614
+ }), options.timeoutMs);
615
+
616
+ await ensureOutputDirectory(outputPath);
617
+ await fs.writeFile(outputPath, base64ToBuffer(result.base64));
618
+ return { outputPath, filename: result.filename, browserErrors };
619
+ } finally {
620
+ await browser?.close();
621
+ await server.close();
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Render a diagram source file (PlantUML / Mermaid / DOT / Vega / ...) to
627
+ * SVG, PNG or DrawIO XML through the shared renderer registry.
628
+ */
629
+ export async function exportMarkdownDiagram(options) {
630
+ const inputPath = path.resolve(options.input);
631
+ const diagramType = options.diagramType || inferDiagramType(inputPath);
632
+ if (!diagramType) {
633
+ throw new Error(`Cannot infer a diagram renderer from ${inputPath}; use --diagram-type`);
634
+ }
635
+ const format = options.format || 'svg';
636
+ const content = await fs.readFile(inputPath, 'utf8');
637
+
638
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
639
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
640
+ });
641
+
642
+ const server = await startAssetServer(path.dirname(inputPath));
643
+ let browser;
644
+ try {
645
+ browser = await chromium.launch({
646
+ headless: true,
647
+ ...(options.chromePath
648
+ ? { executablePath: path.resolve(options.chromePath) }
649
+ : { channel: 'chrome' }),
650
+ });
651
+
652
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
653
+ const browserErrors = [];
654
+ page.on('console', (message) => {
655
+ if (message.type() === 'error') browserErrors.push(message.text());
656
+ });
657
+ page.on('pageerror', (error) => browserErrors.push(error.message));
658
+
659
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
660
+ await page.waitForFunction(() => typeof window.markdownCli?.renderDiagram === 'function');
661
+
662
+ const result = await withTimeout(page.evaluate((request) => {
663
+ return window.markdownCli.renderDiagram(request);
664
+ }, {
665
+ diagramType,
666
+ content,
667
+ theme: options.theme || 'default',
668
+ documentBaseUrl: server.documentBaseUrl,
669
+ fileReadUrl: server.fileReadUrl,
670
+ resourceBaseUrl: server.resourceBaseUrl,
671
+ }), options.timeoutMs);
672
+
673
+ const ext = format === 'png' ? '.png' : format === 'drawio' ? '.drawio' : '.svg';
674
+ const outputPath = options.output
675
+ ? path.resolve(options.output)
676
+ : path.join(path.dirname(inputPath), path.basename(inputPath, path.extname(inputPath)) + ext);
677
+
678
+ await ensureOutputDirectory(outputPath);
679
+ if (format === 'png') {
680
+ if (!result.pngBase64) {
681
+ throw new Error(`Diagram type "${diagramType}" produced no PNG`);
682
+ }
683
+ await fs.writeFile(outputPath, Buffer.from(result.pngBase64, 'base64'));
684
+ } else if (format === 'drawio') {
685
+ if (!result.drawioXml) {
686
+ throw new Error(`Diagram type "${diagramType}" does not produce DrawIO XML (PlantUML only)`);
687
+ }
688
+ await fs.writeFile(outputPath, result.drawioXml, 'utf8');
689
+ } else {
690
+ if (!result.svg) {
691
+ if (result.pngBase64) {
692
+ throw new Error(`Diagram type "${diagramType}" produces PNG only; use --format png (or an output ending in .png)`);
693
+ }
694
+ throw new Error(`Diagram type "${diagramType}" produced no SVG`);
695
+ }
696
+ await fs.writeFile(outputPath, result.svg, 'utf8');
697
+ }
698
+ return { outputPath, browserErrors };
699
+ } finally {
700
+ await browser?.close();
701
+ await server.close();
702
+ }
703
+ }
704
+
705
+ /**
706
+ * Run the REAL DOCX export pipeline (DocxExporter on the raw markdown) and
707
+ * write the generated .docx to disk.
708
+ */
709
+ export async function exportMarkdownDocx(options) {
710
+ const inputPath = path.resolve(options.input);
711
+ const outputPath = outputPathFor(inputPath, options.output, 'docx');
712
+ const markdown = await fs.readFile(inputPath, 'utf8');
713
+
714
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
715
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
716
+ });
717
+
718
+ const server = await startAssetServer(path.dirname(inputPath));
719
+ let browser;
720
+ try {
721
+ browser = await chromium.launch({
722
+ headless: true,
723
+ ...(options.chromePath
724
+ ? { executablePath: path.resolve(options.chromePath) }
725
+ : { channel: 'chrome' }),
726
+ });
727
+
728
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
729
+ const browserErrors = [];
730
+ page.on('console', (message) => {
731
+ if (message.type() === 'error') browserErrors.push(message.text());
732
+ });
733
+ page.on('pageerror', (error) => browserErrors.push(error.message));
734
+
735
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
736
+ await page.waitForFunction(() => typeof window.markdownCli?.renderDocx === 'function');
737
+
738
+ const result = await withTimeout(page.evaluate((request) => {
739
+ return window.markdownCli.renderDocx(request);
740
+ }, {
741
+ markdown,
742
+ filename: path.basename(inputPath),
743
+ title: options.title,
744
+ theme: options.theme,
745
+ language: options.language,
746
+ frontmatterDisplay: options.frontmatterDisplay,
747
+ tableMergeEmpty: options.tableMergeEmpty,
748
+ tableLayout: options.tableLayout,
749
+ imageLayout: options.imageLayout,
750
+ diagramLayout: options.diagramLayout,
751
+ firstLineIndent: options.firstLineIndent ?? 0,
752
+ documentPath: inputPath,
753
+ documentDir: path.dirname(inputPath),
754
+ documentBaseUrl: server.documentBaseUrl,
755
+ fileReadUrl: server.fileReadUrl,
756
+ resourceBaseUrl: server.resourceBaseUrl,
757
+ }), options.timeoutMs);
758
+
759
+ await ensureOutputDirectory(outputPath);
760
+ await fs.writeFile(outputPath, base64ToBuffer(result.base64));
761
+ return { outputPath, browserErrors };
762
+ } finally {
763
+ await browser?.close();
764
+ await server.close();
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Whole-book export: parse the SUMMARY.md pages and run the real book
770
+ * pipeline (book-renderer + exportToEpub / exportBookToDocx).
771
+ */
772
+ export async function exportMarkdownBook(options) {
773
+ const inputPath = path.resolve(options.input);
774
+ const summaryDir = path.dirname(inputPath);
775
+ const summaryContent = await fs.readFile(inputPath, 'utf8');
776
+ const pages = parseSummaryPages(summaryContent, '');
777
+ if (pages.length === 0) {
778
+ throw new Error(`No book pages found in ${inputPath}`);
779
+ }
780
+ const bookTitle = options.title || path.basename(summaryDir) || 'Book';
781
+
782
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
783
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
784
+ });
785
+
786
+ const server = await startAssetServer(summaryDir);
787
+ let browser;
788
+ try {
789
+ browser = await chromium.launch({
790
+ headless: true,
791
+ ...(options.chromePath
792
+ ? { executablePath: path.resolve(options.chromePath) }
793
+ : { channel: 'chrome' }),
794
+ });
795
+
796
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
797
+ const browserErrors = [];
798
+ page.on('console', (message) => {
799
+ if (message.type() === 'error') browserErrors.push(message.text());
800
+ });
801
+ page.on('pageerror', (error) => browserErrors.push(error.message));
802
+
803
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
804
+ const apiName = options.format === 'epub' ? 'renderBookEpub' : 'renderBookDocx';
805
+ await page.waitForFunction((name) => typeof window.markdownCli?.[name] === 'function', apiName);
806
+
807
+ const result = await withTimeout(page.evaluate((request) => {
808
+ const api = request.format === 'epub' ? window.markdownCli.renderBookEpub : window.markdownCli.renderBookDocx;
809
+ return api(request);
810
+ }, {
811
+ markdown: '',
812
+ filename: `${bookTitle}${options.format === 'epub' ? '.epub' : '.docx'}`,
813
+ title: bookTitle,
814
+ bookTitle,
815
+ format: options.format,
816
+ pages,
817
+ theme: options.theme,
818
+ language: options.language,
819
+ frontmatterDisplay: options.frontmatterDisplay,
820
+ tableMergeEmpty: options.tableMergeEmpty,
821
+ tableLayout: options.tableLayout,
822
+ imageLayout: options.imageLayout,
823
+ diagramLayout: options.diagramLayout,
824
+ firstLineIndent: 0,
825
+ documentPath: inputPath,
826
+ documentDir: summaryDir,
827
+ documentBaseUrl: server.documentBaseUrl,
828
+ fileReadUrl: server.fileReadUrl,
829
+ resourceBaseUrl: server.resourceBaseUrl,
830
+ }), options.timeoutMs);
831
+
832
+ const ext = options.format === 'epub' ? '.epub' : '.docx';
833
+ const outputPath = options.output
834
+ ? path.resolve(options.output)
835
+ : path.join(summaryDir, `${bookTitle}${ext}`);
836
+ await ensureOutputDirectory(outputPath);
837
+ await fs.writeFile(outputPath, base64ToBuffer(result.base64));
838
+ return { outputPath, browserErrors };
839
+ } finally {
840
+ await browser?.close();
841
+ await server.close();
842
+ }
843
+ }
844
+
845
+ function pdfOptions() {
846
+ return {
847
+ printBackground: true,
848
+ preferCSSPageSize: true,
849
+ };
850
+ }
851
+
852
+ function doneMessage(action, outputPath) {
853
+ return `${action} ${outputPath} — documd v${CLI_VERSION} · ${CLI_HOMEPAGE}`;
854
+ }
855
+
856
+ /**
857
+ * Export a single markdown file to PDF through the headless Chrome print
858
+ * pipeline (shared print styles from print-utils).
859
+ */
860
+ export async function exportMarkdownPdf(options) {
861
+ const inputPath = path.resolve(options.input);
862
+ const outputPath = outputPathFor(inputPath, options.output, 'pdf');
863
+ const markdown = await fs.readFile(inputPath, 'utf8');
864
+
865
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
866
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
867
+ });
868
+
869
+ const server = await startAssetServer(path.dirname(inputPath));
870
+ let browser;
871
+ try {
872
+ browser = await chromium.launch({
873
+ headless: true,
874
+ ...(options.chromePath
875
+ ? { executablePath: path.resolve(options.chromePath) }
876
+ : { channel: 'chrome' }),
877
+ });
878
+
879
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
880
+ const browserErrors = [];
881
+ page.on('console', (message) => {
882
+ if (message.type() === 'error') browserErrors.push(message.text());
883
+ });
884
+ page.on('pageerror', (error) => browserErrors.push(error.message));
885
+
886
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
887
+ await page.waitForFunction(() => typeof window.markdownCli?.renderPdf === 'function');
888
+
889
+ await withTimeout(page.evaluate((request) => {
890
+ return window.markdownCli.renderPdf(request);
891
+ }, {
892
+ markdown,
893
+ filename: path.basename(inputPath),
894
+ title: options.title,
895
+ theme: options.theme,
896
+ language: options.language,
897
+ frontmatterDisplay: options.frontmatterDisplay,
898
+ tableMergeEmpty: options.tableMergeEmpty,
899
+ tableLayout: options.tableLayout,
900
+ imageLayout: options.imageLayout,
901
+ diagramLayout: options.diagramLayout,
902
+ firstLineIndent: options.firstLineIndent ?? 0,
903
+ documentPath: inputPath,
904
+ documentDir: path.dirname(inputPath),
905
+ documentBaseUrl: server.documentBaseUrl,
906
+ fileReadUrl: server.fileReadUrl,
907
+ resourceBaseUrl: server.resourceBaseUrl,
908
+ }), options.timeoutMs);
909
+
910
+ const pdf = await withTimeout(page.pdf(pdfOptions()), options.timeoutMs);
911
+ await ensureOutputDirectory(outputPath);
912
+ await fs.writeFile(outputPath, pdf);
913
+ return { outputPath, browserErrors };
914
+ } finally {
915
+ await browser?.close();
916
+ await server.close();
917
+ }
918
+ }
919
+
920
+ /**
921
+ * Whole-book PDF export: parse the SUMMARY.md pages, render the book into
922
+ * #book-print-root and print it through headless Chrome.
923
+ */
924
+ export async function exportMarkdownBookPdf(options) {
925
+ const inputPath = path.resolve(options.input);
926
+ const summaryDir = path.dirname(inputPath);
927
+ const summaryContent = await fs.readFile(inputPath, 'utf8');
928
+ const pages = parseSummaryPages(summaryContent, '');
929
+ if (pages.length === 0) {
930
+ throw new Error(`No book pages found in ${inputPath}`);
931
+ }
932
+ const bookTitle = options.title || path.basename(summaryDir) || 'Book';
933
+
934
+ await fs.access(path.join(cliAssetDir, 'browser-renderer.js')).catch(() => {
935
+ throw new Error('CLI browser assets are missing. Run "npm run build:cli" first.');
936
+ });
937
+
938
+ const server = await startAssetServer(summaryDir);
939
+ let browser;
940
+ try {
941
+ browser = await chromium.launch({
942
+ headless: true,
943
+ ...(options.chromePath
944
+ ? { executablePath: path.resolve(options.chromePath) }
945
+ : { channel: 'chrome' }),
946
+ });
947
+
948
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
949
+ const browserErrors = [];
950
+ page.on('console', (message) => {
951
+ if (message.type() === 'error') browserErrors.push(message.text());
952
+ });
953
+ page.on('pageerror', (error) => browserErrors.push(error.message));
954
+
955
+ await page.goto(server.pageUrl, { waitUntil: 'load' });
956
+ await page.waitForFunction(() => typeof window.markdownCli?.renderBookPdf === 'function');
957
+
958
+ await withTimeout(page.evaluate((request) => {
959
+ return window.markdownCli.renderBookPdf(request);
960
+ }, {
961
+ markdown: '',
962
+ filename: `${bookTitle}.pdf`,
963
+ title: bookTitle,
964
+ pages,
965
+ theme: options.theme,
966
+ language: options.language,
967
+ frontmatterDisplay: options.frontmatterDisplay,
968
+ tableMergeEmpty: options.tableMergeEmpty,
969
+ tableLayout: options.tableLayout,
970
+ imageLayout: options.imageLayout,
971
+ diagramLayout: options.diagramLayout,
972
+ firstLineIndent: 0,
973
+ documentPath: inputPath,
974
+ documentDir: summaryDir,
975
+ documentBaseUrl: server.documentBaseUrl,
976
+ fileReadUrl: server.fileReadUrl,
977
+ resourceBaseUrl: server.resourceBaseUrl,
978
+ }), options.timeoutMs);
979
+
980
+ const pdf = await withTimeout(page.pdf(pdfOptions()), options.timeoutMs);
981
+ const outputPath = options.output
982
+ ? path.resolve(options.output)
983
+ : path.join(summaryDir, `${bookTitle}.pdf`);
984
+ await ensureOutputDirectory(outputPath);
985
+ await fs.writeFile(outputPath, pdf);
986
+ return { outputPath, browserErrors };
987
+ } finally {
988
+ await browser?.close();
989
+ await server.close();
990
+ }
991
+ }
992
+
993
+ async function main() {
994
+ try {
995
+ const options = parseArgs(process.argv.slice(2));
996
+ if (options.version) {
997
+ process.stdout.write(`documd v${CLI_VERSION} — ${CLI_HOMEPAGE}\n`);
998
+ return;
999
+ }
1000
+ if (options.help) {
1001
+ process.stdout.write(HELP);
1002
+ return;
1003
+ }
1004
+ if (options.bookMode) {
1005
+ if (options.format === 'pdf') {
1006
+ const result = await exportMarkdownBookPdf(options);
1007
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1008
+ console.log(doneMessage("Exported", result.outputPath));
1009
+ return;
1010
+ }
1011
+ const result = await exportMarkdownBook(options);
1012
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1013
+ console.log(doneMessage("Exported", result.outputPath));
1014
+ return;
1015
+ }
1016
+ if (options.format === 'pdf') {
1017
+ const result = await exportMarkdownPdf(options);
1018
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1019
+ console.log(doneMessage("Exported", result.outputPath));
1020
+ return;
1021
+ }
1022
+ if (options.diagramMode) {
1023
+ const result = await exportMarkdownDiagram(options);
1024
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1025
+ console.log(doneMessage("Exported", result.outputPath));
1026
+ return;
1027
+ }
1028
+ if (options.format === 'docx') {
1029
+ const result = await exportMarkdownDocx(options);
1030
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1031
+ console.log(doneMessage("Exported", result.outputPath));
1032
+ return;
1033
+ }
1034
+ if (options.format === 'epub') {
1035
+ const result = await exportMarkdownEpub(options);
1036
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1037
+ console.log(doneMessage("Exported", result.outputPath));
1038
+ return;
1039
+ }
1040
+ const result = await renderMarkdownFile(options);
1041
+ for (const warning of result.browserErrors) console.warn(`[browser] ${warning}`);
1042
+ console.log(doneMessage("Rendered", result.outputPath));
1043
+ } catch (error) {
1044
+ console.error(`documd: ${error instanceof Error ? error.message : String(error)}`);
1045
+ process.exitCode = 1;
1046
+ }
1047
+ }
1048
+
1049
+ const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : '';
1050
+ if (invokedPath === fileURLToPath(import.meta.url)) await main();