@masumdev/markforge 0.2.2 → 0.2.3

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.
@@ -0,0 +1,2437 @@
1
+ #!/usr/bin/env node
2
+ try {
3
+ if (typeof globalThis !== "undefined" && (!globalThis.localStorage || typeof globalThis.localStorage.getItem !== "function")) {
4
+ Object.defineProperty(globalThis, "localStorage", {
5
+ value: { getItem: () => null, setItem: () => {}, removeItem: () => {}, clear: () => {}, key: () => null, length: 0 },
6
+ configurable: true, writable: true,
7
+ });
8
+ }
9
+ } catch {}
10
+ import {
11
+ MARKFORGE_VERSION
12
+ } from "./chunk-NGC2ZAWZ.mjs";
13
+ import {
14
+ DEFAULT_CONFIG
15
+ } from "./chunk-ASXSHC6H.mjs";
16
+ import "./chunk-YZHGBG4N.mjs";
17
+
18
+ // src/ui/App.tsx
19
+ import { useState, useEffect } from "react";
20
+ import { Box as Box4 } from "ink";
21
+
22
+ // src/ui/Header.tsx
23
+ import { Box, Text } from "ink";
24
+ import { jsx, jsxs } from "react/jsx-runtime";
25
+ var Header = ({ inputFile, theme = "default" }) => {
26
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginY: 1, children: /* @__PURE__ */ jsxs(
27
+ Box,
28
+ {
29
+ borderStyle: "round",
30
+ borderColor: "cyan",
31
+ paddingX: 2,
32
+ paddingY: 0,
33
+ flexDirection: "column",
34
+ children: [
35
+ /* @__PURE__ */ jsxs(Box, { justifyContent: "space-between", children: [
36
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "MARKFORGE DOCUMENT ENGINE" }),
37
+ /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
38
+ "v",
39
+ MARKFORGE_VERSION
40
+ ] })
41
+ ] }),
42
+ inputFile && /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
43
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Source: " }),
44
+ /* @__PURE__ */ jsx(Text, { color: "white", bold: true, children: inputFile })
45
+ ] }),
46
+ /* @__PURE__ */ jsxs(Box, { children: [
47
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Theme: " }),
48
+ /* @__PURE__ */ jsx(Text, { color: "blue", children: theme })
49
+ ] })
50
+ ]
51
+ }
52
+ ) });
53
+ };
54
+
55
+ // src/ui/LiveProgress.tsx
56
+ import { Box as Box2, Text as Text2 } from "ink";
57
+ import Spinner from "ink-spinner";
58
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
59
+ var LiveProgress = ({ status, isCompiling }) => {
60
+ if (!isCompiling) return null;
61
+ return /* @__PURE__ */ jsxs2(Box2, { marginY: 1, alignItems: "center", children: [
62
+ /* @__PURE__ */ jsx2(Text2, { color: "cyan", children: /* @__PURE__ */ jsx2(Spinner, { type: "dots" }) }),
63
+ /* @__PURE__ */ jsxs2(Box2, { marginLeft: 1, children: [
64
+ /* @__PURE__ */ jsx2(Text2, { color: "yellow", children: "[COMPILING] " }),
65
+ /* @__PURE__ */ jsx2(Text2, { color: "white", children: status })
66
+ ] })
67
+ ] });
68
+ };
69
+
70
+ // src/ui/SummaryTable.tsx
71
+ import { Box as Box3, Text as Text3 } from "ink";
72
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
73
+ function formatBytes(bytes) {
74
+ if (bytes === 0) return "0 B";
75
+ const k = 1024;
76
+ const sizes = ["B", "KB", "MB", "GB"];
77
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
78
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
79
+ }
80
+ var SummaryTable = ({ result }) => {
81
+ if (!result) return null;
82
+ const hasErrors = result.errors.length > 0;
83
+ return /* @__PURE__ */ jsx3(Box3, { flexDirection: "column", marginY: 1, children: /* @__PURE__ */ jsxs3(
84
+ Box3,
85
+ {
86
+ borderStyle: "round",
87
+ borderColor: hasErrors ? "red" : "green",
88
+ paddingX: 2,
89
+ paddingY: 1,
90
+ flexDirection: "column",
91
+ children: [
92
+ /* @__PURE__ */ jsxs3(Box3, { justifyContent: "space-between", children: [
93
+ /* @__PURE__ */ jsx3(Text3, { bold: true, color: hasErrors ? "red" : "green", children: hasErrors ? "[COMPILATION ERRORS]" : "[COMPILATION SUCCESSFUL]" }),
94
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
95
+ result.durationMs,
96
+ "ms"
97
+ ] })
98
+ ] }),
99
+ /* @__PURE__ */ jsxs3(Box3, { marginTop: 1, flexDirection: "column", children: [
100
+ /* @__PURE__ */ jsxs3(Text3, { bold: true, color: "white", children: [
101
+ "Output Documents (",
102
+ result.files.length,
103
+ "):"
104
+ ] }),
105
+ result.files.map((f, i) => /* @__PURE__ */ jsxs3(Box3, { marginLeft: 2, justifyContent: "space-between", children: [
106
+ /* @__PURE__ */ jsxs3(Box3, { children: [
107
+ /* @__PURE__ */ jsxs3(Text3, { color: "cyan", children: [
108
+ "[",
109
+ f.format.toUpperCase(),
110
+ "] "
111
+ ] }),
112
+ /* @__PURE__ */ jsx3(Text3, { color: "gray", children: f.filePath })
113
+ ] }),
114
+ /* @__PURE__ */ jsxs3(Text3, { color: "yellow", children: [
115
+ " ",
116
+ formatBytes(f.sizeBytes)
117
+ ] })
118
+ ] }, i))
119
+ ] }),
120
+ hasErrors && /* @__PURE__ */ jsxs3(Box3, { marginTop: 1, flexDirection: "column", children: [
121
+ /* @__PURE__ */ jsx3(Text3, { bold: true, color: "red", children: "Errors:" }),
122
+ result.errors.map((err, i) => /* @__PURE__ */ jsx3(Box3, { marginLeft: 2, children: /* @__PURE__ */ jsxs3(Text3, { color: "red", children: [
123
+ "- ",
124
+ err
125
+ ] }) }, i))
126
+ ] })
127
+ ]
128
+ }
129
+ ) });
130
+ };
131
+
132
+ // src/core/engine.ts
133
+ import * as fs5 from "fs";
134
+ import * as path5 from "path";
135
+
136
+ // src/core/parser.ts
137
+ import matter from "gray-matter";
138
+ function parseInlineSpans(text) {
139
+ const spans = [];
140
+ let remaining = text;
141
+ while (remaining.length > 0) {
142
+ const imgMatch = remaining.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)(?:\{([^}]+)\})?/);
143
+ if (imgMatch) {
144
+ const alt = imgMatch[1];
145
+ const url = imgMatch[2];
146
+ const title = imgMatch[3];
147
+ const attrStr = imgMatch[4] || "";
148
+ let width;
149
+ let height;
150
+ if (attrStr) {
151
+ const wMatch = attrStr.match(/width=([^\s}]+)/i);
152
+ const hMatch = attrStr.match(/height=([^\s}]+)/i);
153
+ if (wMatch) width = wMatch[1];
154
+ if (hMatch) height = hMatch[1];
155
+ }
156
+ spans.push({
157
+ type: "image",
158
+ content: alt,
159
+ url,
160
+ alt,
161
+ title,
162
+ width,
163
+ height
164
+ });
165
+ remaining = remaining.slice(imgMatch[0].length);
166
+ continue;
167
+ }
168
+ const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/);
169
+ if (linkMatch) {
170
+ spans.push({
171
+ type: "link",
172
+ content: linkMatch[1],
173
+ url: linkMatch[2],
174
+ title: linkMatch[3],
175
+ children: parseInlineSpans(linkMatch[1])
176
+ });
177
+ remaining = remaining.slice(linkMatch[0].length);
178
+ continue;
179
+ }
180
+ const boldItalicMatch = remaining.match(/^(\*\*\*|___)(.+?)\1/);
181
+ if (boldItalicMatch) {
182
+ spans.push({
183
+ type: "bold",
184
+ content: boldItalicMatch[2],
185
+ children: [
186
+ {
187
+ type: "italic",
188
+ content: boldItalicMatch[2],
189
+ children: parseInlineSpans(boldItalicMatch[2])
190
+ }
191
+ ]
192
+ });
193
+ remaining = remaining.slice(boldItalicMatch[0].length);
194
+ continue;
195
+ }
196
+ const boldMatch = remaining.match(/^(\*\*|__)(.+?)\1/);
197
+ if (boldMatch) {
198
+ spans.push({
199
+ type: "bold",
200
+ content: boldMatch[2],
201
+ children: parseInlineSpans(boldMatch[2])
202
+ });
203
+ remaining = remaining.slice(boldMatch[0].length);
204
+ continue;
205
+ }
206
+ const italicMatch = remaining.match(/^(\*|_)([^*_]+?)\1/);
207
+ if (italicMatch) {
208
+ spans.push({
209
+ type: "italic",
210
+ content: italicMatch[2],
211
+ children: parseInlineSpans(italicMatch[2])
212
+ });
213
+ remaining = remaining.slice(italicMatch[0].length);
214
+ continue;
215
+ }
216
+ const strikeMatch = remaining.match(/^~~(.+?)~~/);
217
+ if (strikeMatch) {
218
+ spans.push({
219
+ type: "strikethrough",
220
+ content: strikeMatch[1],
221
+ children: parseInlineSpans(strikeMatch[1])
222
+ });
223
+ remaining = remaining.slice(strikeMatch[0].length);
224
+ continue;
225
+ }
226
+ const codeMatch = remaining.match(/^`([^`]+)`/);
227
+ if (codeMatch) {
228
+ spans.push({
229
+ type: "code",
230
+ content: codeMatch[1]
231
+ });
232
+ remaining = remaining.slice(codeMatch[0].length);
233
+ continue;
234
+ }
235
+ const htmlTagMatch = remaining.match(/^<(\w+)([^>]*)>(.*?)<\/\1>/i) || remaining.match(/^<(\w+)([^>]*)\/?>/i);
236
+ if (htmlTagMatch) {
237
+ const fullTag = htmlTagMatch[0];
238
+ const tag = htmlTagMatch[1].toLowerCase();
239
+ const attrs = htmlTagMatch[2] || "";
240
+ const innerText = htmlTagMatch[3] || "";
241
+ if (tag === "img") {
242
+ const srcMatch = attrs.match(/src=["']([^"']+)["']/i);
243
+ const altMatch = attrs.match(/alt=["']([^"']+)["']/i);
244
+ const widthMatch = attrs.match(/width=["']?(\d+%?|\d+px)?["']?/i);
245
+ const heightMatch = attrs.match(/height=["']?(\d+%?|\d+px)?["']?/i);
246
+ if (srcMatch) {
247
+ spans.push({
248
+ type: "image",
249
+ content: altMatch ? altMatch[1] : "",
250
+ url: srcMatch[1],
251
+ alt: altMatch ? altMatch[1] : "",
252
+ width: widthMatch ? widthMatch[1] : void 0,
253
+ height: heightMatch ? heightMatch[1] : void 0
254
+ });
255
+ remaining = remaining.slice(fullTag.length);
256
+ continue;
257
+ }
258
+ }
259
+ spans.push({
260
+ type: "htmlInline",
261
+ content: innerText || fullTag,
262
+ children: innerText ? parseInlineSpans(innerText) : void 0
263
+ });
264
+ remaining = remaining.slice(fullTag.length);
265
+ continue;
266
+ }
267
+ const nextSpecial = remaining.search(/[\*\_\[\!`~<]/);
268
+ if (nextSpecial === -1) {
269
+ spans.push({
270
+ type: "text",
271
+ content: remaining
272
+ });
273
+ break;
274
+ } else if (nextSpecial === 0) {
275
+ spans.push({
276
+ type: "text",
277
+ content: remaining[0]
278
+ });
279
+ remaining = remaining.slice(1);
280
+ } else {
281
+ spans.push({
282
+ type: "text",
283
+ content: remaining.slice(0, nextSpecial)
284
+ });
285
+ remaining = remaining.slice(nextSpecial);
286
+ }
287
+ }
288
+ return spans;
289
+ }
290
+ function slugify(text) {
291
+ return text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
292
+ }
293
+ function parseMarkdownDocument(rawMarkdown) {
294
+ const { data: frontmatter, content } = matter(rawMarkdown);
295
+ const metadata = frontmatter || {};
296
+ const inlinedStyles = [];
297
+ const cleanContent = content.replace(/<style[^>]*>([\s\S]*?)<\/style>/gi, (_, css) => {
298
+ inlinedStyles.push(css.trim());
299
+ return "";
300
+ });
301
+ const lines = cleanContent.split(/\r?\n/);
302
+ const nodes = [];
303
+ const tocEntries = [];
304
+ let i = 0;
305
+ while (i < lines.length) {
306
+ const line = lines[i];
307
+ if (!line.trim()) {
308
+ i++;
309
+ continue;
310
+ }
311
+ const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
312
+ if (headingMatch) {
313
+ const level = headingMatch[1].length;
314
+ const text = headingMatch[2].trim();
315
+ const id = slugify(text);
316
+ nodes.push({
317
+ type: "heading",
318
+ level,
319
+ id,
320
+ text,
321
+ inlines: parseInlineSpans(text)
322
+ });
323
+ tocEntries.push({ id, text, level });
324
+ i++;
325
+ continue;
326
+ }
327
+ if (/^(\*{3,}|-{3,}|_{3,})\s*$/.test(line)) {
328
+ nodes.push({ type: "thematicBreak" });
329
+ i++;
330
+ continue;
331
+ }
332
+ const codeBlockMatch = line.match(/^```(\w+)?/);
333
+ if (codeBlockMatch) {
334
+ const language = (codeBlockMatch[1] || "text").trim().toLowerCase();
335
+ const codeLines = [];
336
+ i++;
337
+ while (i < lines.length && !lines[i].startsWith("```")) {
338
+ codeLines.push(lines[i]);
339
+ i++;
340
+ }
341
+ if (i < lines.length) i++;
342
+ const codeText = codeLines.join("\n");
343
+ if (language === "mermaid") {
344
+ nodes.push({
345
+ type: "mermaid",
346
+ language: "mermaid",
347
+ text: codeText
348
+ });
349
+ } else {
350
+ nodes.push({
351
+ type: "codeBlock",
352
+ language,
353
+ text: codeText
354
+ });
355
+ }
356
+ continue;
357
+ }
358
+ const calloutMatch = line.match(/^>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i);
359
+ if (calloutMatch) {
360
+ const calloutType = calloutMatch[1].toUpperCase();
361
+ const blockLines = [];
362
+ i++;
363
+ while (i < lines.length && lines[i].startsWith(">")) {
364
+ blockLines.push(lines[i].replace(/^>\s?/, ""));
365
+ i++;
366
+ }
367
+ const blockText = blockLines.join("\n");
368
+ nodes.push({
369
+ type: "callout",
370
+ calloutType,
371
+ text: blockText,
372
+ inlines: parseInlineSpans(blockText)
373
+ });
374
+ continue;
375
+ }
376
+ if (line.startsWith(">")) {
377
+ const quoteLines = [];
378
+ while (i < lines.length && lines[i].startsWith(">")) {
379
+ quoteLines.push(lines[i].replace(/^>\s?/, ""));
380
+ i++;
381
+ }
382
+ const quoteText = quoteLines.join("\n");
383
+ nodes.push({
384
+ type: "blockquote",
385
+ text: quoteText,
386
+ inlines: parseInlineSpans(quoteText)
387
+ });
388
+ continue;
389
+ }
390
+ if (line.trim().startsWith("|") && line.includes("|")) {
391
+ const tableLines = [];
392
+ while (i < lines.length && lines[i].trim().startsWith("|")) {
393
+ tableLines.push(lines[i].trim());
394
+ i++;
395
+ }
396
+ if (tableLines.length >= 2) {
397
+ const headerRow = tableLines[0].split("|").slice(1, -1).map((c) => c.trim());
398
+ const alignRow = tableLines[1].split("|").slice(1, -1).map((c) => c.trim());
399
+ const align = alignRow.map((col) => {
400
+ if (col.startsWith(":") && col.endsWith(":")) return "center";
401
+ if (col.endsWith(":")) return "right";
402
+ if (col.startsWith(":")) return "left";
403
+ return null;
404
+ });
405
+ const rows = [];
406
+ rows.push({
407
+ type: "tableRow",
408
+ isHeader: true,
409
+ children: headerRow.map((cellText) => ({
410
+ type: "tableCell",
411
+ isHeader: true,
412
+ text: cellText,
413
+ inlines: parseInlineSpans(cellText)
414
+ }))
415
+ });
416
+ for (let r = 2; r < tableLines.length; r++) {
417
+ const cells = tableLines[r].split("|").slice(1, -1).map((c) => c.trim());
418
+ rows.push({
419
+ type: "tableRow",
420
+ isHeader: false,
421
+ children: cells.map((cellText) => ({
422
+ type: "tableCell",
423
+ isHeader: false,
424
+ text: cellText,
425
+ inlines: parseInlineSpans(cellText)
426
+ }))
427
+ });
428
+ }
429
+ nodes.push({
430
+ type: "table",
431
+ align,
432
+ children: rows
433
+ });
434
+ continue;
435
+ }
436
+ }
437
+ const listMatch = line.match(/^(\s*)([-*+]|\d+\.)\s+(.+)$/);
438
+ if (listMatch) {
439
+ const listItems = [];
440
+ const isOrdered = /^\d+\./.test(listMatch[2]);
441
+ while (i < lines.length) {
442
+ const itemMatch = lines[i].match(/^(\s*)([-*+]|\d+\.)\s+(.+)$/);
443
+ if (!itemMatch) break;
444
+ let itemText = itemMatch[3].trim();
445
+ let checked = void 0;
446
+ const taskMatch = itemText.match(/^\[([ xX])\]\s+(.*)$/);
447
+ if (taskMatch) {
448
+ checked = taskMatch[1].toLowerCase() === "x";
449
+ itemText = taskMatch[2];
450
+ }
451
+ listItems.push({
452
+ type: "listItem",
453
+ checked,
454
+ text: itemText,
455
+ inlines: parseInlineSpans(itemText)
456
+ });
457
+ i++;
458
+ }
459
+ nodes.push({
460
+ type: "list",
461
+ ordered: isOrdered,
462
+ children: listItems
463
+ });
464
+ continue;
465
+ }
466
+ if (line.trim().startsWith("<") && !line.trim().startsWith("<!--")) {
467
+ const htmlLines = [];
468
+ while (i < lines.length && lines[i].trim().length > 0) {
469
+ htmlLines.push(lines[i]);
470
+ i++;
471
+ }
472
+ const rawHtml = htmlLines.join("\n");
473
+ nodes.push({
474
+ type: "htmlBlock",
475
+ rawHtml,
476
+ text: rawHtml
477
+ });
478
+ continue;
479
+ }
480
+ const paraLines = [];
481
+ while (i < lines.length && lines[i].trim() && !lines[i].match(/^#{1,6}\s+/) && !lines[i].startsWith("```") && !lines[i].startsWith(">") && !lines[i].trim().startsWith("|") && !lines[i].match(/^(\s*)([-*+]|\d+\.)\s+/)) {
482
+ paraLines.push(lines[i]);
483
+ i++;
484
+ }
485
+ const paraText = paraLines.join(" ");
486
+ nodes.push({
487
+ type: "paragraph",
488
+ text: paraText,
489
+ inlines: parseInlineSpans(paraText)
490
+ });
491
+ }
492
+ return {
493
+ metadata,
494
+ content: cleanContent,
495
+ nodes,
496
+ tocEntries,
497
+ inlinedStyles
498
+ };
499
+ }
500
+
501
+ // src/core/docx/docxBuilder.ts
502
+ import {
503
+ Document,
504
+ Paragraph,
505
+ TextRun,
506
+ HeadingLevel,
507
+ Table,
508
+ TableRow,
509
+ TableCell,
510
+ WidthType,
511
+ BorderStyle,
512
+ AlignmentType,
513
+ ImageRun,
514
+ Header as Header2,
515
+ Footer,
516
+ PageNumber,
517
+ Packer,
518
+ PageOrientation,
519
+ convertInchesToTwip,
520
+ convertMillimetersToTwip,
521
+ ShadingType,
522
+ ExternalHyperlink,
523
+ TabStopType
524
+ } from "docx";
525
+
526
+ // src/core/imageResolver.ts
527
+ import * as fs from "fs";
528
+ import * as path from "path";
529
+ var memoryImageCache = /* @__PURE__ */ new Map();
530
+ function getMimeType(filePathOrUrl) {
531
+ const clean = filePathOrUrl.split("?")[0].toLowerCase();
532
+ if (clean.endsWith(".png")) return "image/png";
533
+ if (clean.endsWith(".jpg") || clean.endsWith(".jpeg")) return "image/jpeg";
534
+ if (clean.endsWith(".gif")) return "image/gif";
535
+ if (clean.endsWith(".svg")) return "image/svg+xml";
536
+ if (clean.endsWith(".webp")) return "image/webp";
537
+ if (clean.endsWith(".bmp")) return "image/bmp";
538
+ return "image/png";
539
+ }
540
+ async function resolveImage(src, baseDir = process.cwd()) {
541
+ const cacheKey = `${baseDir}::${src}`;
542
+ if (memoryImageCache.has(cacheKey)) {
543
+ return memoryImageCache.get(cacheKey);
544
+ }
545
+ try {
546
+ if (src.startsWith("data:")) {
547
+ const parts = src.split(",");
548
+ const meta = parts[0];
549
+ const base64Data = parts[1];
550
+ const mimeMatch = meta.match(/data:([^;]+)/);
551
+ const mimeType2 = mimeMatch ? mimeMatch[1] : "image/png";
552
+ const buffer2 = Buffer.from(base64Data, "base64");
553
+ const isSvg2 = mimeType2 === "image/svg+xml";
554
+ const resolved2 = {
555
+ src,
556
+ buffer: buffer2,
557
+ mimeType: mimeType2,
558
+ dataUri: src,
559
+ isSvg: isSvg2
560
+ };
561
+ memoryImageCache.set(cacheKey, resolved2);
562
+ return resolved2;
563
+ }
564
+ if (src.startsWith("http://") || src.startsWith("https://")) {
565
+ const response = await fetch(src, { signal: AbortSignal.timeout(1e4) });
566
+ if (!response.ok) {
567
+ return null;
568
+ }
569
+ const arrayBuffer = await response.arrayBuffer();
570
+ const buffer2 = Buffer.from(arrayBuffer);
571
+ const contentType = response.headers.get("content-type") || getMimeType(src);
572
+ const mimeType2 = contentType.split(";")[0].trim();
573
+ const dataUri2 = `data:${mimeType2};base64,${buffer2.toString("base64")}`;
574
+ const isSvg2 = mimeType2 === "image/svg+xml";
575
+ const resolved2 = {
576
+ src,
577
+ buffer: buffer2,
578
+ mimeType: mimeType2,
579
+ dataUri: dataUri2,
580
+ isSvg: isSvg2
581
+ };
582
+ memoryImageCache.set(cacheKey, resolved2);
583
+ return resolved2;
584
+ }
585
+ const localPath = path.isAbsolute(src) ? src : path.resolve(baseDir, src);
586
+ if (!fs.existsSync(localPath)) {
587
+ return null;
588
+ }
589
+ const buffer = fs.readFileSync(localPath);
590
+ const mimeType = getMimeType(localPath);
591
+ const dataUri = `data:${mimeType};base64,${buffer.toString("base64")}`;
592
+ const isSvg = mimeType === "image/svg+xml";
593
+ const resolved = {
594
+ src,
595
+ buffer,
596
+ mimeType,
597
+ dataUri,
598
+ isSvg
599
+ };
600
+ memoryImageCache.set(cacheKey, resolved);
601
+ return resolved;
602
+ } catch {
603
+ return null;
604
+ }
605
+ }
606
+
607
+ // src/core/syntax/syntaxHighlighter.ts
608
+ var SYNTAX_COLORS = {
609
+ keyword: "FF7B72",
610
+ // Bright coral-red — keywords (import, def, return...)
611
+ string: "E07C4F",
612
+ // Warm orange — strings (visible on dark bg)
613
+ comment: "8B949E",
614
+ // Muted gray — comments (italic)
615
+ number: "79C0FF",
616
+ // Sky blue — numbers
617
+ boolean: "FF9580",
618
+ // Salmon — true / false / None
619
+ function: "D2A8FF",
620
+ // Soft purple — function names
621
+ type: "7EE787",
622
+ // Bright green — Types / Classes
623
+ operator: "FF7B72",
624
+ // Same as keyword — = + - * / > <
625
+ punctuation: "8B9AC0",
626
+ // Steel blue-gray — () [] {} , . ;
627
+ plain: "E2E8F0"
628
+ // Light gray — identifiers / plain text
629
+ };
630
+ var SYNTAX_COLORS_LIGHT = {
631
+ keyword: "D73A49",
632
+ // Crimson red — keywords
633
+ string: "0A7E5C",
634
+ // Forest teal — strings (readable on white)
635
+ comment: "6A737D",
636
+ // Muted gray — comments
637
+ number: "005CC5",
638
+ // Cobalt blue — numbers
639
+ boolean: "D73A49",
640
+ // Crimson — true/false/None
641
+ function: "6F42C1",
642
+ // Purple — function names
643
+ type: "22863A",
644
+ // Forest green — Types / Classes
645
+ operator: "D73A49",
646
+ // Crimson — operators
647
+ punctuation: "586069",
648
+ // Dark gray — punctuation
649
+ plain: "24292E"
650
+ // Near-black — identifiers
651
+ };
652
+ var JS_KEYWORDS = /* @__PURE__ */ new Set([
653
+ "import",
654
+ "from",
655
+ "export",
656
+ "default",
657
+ "const",
658
+ "let",
659
+ "var",
660
+ "function",
661
+ "async",
662
+ "await",
663
+ "return",
664
+ "if",
665
+ "else",
666
+ "for",
667
+ "while",
668
+ "switch",
669
+ "case",
670
+ "break",
671
+ "continue",
672
+ "new",
673
+ "this",
674
+ "typeof",
675
+ "instanceof",
676
+ "class",
677
+ "extends",
678
+ "implements",
679
+ "interface",
680
+ "type",
681
+ "enum",
682
+ "as",
683
+ "try",
684
+ "catch",
685
+ "finally",
686
+ "throw",
687
+ "void",
688
+ "yield",
689
+ "static",
690
+ "readonly",
691
+ "private",
692
+ "public",
693
+ "protected"
694
+ ]);
695
+ var PYTHON_KEYWORDS = /* @__PURE__ */ new Set([
696
+ "def",
697
+ "class",
698
+ "import",
699
+ "from",
700
+ "as",
701
+ "return",
702
+ "if",
703
+ "elif",
704
+ "else",
705
+ "for",
706
+ "while",
707
+ "in",
708
+ "is",
709
+ "not",
710
+ "and",
711
+ "or",
712
+ "try",
713
+ "except",
714
+ "finally",
715
+ "raise",
716
+ "with",
717
+ "yield",
718
+ "lambda",
719
+ "global",
720
+ "nonlocal",
721
+ "pass",
722
+ "break",
723
+ "continue"
724
+ ]);
725
+ var BASH_KEYWORDS = /* @__PURE__ */ new Set([
726
+ "echo",
727
+ "cd",
728
+ "ls",
729
+ "mkdir",
730
+ "rm",
731
+ "cp",
732
+ "mv",
733
+ "cat",
734
+ "grep",
735
+ "find",
736
+ "curl",
737
+ "wget",
738
+ "npm",
739
+ "bun",
740
+ "pnpm",
741
+ "yarn",
742
+ "git",
743
+ "export",
744
+ "source",
745
+ "if",
746
+ "then",
747
+ "else",
748
+ "elif",
749
+ "fi",
750
+ "for",
751
+ "do",
752
+ "done",
753
+ "case",
754
+ "esac",
755
+ "sudo",
756
+ "chmod",
757
+ "chown",
758
+ "exit"
759
+ ]);
760
+ var SQL_KEYWORDS = /* @__PURE__ */ new Set([
761
+ "select",
762
+ "from",
763
+ "where",
764
+ "insert",
765
+ "into",
766
+ "values",
767
+ "update",
768
+ "set",
769
+ "delete",
770
+ "create",
771
+ "table",
772
+ "drop",
773
+ "alter",
774
+ "join",
775
+ "inner",
776
+ "left",
777
+ "right",
778
+ "on",
779
+ "group",
780
+ "by",
781
+ "order",
782
+ "asc",
783
+ "desc",
784
+ "having",
785
+ "limit",
786
+ "and",
787
+ "or",
788
+ "not",
789
+ "null",
790
+ "primary",
791
+ "key",
792
+ "foreign",
793
+ "references"
794
+ ]);
795
+ function tokenizeCodeLine(line, lang = "", theme = "dark") {
796
+ var _a;
797
+ const COLORS = theme === "light" ? SYNTAX_COLORS_LIGHT : SYNTAX_COLORS;
798
+ if (!line) {
799
+ return [{ text: " ", type: "plain", colorHex: COLORS.plain }];
800
+ }
801
+ const normalizedLang = (lang || "").toLowerCase().trim();
802
+ const tokens = [];
803
+ let pos = 0;
804
+ if (line.trimStart().startsWith("//") || line.trimStart().startsWith("#") || line.trimStart().startsWith("--")) {
805
+ const leadWs = ((_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) || "";
806
+ if (leadWs) {
807
+ tokens.push({ text: leadWs, type: "plain", colorHex: COLORS.plain });
808
+ }
809
+ tokens.push({
810
+ text: line.slice(leadWs.length),
811
+ type: "comment",
812
+ colorHex: COLORS.comment,
813
+ italic: true
814
+ });
815
+ return tokens;
816
+ }
817
+ while (pos < line.length) {
818
+ if (/\s/.test(line[pos])) {
819
+ let ws = "";
820
+ while (pos < line.length && /\s/.test(line[pos])) {
821
+ ws += line[pos++];
822
+ }
823
+ tokens.push({ text: ws, type: "plain", colorHex: COLORS.plain });
824
+ continue;
825
+ }
826
+ if (line.slice(pos, pos + 2) === "//") {
827
+ tokens.push({
828
+ text: line.slice(pos),
829
+ type: "comment",
830
+ colorHex: COLORS.comment,
831
+ italic: true
832
+ });
833
+ break;
834
+ }
835
+ if (line[pos] === '"' || line[pos] === "'" || line[pos] === "`") {
836
+ const quote = line[pos];
837
+ let str = quote;
838
+ pos++;
839
+ while (pos < line.length) {
840
+ if (line[pos] === "\\" && pos + 1 < line.length) {
841
+ str += line[pos] + line[pos + 1];
842
+ pos += 2;
843
+ continue;
844
+ }
845
+ str += line[pos];
846
+ if (line[pos] === quote) {
847
+ pos++;
848
+ break;
849
+ }
850
+ pos++;
851
+ }
852
+ tokens.push({ text: str, type: "string", colorHex: COLORS.string });
853
+ continue;
854
+ }
855
+ if (/\d/.test(line[pos])) {
856
+ let num = "";
857
+ while (pos < line.length && /[\d.a-fA-FxX]/.test(line[pos])) {
858
+ num += line[pos++];
859
+ }
860
+ tokens.push({ text: num, type: "number", colorHex: COLORS.number });
861
+ continue;
862
+ }
863
+ if (/[a-zA-Z_$]/.test(line[pos])) {
864
+ let word = "";
865
+ while (pos < line.length && /[a-zA-Z0-9_$]/.test(line[pos])) {
866
+ word += line[pos++];
867
+ }
868
+ if (word === "true" || word === "false" || word === "null" || word === "undefined" || word === "True" || word === "False" || word === "None") {
869
+ tokens.push({ text: word, type: "boolean", colorHex: COLORS.boolean, bold: true });
870
+ continue;
871
+ }
872
+ const isJsKeyword = (!normalizedLang || ["ts", "typescript", "js", "javascript", "tsx", "jsx"].includes(normalizedLang)) && JS_KEYWORDS.has(word);
873
+ const isPyKeyword = ["py", "python"].includes(normalizedLang) && PYTHON_KEYWORDS.has(word);
874
+ const isBashKeyword = ["sh", "bash", "shell", "zsh"].includes(normalizedLang) && BASH_KEYWORDS.has(word);
875
+ const isSqlKeyword = ["sql"].includes(normalizedLang) && SQL_KEYWORDS.has(word.toLowerCase());
876
+ if (isJsKeyword || isPyKeyword || isBashKeyword || isSqlKeyword) {
877
+ tokens.push({ text: word, type: "keyword", colorHex: COLORS.keyword, bold: true });
878
+ continue;
879
+ }
880
+ let nextNonWs = pos;
881
+ while (nextNonWs < line.length && /\s/.test(line[nextNonWs])) {
882
+ nextNonWs++;
883
+ }
884
+ if (line[nextNonWs] === "(") {
885
+ tokens.push({ text: word, type: "function", colorHex: COLORS.function });
886
+ continue;
887
+ }
888
+ if (/^[A-Z][a-zA-Z0-9_$]*$/.test(word)) {
889
+ tokens.push({ text: word, type: "type", colorHex: COLORS.type });
890
+ continue;
891
+ }
892
+ tokens.push({ text: word, type: "plain", colorHex: COLORS.plain });
893
+ continue;
894
+ }
895
+ const char = line[pos++];
896
+ if (["=", "+", "-", "*", "/", "!", ">", "<", "&", "|", "?", ":"].includes(char)) {
897
+ tokens.push({ text: char, type: "operator", colorHex: COLORS.operator });
898
+ } else {
899
+ tokens.push({ text: char, type: "punctuation", colorHex: COLORS.punctuation });
900
+ }
901
+ }
902
+ return tokens;
903
+ }
904
+ function highlightCodeToHtml(code, lang = "") {
905
+ const lines = (code || "").split("\n");
906
+ const htmlLines = lines.map((line) => {
907
+ const tokens = tokenizeCodeLine(line, lang);
908
+ return tokens.map((t) => {
909
+ const escaped = t.text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
910
+ if (t.type === "plain") return escaped;
911
+ return `<span style="color: #${t.colorHex};${t.bold ? " font-weight: bold;" : ""}${t.italic ? " font-style: italic;" : ""}">${escaped}</span>`;
912
+ }).join("");
913
+ });
914
+ return htmlLines.join("\n");
915
+ }
916
+
917
+ // src/core/mermaid/mermaidRenderer.ts
918
+ import { spawnSync as spawnSync2 } from "child_process";
919
+ import * as fs4 from "fs";
920
+ import * as os2 from "os";
921
+ import * as path4 from "path";
922
+ import { pathToFileURL as pathToFileURL2 } from "url";
923
+
924
+ // src/core/pdf/pdfBuilder.ts
925
+ import * as fs3 from "fs";
926
+ import * as path3 from "path";
927
+ import * as os from "os";
928
+ import { pathToFileURL } from "url";
929
+ import { spawnSync } from "child_process";
930
+
931
+ // src/core/html/htmlBuilder.ts
932
+ import * as fs2 from "fs";
933
+ import * as path2 from "path";
934
+
935
+ // src/core/html/htmlThemes.ts
936
+ var THEME_COMPONENTS = `
937
+ /* Fallback CSS variables \u2014 overridden by each named theme's :root block */
938
+ :root {
939
+ --mf-bg: #ffffff;
940
+ --mf-text: #0f172a;
941
+ --mf-text-muted: #64748b;
942
+ --mf-primary: #33CDCF;
943
+ --mf-primary-dark: #009DA0;
944
+ --mf-primary-light: #ECFDFD;
945
+ --mf-border: #e2e8f0;
946
+ --mf-card-bg: #f8fafc;
947
+ --mf-code-bg: #0f172a;
948
+ --mf-code-text: #f8fafc;
949
+ --mf-font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
950
+ --mf-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
951
+ }
952
+
953
+ /* Document header */
954
+ .document-header { margin-bottom: 2.5rem; padding-bottom: 1.5rem; border-bottom: 2px solid var(--mf-border); }
955
+ .document-title { font-size: 2.5rem; font-weight: 800; margin: 0 0 0.5rem 0; }
956
+ .document-subtitle { font-size: 1.25rem; color: var(--mf-text-muted); margin: 0 0 1rem 0; }
957
+ .document-meta { font-size: 0.9rem; color: var(--mf-text-muted); display: flex; gap: 1.5rem; flex-wrap: wrap; }
958
+
959
+ /* Table of Contents */
960
+ .table-of-contents { background: var(--mf-card-bg); border: 1px solid var(--mf-border); border-radius: 8px; padding: 1.5rem 2rem; margin: 2rem 0; }
961
+ .table-of-contents h2 { font-size: 1rem; text-transform: uppercase; letter-spacing: 0.08em; color: var(--mf-text-muted); margin: 0 0 1rem 0; }
962
+ .table-of-contents ul { list-style: none; padding: 0; margin: 0; }
963
+ .table-of-contents li { padding: 0.25rem 0; }
964
+ .table-of-contents a { color: var(--mf-primary-dark); text-decoration: none; }
965
+ .table-of-contents a:hover { text-decoration: underline; }
966
+
967
+ /* Links */
968
+ a { color: var(--mf-primary-dark); font-weight: 600; text-decoration: none; }
969
+ a:hover { text-decoration: underline; }
970
+
971
+ /* Blockquote */
972
+ blockquote { border-left: 4px solid var(--mf-primary); background-color: var(--mf-card-bg); margin: 1.2rem 0; padding: 0.8rem 1.2rem; border-radius: 0 8px 8px 0; color: #334155; font-style: italic; }
973
+
974
+ /* Callout / Alert Boxes */
975
+ .callout { border-left: 4px solid var(--mf-primary); background: var(--mf-card-bg); border-radius: 6px; padding: 1rem 1.2rem; margin: 1.2rem 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
976
+ .callout-title { font-weight: 700; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.4rem; }
977
+ .callout-NOTE { border-color: #33CDCF; background: #ECFDFD; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
978
+ .callout-NOTE .callout-title { color: #009DA0; }
979
+ .callout-TIP { border-color: #10b981; background: #ecfdf5; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
980
+ .callout-TIP .callout-title { color: #10b981; }
981
+ .callout-WARNING { border-color: #f59e0b; background: #fffbeb; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
982
+ .callout-WARNING .callout-title { color: #f59e0b; }
983
+ .callout-CAUTION { border-color: #ef4444; background: #fef2f2; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
984
+ .callout-CAUTION .callout-title { color: #ef4444; }
985
+ .callout-IMPORTANT { border-color: #8b5cf6; background: #f5f3ff; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
986
+ .callout-IMPORTANT .callout-title { color: #8b5cf6; }
987
+
988
+ /* Inline Code */
989
+ code { font-family: var(--mf-font-mono); font-size: 0.88em; background-color: #f1f5f9; padding: 0.2em 0.4em; border-radius: 4px; color: #0f172a; }
990
+
991
+ /* Code Blocks */
992
+ pre { background-color: var(--mf-code-bg); color: var(--mf-code-text); padding: 1.2rem; border-radius: 8px; overflow-x: auto; font-family: var(--mf-font-mono); font-size: 0.9rem; line-height: 1.5; margin: 1.2rem 0; }
993
+ pre code { background-color: transparent; color: inherit; padding: 0; }
994
+
995
+ /* Tables */
996
+ table { width: 100%; border-collapse: collapse; margin: 1.5rem 0; font-size: 0.95rem; }
997
+ th, td { border: 1px solid var(--mf-border); padding: 0.75rem 1rem; text-align: left; }
998
+ th { background-color: var(--mf-card-bg); font-weight: 600; color: #0f172a; }
999
+ tr:nth-child(even) { background-color: var(--mf-card-bg); }
1000
+
1001
+ /* Images */
1002
+ img { max-width: 100%; height: auto; border-radius: 6px; margin: 1rem 0; }
1003
+
1004
+ /* Dividers */
1005
+ hr { border: none; border-top: 1px solid var(--mf-border); margin: 2rem 0; }
1006
+
1007
+ /* Print / PDF */
1008
+ @media print {
1009
+ body { padding: 0; }
1010
+ .document-container { max-width: 100%; }
1011
+ pre, table, blockquote, .callout { break-inside: avoid; }
1012
+ /* Remove scrollbars \u2014 PDF has no scrolling */
1013
+ pre { overflow: visible; white-space: pre-wrap; word-break: break-all; }
1014
+ }
1015
+ `;
1016
+ var THEME_DEFAULT = `
1017
+ :root {
1018
+ --mf-bg: #ffffff;
1019
+ --mf-text: #0f172a;
1020
+ --mf-text-muted: #64748b;
1021
+ --mf-primary: #33CDCF;
1022
+ --mf-primary-dark: #009DA0;
1023
+ --mf-primary-light: #ECFDFD;
1024
+ --mf-border: #e2e8f0;
1025
+ --mf-card-bg: #f8fafc;
1026
+ --mf-code-bg: #0f172a;
1027
+ --mf-code-text: #f8fafc;
1028
+ --mf-font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
1029
+ --mf-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1030
+ }
1031
+ body { background-color: var(--mf-bg); color: var(--mf-text); font-family: var(--mf-font-family); font-size: 15px; line-height: 1.65; margin: 0; padding: 2.5rem; }
1032
+ .document-container { max-width: 860px; margin: 0 auto; }
1033
+ h1, h2, h3, h4, h5, h6 { color: var(--mf-text); font-weight: 700; margin-top: 1.8rem; margin-bottom: 0.8rem; line-height: 1.25; }
1034
+ h1 { font-size: 2.2rem; border-bottom: 2px solid #33CDCF; padding-bottom: 0.5rem; }
1035
+ h2 { font-size: 1.6rem; color: #009DA0; border-bottom: 1px solid #CCFBF1; padding-bottom: 0.4rem; }
1036
+ h3 { font-size: 1.3rem; }
1037
+ h4 { font-size: 1.1rem; }
1038
+ p { margin: 0.8rem 0; }
1039
+ `;
1040
+ var THEME_ACADEMIC = `
1041
+ :root {
1042
+ --mf-bg: #ffffff;
1043
+ --mf-text: #1a1a1a;
1044
+ --mf-text-muted: #555;
1045
+ --mf-primary: #33CDCF;
1046
+ --mf-primary-dark: #009DA0;
1047
+ --mf-primary-light: #ECFDFD;
1048
+ --mf-border: #ccc;
1049
+ --mf-card-bg: #f9f9f9;
1050
+ --mf-code-bg: #1e1e1e;
1051
+ --mf-code-text: #d4d4d4;
1052
+ --mf-font-family: "Merriweather", "Georgia", "Times New Roman", serif;
1053
+ --mf-font-mono: "Courier New", Courier, monospace;
1054
+ }
1055
+ body { font-family: var(--mf-font-family); font-size: 16px; line-height: 1.8; padding: 3rem; color: var(--mf-text); }
1056
+ .document-container { max-width: 780px; margin: 0 auto; text-align: justify; }
1057
+ h1, h2, h3 { font-family: "Times New Roman", Times, serif; font-weight: bold; text-align: left; }
1058
+ h1 { font-size: 2rem; border-bottom: 1px solid #000; padding-bottom: 0.3rem; }
1059
+ h2 { font-size: 1.4rem; border-bottom: 1px solid #ccc; padding-bottom: 0.2rem; }
1060
+ h3 { font-size: 1.2rem; }
1061
+ p { margin: 0.9rem 0; }
1062
+ `;
1063
+ var THEMES = {
1064
+ default: THEME_DEFAULT,
1065
+ academic: THEME_ACADEMIC,
1066
+ github: THEME_DEFAULT,
1067
+ corporate: THEME_DEFAULT,
1068
+ minimal: THEME_DEFAULT,
1069
+ dracula: THEME_DEFAULT
1070
+ };
1071
+
1072
+ // src/core/html/htmlBuilder.ts
1073
+ function escapeHtml(str) {
1074
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1075
+ }
1076
+ async function renderInlinesToHtml(spans = [], baseDir = process.cwd()) {
1077
+ let result = "";
1078
+ for (const span of spans) {
1079
+ if (span.type === "image" && span.url) {
1080
+ const resolved = await resolveImage(span.url, baseDir);
1081
+ const src = resolved ? resolved.dataUri : span.url;
1082
+ const alt = escapeHtml(span.alt || "");
1083
+ const title = span.title ? ` title="${escapeHtml(span.title)}"` : "";
1084
+ const width = span.width ? ` width="${span.width}"` : "";
1085
+ const height = span.height ? ` height="${span.height}"` : "";
1086
+ result += `<img src="${src}" alt="${alt}"${title}${width}${height} />`;
1087
+ continue;
1088
+ }
1089
+ if (span.type === "link" && span.url) {
1090
+ const inner = span.children ? await renderInlinesToHtml(span.children, baseDir) : escapeHtml(span.content);
1091
+ const title = span.title ? ` title="${escapeHtml(span.title)}"` : "";
1092
+ result += `<a href="${escapeHtml(span.url)}"${title}>${inner}</a>`;
1093
+ continue;
1094
+ }
1095
+ if (span.type === "bold") {
1096
+ const inner = span.children ? await renderInlinesToHtml(span.children, baseDir) : escapeHtml(span.content);
1097
+ result += `<strong>${inner}</strong>`;
1098
+ continue;
1099
+ }
1100
+ if (span.type === "italic") {
1101
+ const inner = span.children ? await renderInlinesToHtml(span.children, baseDir) : escapeHtml(span.content);
1102
+ result += `<em>${inner}</em>`;
1103
+ continue;
1104
+ }
1105
+ if (span.type === "strikethrough") {
1106
+ const inner = span.children ? await renderInlinesToHtml(span.children, baseDir) : escapeHtml(span.content);
1107
+ result += `<del>${inner}</del>`;
1108
+ continue;
1109
+ }
1110
+ if (span.type === "code") {
1111
+ result += `<code>${escapeHtml(span.content)}</code>`;
1112
+ continue;
1113
+ }
1114
+ if (span.type === "htmlInline") {
1115
+ result += span.content;
1116
+ continue;
1117
+ }
1118
+ result += escapeHtml(span.content);
1119
+ }
1120
+ return result;
1121
+ }
1122
+ async function buildHtmlDocument(doc, config, baseDir = process.cwd()) {
1123
+ var _a;
1124
+ const metadata = { ...config.metadata, ...doc.metadata };
1125
+ const themeName = metadata.theme || config.theme || "default";
1126
+ const baseThemeCss = THEMES[themeName] || THEMES.default;
1127
+ let customCss = "";
1128
+ if (config.css) {
1129
+ const cssList = Array.isArray(config.css) ? config.css : [config.css];
1130
+ for (const cssPath of cssList) {
1131
+ const fullCssPath = path2.isAbsolute(cssPath) ? cssPath : path2.resolve(baseDir, cssPath);
1132
+ if (fs2.existsSync(fullCssPath)) {
1133
+ customCss += `
1134
+ /* Custom CSS: ${cssPath} */
1135
+ ` + fs2.readFileSync(fullCssPath, "utf-8");
1136
+ }
1137
+ }
1138
+ }
1139
+ const inlinedCss = doc.inlinedStyles.join("\n");
1140
+ let bodyHtml = "";
1141
+ if (metadata.title) {
1142
+ bodyHtml += ` <header class="document-header">
1143
+ `;
1144
+ bodyHtml += ` <h1 class="document-title">${escapeHtml(metadata.title)}</h1>
1145
+ `;
1146
+ if (metadata.subtitle) {
1147
+ bodyHtml += ` <div class="document-subtitle">${escapeHtml(metadata.subtitle)}</div>
1148
+ `;
1149
+ }
1150
+ if (metadata.author || metadata.date) {
1151
+ bodyHtml += ` <div class="document-meta">
1152
+ `;
1153
+ if (metadata.author) {
1154
+ const authors = Array.isArray(metadata.author) ? metadata.author.join(", ") : metadata.author;
1155
+ bodyHtml += ` <span>Author: ${escapeHtml(authors)}</span>
1156
+ `;
1157
+ }
1158
+ if (metadata.date) {
1159
+ bodyHtml += ` <span>Date: ${escapeHtml(metadata.date)}</span>
1160
+ `;
1161
+ }
1162
+ bodyHtml += ` </div>
1163
+ `;
1164
+ }
1165
+ bodyHtml += ` </header>
1166
+ `;
1167
+ }
1168
+ if (config.toc || metadata.toc) {
1169
+ if (doc.tocEntries.length > 0) {
1170
+ bodyHtml += ` <nav class="table-of-contents">
1171
+ `;
1172
+ bodyHtml += ` <h2>Table of Contents</h2>
1173
+ <ul>
1174
+ `;
1175
+ for (const entry of doc.tocEntries) {
1176
+ const indent = " ".repeat(entry.level);
1177
+ bodyHtml += ` ${indent}<li><a href="#${entry.id}">${escapeHtml(entry.text)}</a></li>
1178
+ `;
1179
+ }
1180
+ bodyHtml += ` </ul>
1181
+ </nav>
1182
+ `;
1183
+ }
1184
+ }
1185
+ for (const node of doc.nodes) {
1186
+ if (node.type === "heading") {
1187
+ const inner = await renderInlinesToHtml(node.inlines, baseDir);
1188
+ bodyHtml += ` <h${node.level} id="${node.id}">${inner}</h${node.level}>
1189
+ `;
1190
+ continue;
1191
+ }
1192
+ if (node.type === "paragraph") {
1193
+ const inner = await renderInlinesToHtml(node.inlines, baseDir);
1194
+ bodyHtml += ` <p>${inner}</p>
1195
+ `;
1196
+ continue;
1197
+ }
1198
+ if (node.type === "codeBlock") {
1199
+ const lang = node.language || "";
1200
+ const langClass = lang ? ` class="language-${escapeHtml(lang)}"` : "";
1201
+ const highlighted = highlightCodeToHtml(node.text || "", lang);
1202
+ bodyHtml += ` <pre><code${langClass}>${highlighted}</code></pre>
1203
+ `;
1204
+ continue;
1205
+ }
1206
+ if (node.type === "mermaid") {
1207
+ bodyHtml += ` <div class="mermaid">
1208
+ ${escapeHtml(node.text || "")}
1209
+ </div>
1210
+ `;
1211
+ continue;
1212
+ }
1213
+ if (node.type === "callout") {
1214
+ const inner = await renderInlinesToHtml(node.inlines, baseDir);
1215
+ const CALLOUT_STYLES = {
1216
+ NOTE: { bg: "#ECFDFD", border: "#33CDCF", titleColor: "#009DA0" },
1217
+ TIP: { bg: "#ecfdf5", border: "#10b981", titleColor: "#10b981" },
1218
+ WARNING: { bg: "#fffbeb", border: "#f59e0b", titleColor: "#f59e0b" },
1219
+ CAUTION: { bg: "#fef2f2", border: "#ef4444", titleColor: "#ef4444" },
1220
+ IMPORTANT: { bg: "#f5f3ff", border: "#8b5cf6", titleColor: "#8b5cf6" }
1221
+ };
1222
+ const cs = CALLOUT_STYLES[node.calloutType ?? "NOTE"] ?? CALLOUT_STYLES["NOTE"];
1223
+ bodyHtml += ` <div class="callout callout-${node.calloutType}" style="border-left:4px solid ${cs.border};background:${cs.bg};border-radius:6px;padding:1rem 1.2rem;margin:1.2rem 0;">
1224
+ `;
1225
+ bodyHtml += ` <div class="callout-title" style="font-weight:700;font-size:0.85rem;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:0.4rem;color:${cs.titleColor};">${node.calloutType}</div>
1226
+ `;
1227
+ bodyHtml += ` <div class="callout-body">${inner}</div>
1228
+ `;
1229
+ bodyHtml += ` </div>
1230
+ `;
1231
+ continue;
1232
+ }
1233
+ if (node.type === "blockquote") {
1234
+ const inner = await renderInlinesToHtml(node.inlines, baseDir);
1235
+ bodyHtml += ` <blockquote>${inner}</blockquote>
1236
+ `;
1237
+ continue;
1238
+ }
1239
+ if (node.type === "table" && node.children) {
1240
+ bodyHtml += ` <table>
1241
+ `;
1242
+ for (const row of node.children) {
1243
+ bodyHtml += ` <tr>
1244
+ `;
1245
+ if (row.children) {
1246
+ for (let colIdx = 0; colIdx < row.children.length; colIdx++) {
1247
+ const cell = row.children[colIdx];
1248
+ const tag = row.isHeader ? "th" : "td";
1249
+ const align = ((_a = node.align) == null ? void 0 : _a[colIdx]) ? ` style="text-align: ${node.align[colIdx]}"` : "";
1250
+ const cellInner = await renderInlinesToHtml(cell.inlines, baseDir);
1251
+ bodyHtml += ` <${tag}${align}>${cellInner}</${tag}>
1252
+ `;
1253
+ }
1254
+ }
1255
+ bodyHtml += ` </tr>
1256
+ `;
1257
+ }
1258
+ bodyHtml += ` </table>
1259
+ `;
1260
+ continue;
1261
+ }
1262
+ if (node.type === "list" && node.children) {
1263
+ const tag = node.ordered ? "ol" : "ul";
1264
+ bodyHtml += ` <${tag}>
1265
+ `;
1266
+ for (const item of node.children) {
1267
+ const itemInner = await renderInlinesToHtml(item.inlines, baseDir);
1268
+ let prefix = "";
1269
+ if (item.checked !== void 0) {
1270
+ prefix = `<input type="checkbox" disabled ${item.checked ? "checked" : ""}/> `;
1271
+ }
1272
+ bodyHtml += ` <li>${prefix}${itemInner}</li>
1273
+ `;
1274
+ }
1275
+ bodyHtml += ` </${tag}>
1276
+ `;
1277
+ continue;
1278
+ }
1279
+ if (node.type === "htmlBlock") {
1280
+ bodyHtml += ` ${node.rawHtml}
1281
+ `;
1282
+ continue;
1283
+ }
1284
+ if (node.type === "thematicBreak") {
1285
+ bodyHtml += ` <hr />
1286
+ `;
1287
+ continue;
1288
+ }
1289
+ }
1290
+ const wmConfig = config.watermark ?? metadata.watermark;
1291
+ let watermarkHtml = "";
1292
+ let watermarkCss = "";
1293
+ if (wmConfig) {
1294
+ const wmText = typeof wmConfig === "string" ? wmConfig : wmConfig.text;
1295
+ const opacity = typeof wmConfig === "object" && wmConfig.opacity !== void 0 ? wmConfig.opacity : 0.12;
1296
+ const rotate = typeof wmConfig === "object" && wmConfig.rotate !== void 0 ? wmConfig.rotate : -45;
1297
+ const color = typeof wmConfig === "object" && wmConfig.color ? wmConfig.color : "#94A3B8";
1298
+ const fontSize = typeof wmConfig === "object" && wmConfig.fontSize ? `${wmConfig.fontSize}pt` : "52pt";
1299
+ watermarkCss = `
1300
+ .document-watermark {
1301
+ position: fixed;
1302
+ top: 50%;
1303
+ left: 50%;
1304
+ transform: translate(-50%, -50%) rotate(${rotate}deg);
1305
+ font-size: ${fontSize};
1306
+ font-weight: 800;
1307
+ color: ${color};
1308
+ opacity: ${opacity};
1309
+ pointer-events: none;
1310
+ user-select: none;
1311
+ z-index: 9999;
1312
+ text-transform: uppercase;
1313
+ letter-spacing: 0.15em;
1314
+ white-space: nowrap;
1315
+ }
1316
+ `;
1317
+ watermarkHtml = ` <div class="document-watermark">${escapeHtml(wmText)}</div>
1318
+ `;
1319
+ }
1320
+ const hasMermaid = doc.nodes.some((n) => n.type === "mermaid");
1321
+ const mermaidScript = hasMermaid ? `<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
1322
+ <script>
1323
+ mermaid.initialize({
1324
+ startOnLoad: true,
1325
+ theme: 'neutral',
1326
+ themeVariables: {
1327
+ primaryColor: '#33CDCF',
1328
+ primaryTextColor: '#0F172A',
1329
+ primaryBorderColor: '#009DA0',
1330
+ lineColor: '#009DA0',
1331
+ secondaryColor: '#ECFDFD',
1332
+ tertiaryColor: '#F8FAFC'
1333
+ }
1334
+ });
1335
+ </script>` : "";
1336
+ const documentTitle = metadata.title || "MarkForge Document";
1337
+ return `<!DOCTYPE html>
1338
+ <html lang="${metadata.lang || "en"}">
1339
+ <head>
1340
+ <meta charset="UTF-8">
1341
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1342
+ <title>${escapeHtml(documentTitle)}</title>
1343
+ <style>
1344
+ ${THEME_COMPONENTS}
1345
+ ${baseThemeCss}
1346
+ ${customCss}
1347
+ ${inlinedCss}
1348
+ ${watermarkCss}
1349
+ </style>
1350
+ </head>
1351
+ <body>
1352
+ ${watermarkHtml} <div class="document-container">
1353
+ ${bodyHtml} </div>
1354
+ ${mermaidScript}
1355
+ </body>
1356
+ </html>`;
1357
+ }
1358
+
1359
+ // src/core/pdf/pdfBuilder.ts
1360
+ function findChromeExecutable() {
1361
+ if (process.env.CHROME_PATH && fs3.existsSync(process.env.CHROME_PATH)) {
1362
+ return process.env.CHROME_PATH;
1363
+ }
1364
+ if (process.env.PUPPETEER_EXECUTABLE_PATH && fs3.existsSync(process.env.PUPPETEER_EXECUTABLE_PATH)) {
1365
+ return process.env.PUPPETEER_EXECUTABLE_PATH;
1366
+ }
1367
+ const isWin = process.platform === "win32";
1368
+ const winLocalAppData = process.env.LOCALAPPDATA ?? "";
1369
+ const winProgramFiles = process.env.PROGRAMFILES ?? "C:\\Program Files";
1370
+ const winProgramFilesX86 = process.env["PROGRAMFILES(X86)"] ?? "C:\\Program Files (x86)";
1371
+ const candidates = [
1372
+ // Linux
1373
+ "/usr/bin/google-chrome",
1374
+ "/usr/bin/google-chrome-stable",
1375
+ "/usr/bin/chromium",
1376
+ "/usr/bin/chromium-browser",
1377
+ "/snap/bin/chromium",
1378
+ "/usr/bin/microsoft-edge",
1379
+ "/usr/bin/microsoft-edge-stable",
1380
+ "/usr/bin/brave-browser",
1381
+ // macOS
1382
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
1383
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
1384
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
1385
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
1386
+ // Windows — Google Chrome
1387
+ `${winProgramFiles}\\Google\\Chrome\\Application\\chrome.exe`,
1388
+ `${winProgramFilesX86}\\Google\\Chrome\\Application\\chrome.exe`,
1389
+ `${winLocalAppData}\\Google\\Chrome\\Application\\chrome.exe`,
1390
+ // Windows — Microsoft Edge (ships with Windows 10/11)
1391
+ `${winProgramFiles}\\Microsoft\\Edge\\Application\\msedge.exe`,
1392
+ `${winProgramFilesX86}\\Microsoft\\Edge\\Application\\msedge.exe`,
1393
+ `${winLocalAppData}\\Microsoft\\Edge\\Application\\msedge.exe`,
1394
+ // Windows — Brave Browser
1395
+ `${winProgramFiles}\\BraveSoftware\\Brave-Browser\\Application\\brave.exe`,
1396
+ `${winProgramFilesX86}\\BraveSoftware\\Brave-Browser\\Application\\brave.exe`,
1397
+ `${winLocalAppData}\\BraveSoftware\\Brave-Browser\\Application\\brave.exe`,
1398
+ // Windows — Chromium
1399
+ `${winLocalAppData}\\Chromium\\Application\\chrome.exe`
1400
+ ].filter(Boolean);
1401
+ for (const candidate of candidates) {
1402
+ try {
1403
+ if (fs3.existsSync(candidate)) {
1404
+ return candidate;
1405
+ }
1406
+ } catch {
1407
+ }
1408
+ }
1409
+ try {
1410
+ const cmd = isWin ? "where" : "which";
1411
+ const names = isWin ? ["chrome", "msedge", "brave", "google-chrome", "chromium", "chromium-browser"] : ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge", "brave-browser"];
1412
+ for (const name of names) {
1413
+ const res = spawnSync(cmd, [name], { encoding: "utf-8" });
1414
+ if (res.status === 0 && res.stdout.trim()) {
1415
+ const binPath = res.stdout.split(/\r?\n/)[0].trim();
1416
+ if (fs3.existsSync(binPath)) return binPath;
1417
+ }
1418
+ }
1419
+ } catch {
1420
+ }
1421
+ return null;
1422
+ }
1423
+ function injectPagedMediaStyles(html, config, metadata) {
1424
+ var _a, _b, _c, _d;
1425
+ const merged = { ...config.metadata, ...metadata };
1426
+ const orientation = merged.orientation || config.orientation || "portrait";
1427
+ const size = merged.paperSize || config.paperSize || "A4";
1428
+ const margins = merged.margins || config.margins || {};
1429
+ const top = margins.top || ((_a = config.margins) == null ? void 0 : _a.top) || "2.5cm";
1430
+ const bottom = margins.bottom || ((_b = config.margins) == null ? void 0 : _b.bottom) || "2.5cm";
1431
+ const left = margins.left || ((_c = config.margins) == null ? void 0 : _c.left) || "2.5cm";
1432
+ const right = margins.right || ((_d = config.margins) == null ? void 0 : _d.right) || "2.5cm";
1433
+ const headerCfg = merged.header;
1434
+ const footerCfg = merged.footer;
1435
+ const headerLeft = (headerCfg == null ? void 0 : headerCfg.left) ?? "";
1436
+ const headerCenter = (headerCfg == null ? void 0 : headerCfg.center) ?? "";
1437
+ const headerRight = (headerCfg == null ? void 0 : headerCfg.right) ?? "";
1438
+ const footerLeft = ((footerCfg == null ? void 0 : footerCfg.left) ?? "").replace("{page}", "").replace("{pages}", "").trim();
1439
+ const esc = (s) => s.replace(/"/g, '"').replace(/\\/g, "\\\\");
1440
+ const pagedCss = `
1441
+ @page {
1442
+ size: ${size} ${orientation};
1443
+ margin-top: ${top};
1444
+ margin-bottom: ${bottom};
1445
+ margin-left: ${left};
1446
+ margin-right: ${right};
1447
+ ${headerLeft ? `@top-left { content: "${esc(headerLeft)}"; font-size: 9pt; color: #94a3b8; }` : ""}
1448
+ ${headerCenter ? `@top-center { content: "${esc(headerCenter)}"; font-size: 9pt; color: #94a3b8; }` : ""}
1449
+ ${headerRight ? `@top-right { content: "${esc(headerRight)}"; font-size: 9pt; color: #94a3b8; }` : ""}
1450
+ ${footerLeft ? `@bottom-left { content: "${esc(footerLeft)}"; font-size: 9pt; color: #94a3b8; }` : ""}
1451
+ @bottom-right {
1452
+ content: "Page " counter(page) " of " counter(pages);
1453
+ font-size: 9pt;
1454
+ color: #94a3b8;
1455
+ }
1456
+ }
1457
+ @media print {
1458
+ body { padding: 0; }
1459
+ h1, h2, h3, pre, table, blockquote, .callout {
1460
+ break-inside: avoid;
1461
+ }
1462
+ }
1463
+ `;
1464
+ return html.replace("</head>", `<style>${pagedCss}</style></head>`);
1465
+ }
1466
+ function createFallbackPdfBuffer(title = "Document") {
1467
+ const streamContent = `BT /F1 18 Tf 50 750 Td (${title}) Tj ET
1468
+ BT /F1 12 Tf 50 720 Td (Generated via MarkForge Fallback Renderer) Tj ET`;
1469
+ const streamLength = Buffer.byteLength(streamContent, "utf-8");
1470
+ const pdfBody = `%PDF-1.4
1471
+ 1 0 obj
1472
+ << /Type /Catalog /Pages 2 0 R >>
1473
+ endobj
1474
+ 2 0 obj
1475
+ << /Type /Pages /Kids [3 0 R] /Count 1 >>
1476
+ endobj
1477
+ 3 0 obj
1478
+ << /Type /Page /Parent 2 0 R /MediaBox [0 0 595.28 841.89] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>
1479
+ endobj
1480
+ 4 0 obj
1481
+ << /Length ${streamLength} >>
1482
+ stream
1483
+ ${streamContent}
1484
+ endstream
1485
+ endobj
1486
+ 5 0 obj
1487
+ << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
1488
+ endobj
1489
+ xref
1490
+ 0 6
1491
+ 0000000000 65535 f
1492
+ 0000000009 00000 n
1493
+ 0000000058 00000 n
1494
+ 0000000115 00000 n
1495
+ 0000000266 00000 n
1496
+ 0000000373 00000 n
1497
+ trailer
1498
+ << /Size 6 /Root 1 0 R >>
1499
+ startxref
1500
+ 453
1501
+ %%EOF
1502
+ `;
1503
+ return Buffer.from(pdfBody, "utf-8");
1504
+ }
1505
+ async function buildPdfDocument(doc, config, baseDir = process.cwd()) {
1506
+ const baseHtml = await buildHtmlDocument(doc, config, baseDir);
1507
+ const pagedHtml = injectPagedMediaStyles(baseHtml, config, doc.metadata);
1508
+ const chromePath = findChromeExecutable();
1509
+ if (chromePath) {
1510
+ const tmpId = Math.random().toString(36).substring(2, 9);
1511
+ const tmpDir = os.tmpdir();
1512
+ const tmpHtml = path3.join(tmpDir, `markforge_${tmpId}.html`);
1513
+ const tmpPdf = path3.join(tmpDir, `markforge_${tmpId}.pdf`);
1514
+ try {
1515
+ fs3.writeFileSync(tmpHtml, pagedHtml, "utf-8");
1516
+ const fileUrl = pathToFileURL(tmpHtml).href;
1517
+ let res = spawnSync(
1518
+ chromePath,
1519
+ [
1520
+ "--headless=new",
1521
+ "--disable-gpu",
1522
+ "--no-sandbox",
1523
+ "--disable-setuid-sandbox",
1524
+ "--allow-file-access-from-files",
1525
+ "--disable-web-security",
1526
+ "--force-color-profile=srgb",
1527
+ "--run-all-compositor-stages-before-draw",
1528
+ "--virtual-time-budget=8000",
1529
+ "--no-pdf-header-footer",
1530
+ `--print-to-pdf=${tmpPdf}`,
1531
+ fileUrl
1532
+ ],
1533
+ { timeout: 3e4 }
1534
+ );
1535
+ if ((res.status !== 0 || !fs3.existsSync(tmpPdf)) && chromePath) {
1536
+ res = spawnSync(
1537
+ chromePath,
1538
+ [
1539
+ "--headless",
1540
+ "--disable-gpu",
1541
+ "--no-sandbox",
1542
+ "--disable-setuid-sandbox",
1543
+ "--allow-file-access-from-files",
1544
+ "--disable-web-security",
1545
+ "--force-color-profile=srgb",
1546
+ "--no-pdf-header-footer",
1547
+ `--print-to-pdf=${tmpPdf}`,
1548
+ fileUrl
1549
+ ],
1550
+ { timeout: 3e4 }
1551
+ );
1552
+ }
1553
+ if (fs3.existsSync(tmpPdf) && fs3.statSync(tmpPdf).size > 0) {
1554
+ const pdfBuffer = fs3.readFileSync(tmpPdf);
1555
+ return pdfBuffer;
1556
+ }
1557
+ } catch {
1558
+ } finally {
1559
+ try {
1560
+ if (fs3.existsSync(tmpHtml)) fs3.unlinkSync(tmpHtml);
1561
+ if (fs3.existsSync(tmpPdf)) fs3.unlinkSync(tmpPdf);
1562
+ } catch {
1563
+ }
1564
+ }
1565
+ }
1566
+ return createFallbackPdfBuffer(doc.metadata.title || "MarkForge Document");
1567
+ }
1568
+
1569
+ // src/core/mermaid/mermaidRenderer.ts
1570
+ async function renderMermaidToPng(mermaidCode, _baseDir = process.cwd()) {
1571
+ const chromePath = findChromeExecutable();
1572
+ if (!chromePath) {
1573
+ return null;
1574
+ }
1575
+ const tmpId = Math.random().toString(36).substring(2, 9);
1576
+ const tmpDir = os2.tmpdir();
1577
+ const tmpHtml = path4.join(tmpDir, `mermaid_${tmpId}.html`);
1578
+ const tmpScreenshot = path4.join(tmpDir, `mermaid_${tmpId}.png`);
1579
+ const htmlContent = `<!DOCTYPE html>
1580
+ <html>
1581
+ <head>
1582
+ <meta charset="utf-8">
1583
+ <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
1584
+ <style>
1585
+ body {
1586
+ margin: 0;
1587
+ padding: 16px;
1588
+ background: #ffffff;
1589
+ display: inline-block;
1590
+ }
1591
+ .mermaid {
1592
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1593
+ }
1594
+ </style>
1595
+ </head>
1596
+ <body>
1597
+ <div id="container" class="mermaid">
1598
+ ${mermaidCode}
1599
+ </div>
1600
+ <script>
1601
+ mermaid.initialize({
1602
+ startOnLoad: true,
1603
+ theme: 'neutral',
1604
+ themeVariables: {
1605
+ primaryColor: '#33CDCF',
1606
+ primaryTextColor: '#0F172A',
1607
+ primaryBorderColor: '#009DA0',
1608
+ lineColor: '#009DA0',
1609
+ secondaryColor: '#ECFDFD',
1610
+ tertiaryColor: '#F8FAFC'
1611
+ }
1612
+ });
1613
+ </script>
1614
+ </body>
1615
+ </html>`;
1616
+ try {
1617
+ fs4.writeFileSync(tmpHtml, htmlContent, "utf-8");
1618
+ const fileUrl = pathToFileURL2(tmpHtml).href;
1619
+ const res = spawnSync2(
1620
+ chromePath,
1621
+ [
1622
+ "--headless",
1623
+ "--disable-gpu",
1624
+ "--no-sandbox",
1625
+ "--disable-setuid-sandbox",
1626
+ "--allow-file-access-from-files",
1627
+ "--disable-web-security",
1628
+ "--disable-software-rasterizer",
1629
+ "--window-size=1200,800",
1630
+ "--virtual-time-budget=5000",
1631
+ `--screenshot=${tmpScreenshot}`,
1632
+ fileUrl
1633
+ ],
1634
+ { timeout: 15e3 }
1635
+ );
1636
+ if (res.status === 0 && fs4.existsSync(tmpScreenshot)) {
1637
+ const buffer = fs4.readFileSync(tmpScreenshot);
1638
+ return buffer;
1639
+ }
1640
+ } catch {
1641
+ } finally {
1642
+ try {
1643
+ if (fs4.existsSync(tmpHtml)) fs4.unlinkSync(tmpHtml);
1644
+ if (fs4.existsSync(tmpScreenshot)) fs4.unlinkSync(tmpScreenshot);
1645
+ } catch {
1646
+ }
1647
+ }
1648
+ return null;
1649
+ }
1650
+
1651
+ // src/core/docx/docxBuilder.ts
1652
+ function parseMarginToTwip(margin, defaultTwip = 1440) {
1653
+ if (typeof margin === "number") return margin;
1654
+ if (!margin) return defaultTwip;
1655
+ const str = margin.trim().toLowerCase();
1656
+ if (str.endsWith("cm")) {
1657
+ const cm = parseFloat(str);
1658
+ return Math.round(convertMillimetersToTwip(cm * 10));
1659
+ }
1660
+ if (str.endsWith("mm")) {
1661
+ const mm = parseFloat(str);
1662
+ return Math.round(convertMillimetersToTwip(mm));
1663
+ }
1664
+ if (str.endsWith("in") || str.endsWith("inch")) {
1665
+ const inch = parseFloat(str);
1666
+ return Math.round(convertInchesToTwip(inch));
1667
+ }
1668
+ if (str.endsWith("pt")) {
1669
+ const pt = parseFloat(str);
1670
+ return Math.round(pt * 20);
1671
+ }
1672
+ const val = parseFloat(str);
1673
+ return isNaN(val) ? defaultTwip : Math.round(val);
1674
+ }
1675
+ async function convertInlinesToTextRuns(spans = [], baseDir = process.cwd()) {
1676
+ const runs = [];
1677
+ for (const span of spans) {
1678
+ if (span.type === "image" && span.url) {
1679
+ const resolved = await resolveImage(span.url, baseDir);
1680
+ if (resolved) {
1681
+ let width = 500;
1682
+ let height = 300;
1683
+ if (span.width) width = parseInt(String(span.width), 10) || 500;
1684
+ if (span.height) height = parseInt(String(span.height), 10) || 300;
1685
+ runs.push(
1686
+ new ImageRun({
1687
+ data: resolved.buffer,
1688
+ transformation: {
1689
+ width: Math.min(width, 550),
1690
+ height: Math.min(height, 400)
1691
+ },
1692
+ type: "png"
1693
+ })
1694
+ );
1695
+ }
1696
+ continue;
1697
+ }
1698
+ if (span.type === "link" && span.url) {
1699
+ runs.push(
1700
+ new ExternalHyperlink({
1701
+ children: [
1702
+ new TextRun({
1703
+ text: span.content,
1704
+ style: "Hyperlink",
1705
+ color: "0969DA",
1706
+ underline: {}
1707
+ })
1708
+ ],
1709
+ link: span.url
1710
+ })
1711
+ );
1712
+ continue;
1713
+ }
1714
+ if (span.type === "bold") {
1715
+ runs.push(
1716
+ new TextRun({
1717
+ text: span.content,
1718
+ bold: true
1719
+ })
1720
+ );
1721
+ continue;
1722
+ }
1723
+ if (span.type === "italic") {
1724
+ runs.push(
1725
+ new TextRun({
1726
+ text: span.content,
1727
+ italics: true
1728
+ })
1729
+ );
1730
+ continue;
1731
+ }
1732
+ if (span.type === "strikethrough") {
1733
+ runs.push(
1734
+ new TextRun({
1735
+ text: span.content,
1736
+ strike: true
1737
+ })
1738
+ );
1739
+ continue;
1740
+ }
1741
+ if (span.type === "code") {
1742
+ runs.push(
1743
+ new TextRun({
1744
+ text: ` ${span.content} `,
1745
+ font: "Consolas",
1746
+ shading: {
1747
+ type: ShadingType.CLEAR,
1748
+ fill: "F1F5F9",
1749
+ color: "0F172A"
1750
+ }
1751
+ })
1752
+ );
1753
+ continue;
1754
+ }
1755
+ if (span.type === "htmlInline") {
1756
+ let colorHex;
1757
+ let bgHex;
1758
+ let isBold = false;
1759
+ let isItalic = false;
1760
+ if (span.style) {
1761
+ if (span.style.color) {
1762
+ colorHex = span.style.color.replace("#", "").trim();
1763
+ }
1764
+ if (span.style.background || span.style["background-color"]) {
1765
+ bgHex = (span.style.background || span.style["background-color"]).replace("#", "").trim();
1766
+ }
1767
+ if (span.style["font-weight"] === "bold" || span.style["font-weight"] === "700") {
1768
+ isBold = true;
1769
+ }
1770
+ if (span.style["font-style"] === "italic") {
1771
+ isItalic = true;
1772
+ }
1773
+ }
1774
+ if (span.children && span.children.length > 0) {
1775
+ const childRuns = await convertInlinesToTextRuns(span.children, baseDir);
1776
+ for (const child of childRuns) {
1777
+ if (child instanceof TextRun) {
1778
+ runs.push(child);
1779
+ } else {
1780
+ runs.push(child);
1781
+ }
1782
+ }
1783
+ continue;
1784
+ }
1785
+ runs.push(
1786
+ new TextRun({
1787
+ text: span.content,
1788
+ color: colorHex,
1789
+ bold: isBold,
1790
+ italics: isItalic,
1791
+ shading: bgHex ? { type: ShadingType.CLEAR, fill: bgHex } : void 0
1792
+ })
1793
+ );
1794
+ continue;
1795
+ }
1796
+ runs.push(
1797
+ new TextRun({
1798
+ text: span.content
1799
+ })
1800
+ );
1801
+ }
1802
+ return runs;
1803
+ }
1804
+ async function buildDocxDocument(doc, config, baseDir = process.cwd()) {
1805
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1806
+ const metadata = { ...config.metadata, ...doc.metadata };
1807
+ const docElements = [];
1808
+ if (metadata.title) {
1809
+ docElements.push(
1810
+ new Paragraph({
1811
+ text: metadata.title,
1812
+ heading: HeadingLevel.TITLE,
1813
+ spacing: { before: 200, after: 120 }
1814
+ })
1815
+ );
1816
+ if (metadata.subtitle) {
1817
+ docElements.push(
1818
+ new Paragraph({
1819
+ children: [
1820
+ new TextRun({
1821
+ text: metadata.subtitle,
1822
+ italics: true,
1823
+ color: "64748B",
1824
+ size: 24
1825
+ // 12pt
1826
+ })
1827
+ ],
1828
+ spacing: { after: 180 }
1829
+ })
1830
+ );
1831
+ }
1832
+ if (metadata.author || metadata.date) {
1833
+ const metaParts = [];
1834
+ if (metadata.author) metaParts.push(`Author: ${Array.isArray(metadata.author) ? metadata.author.join(", ") : metadata.author}`);
1835
+ if (metadata.date) metaParts.push(`Date: ${metadata.date}`);
1836
+ docElements.push(
1837
+ new Paragraph({
1838
+ children: [
1839
+ new TextRun({
1840
+ text: metaParts.join(" | "),
1841
+ color: "94A3B8",
1842
+ size: 20
1843
+ // 10pt
1844
+ })
1845
+ ],
1846
+ spacing: { after: 360 },
1847
+ border: {
1848
+ bottom: {
1849
+ color: "E2E8F0",
1850
+ space: 10,
1851
+ style: BorderStyle.SINGLE,
1852
+ size: 6
1853
+ }
1854
+ }
1855
+ })
1856
+ );
1857
+ }
1858
+ }
1859
+ for (const node of doc.nodes) {
1860
+ if (node.type === "heading") {
1861
+ let headingLevel = HeadingLevel.HEADING_1;
1862
+ if (node.level === 2) headingLevel = HeadingLevel.HEADING_2;
1863
+ if (node.level === 3) headingLevel = HeadingLevel.HEADING_3;
1864
+ if (node.level === 4) headingLevel = HeadingLevel.HEADING_4;
1865
+ if (node.level === 5) headingLevel = HeadingLevel.HEADING_5;
1866
+ if (node.level === 6) headingLevel = HeadingLevel.HEADING_6;
1867
+ const runs = await convertInlinesToTextRuns(node.inlines, baseDir);
1868
+ docElements.push(
1869
+ new Paragraph({
1870
+ heading: headingLevel,
1871
+ children: runs,
1872
+ spacing: { before: 240, after: 120 }
1873
+ })
1874
+ );
1875
+ continue;
1876
+ }
1877
+ if (node.type === "paragraph") {
1878
+ const runs = await convertInlinesToTextRuns(node.inlines, baseDir);
1879
+ docElements.push(
1880
+ new Paragraph({
1881
+ children: runs,
1882
+ spacing: { before: 60, after: 140 }
1883
+ })
1884
+ );
1885
+ continue;
1886
+ }
1887
+ if (node.type === "codeBlock") {
1888
+ const codeLines = (node.text || "").split("\n");
1889
+ const codeParagraphs = codeLines.map((l) => {
1890
+ const tokens = tokenizeCodeLine(l, node.language, "light");
1891
+ const textRuns = tokens.map(
1892
+ (t) => new TextRun({
1893
+ text: t.text,
1894
+ font: "Consolas",
1895
+ size: 19,
1896
+ // 9.5pt
1897
+ color: t.colorHex,
1898
+ bold: t.bold,
1899
+ italics: t.italic
1900
+ })
1901
+ );
1902
+ return new Paragraph({
1903
+ children: textRuns,
1904
+ spacing: { before: 20, after: 20 }
1905
+ });
1906
+ });
1907
+ const codeTable = new Table({
1908
+ width: { size: 100, type: WidthType.PERCENTAGE },
1909
+ columnWidths: [9e3],
1910
+ rows: [
1911
+ new TableRow({
1912
+ children: [
1913
+ new TableCell({
1914
+ width: { size: 9e3, type: WidthType.DXA },
1915
+ shading: { fill: "F8FAFC", type: ShadingType.CLEAR },
1916
+ margins: { top: 140, bottom: 140, left: 180, right: 180 },
1917
+ borders: {
1918
+ top: { style: BorderStyle.SINGLE, size: 4, color: "E2E8F0" },
1919
+ bottom: { style: BorderStyle.SINGLE, size: 4, color: "E2E8F0" },
1920
+ left: { style: BorderStyle.SINGLE, size: 8, color: "33CDCF" },
1921
+ right: { style: BorderStyle.SINGLE, size: 4, color: "E2E8F0" }
1922
+ },
1923
+ children: codeParagraphs
1924
+ })
1925
+ ]
1926
+ })
1927
+ ]
1928
+ });
1929
+ docElements.push(codeTable);
1930
+ docElements.push(new Paragraph({ spacing: { after: 120 } }));
1931
+ continue;
1932
+ }
1933
+ if (node.type === "callout") {
1934
+ let borderColor = "33CDCF";
1935
+ let bgFill = "ECFDFD";
1936
+ let title = "NOTE";
1937
+ if (node.calloutType === "TIP") {
1938
+ borderColor = "10B981";
1939
+ bgFill = "ECFDF5";
1940
+ title = "TIP";
1941
+ } else if (node.calloutType === "WARNING") {
1942
+ borderColor = "F59E0B";
1943
+ bgFill = "FFFBEB";
1944
+ title = "WARNING";
1945
+ } else if (node.calloutType === "CAUTION") {
1946
+ borderColor = "EF4444";
1947
+ bgFill = "FEF2F2";
1948
+ title = "CAUTION";
1949
+ } else if (node.calloutType === "IMPORTANT") {
1950
+ borderColor = "8B5CF6";
1951
+ bgFill = "F5F3FF";
1952
+ title = "IMPORTANT";
1953
+ }
1954
+ const runs = await convertInlinesToTextRuns(node.inlines, baseDir);
1955
+ const calloutTable = new Table({
1956
+ width: { size: 100, type: WidthType.PERCENTAGE },
1957
+ columnWidths: [9e3],
1958
+ rows: [
1959
+ new TableRow({
1960
+ children: [
1961
+ new TableCell({
1962
+ width: { size: 9e3, type: WidthType.DXA },
1963
+ shading: { fill: bgFill, type: ShadingType.CLEAR },
1964
+ margins: { top: 120, bottom: 120, left: 160, right: 160 },
1965
+ borders: {
1966
+ top: { style: BorderStyle.NONE },
1967
+ bottom: { style: BorderStyle.NONE },
1968
+ right: { style: BorderStyle.NONE },
1969
+ left: { style: BorderStyle.SINGLE, size: 16, color: borderColor }
1970
+ },
1971
+ children: [
1972
+ new Paragraph({
1973
+ children: [
1974
+ new TextRun({
1975
+ text: `[${title}]`,
1976
+ bold: true,
1977
+ color: borderColor,
1978
+ size: 20
1979
+ })
1980
+ ],
1981
+ spacing: { after: 60 }
1982
+ }),
1983
+ new Paragraph({
1984
+ children: runs
1985
+ })
1986
+ ]
1987
+ })
1988
+ ]
1989
+ })
1990
+ ]
1991
+ });
1992
+ docElements.push(calloutTable);
1993
+ docElements.push(new Paragraph({ spacing: { after: 120 } }));
1994
+ continue;
1995
+ }
1996
+ if (node.type === "blockquote") {
1997
+ const quoteParagraphs = [];
1998
+ const lines = (node.text || "").split("\n\n").filter(Boolean);
1999
+ if (lines.length > 0) {
2000
+ for (const lineText of lines) {
2001
+ const spans = parseInlineSpans(lineText.replace(/^>\s?/, "").trim());
2002
+ const lineRuns = await convertInlinesToTextRuns(spans, baseDir);
2003
+ quoteParagraphs.push(
2004
+ new Paragraph({
2005
+ children: lineRuns,
2006
+ spacing: { before: 40, after: 40 }
2007
+ })
2008
+ );
2009
+ }
2010
+ } else {
2011
+ const runs = await convertInlinesToTextRuns(node.inlines, baseDir);
2012
+ quoteParagraphs.push(new Paragraph({ children: runs }));
2013
+ }
2014
+ const quoteTable = new Table({
2015
+ width: { size: 100, type: WidthType.PERCENTAGE },
2016
+ columnWidths: [9e3],
2017
+ rows: [
2018
+ new TableRow({
2019
+ children: [
2020
+ new TableCell({
2021
+ width: { size: 9e3, type: WidthType.DXA },
2022
+ shading: { fill: "F8FAFC", type: ShadingType.CLEAR },
2023
+ margins: { top: 100, bottom: 100, left: 140, right: 140 },
2024
+ borders: {
2025
+ top: { style: BorderStyle.NONE },
2026
+ bottom: { style: BorderStyle.NONE },
2027
+ right: { style: BorderStyle.NONE },
2028
+ left: { style: BorderStyle.SINGLE, size: 12, color: "33CDCF" }
2029
+ },
2030
+ children: quoteParagraphs
2031
+ })
2032
+ ]
2033
+ })
2034
+ ]
2035
+ });
2036
+ docElements.push(quoteTable);
2037
+ docElements.push(new Paragraph({ spacing: { after: 120 } }));
2038
+ continue;
2039
+ }
2040
+ if (node.type === "mermaid") {
2041
+ const pngBuffer = await renderMermaidToPng(node.text || "", baseDir);
2042
+ if (pngBuffer) {
2043
+ docElements.push(
2044
+ new Paragraph({
2045
+ alignment: AlignmentType.CENTER,
2046
+ children: [
2047
+ new ImageRun({
2048
+ data: pngBuffer,
2049
+ transformation: {
2050
+ width: 550,
2051
+ height: 320
2052
+ },
2053
+ type: "png"
2054
+ })
2055
+ ],
2056
+ spacing: { before: 120, after: 120 }
2057
+ })
2058
+ );
2059
+ } else {
2060
+ docElements.push(
2061
+ new Paragraph({
2062
+ children: [
2063
+ new TextRun({ text: "[Mermaid Diagram: " + (node.text || "").slice(0, 40) + "...]", bold: true, color: "33CDCF" })
2064
+ ],
2065
+ spacing: { before: 60, after: 60 }
2066
+ })
2067
+ );
2068
+ }
2069
+ continue;
2070
+ }
2071
+ if (node.type === "table" && node.children) {
2072
+ const tableRows = [];
2073
+ const numCols = ((_b = (_a = node.children[0]) == null ? void 0 : _a.children) == null ? void 0 : _b.length) || 1;
2074
+ const colWidth = Math.floor(9e3 / numCols);
2075
+ for (const rowNode of node.children) {
2076
+ const cells = [];
2077
+ if (rowNode.children) {
2078
+ for (let colIdx = 0; colIdx < rowNode.children.length; colIdx++) {
2079
+ const cellNode = rowNode.children[colIdx];
2080
+ const align = (_c = node.align) == null ? void 0 : _c[colIdx];
2081
+ let alignment = AlignmentType.LEFT;
2082
+ if (align === "center") alignment = AlignmentType.CENTER;
2083
+ if (align === "right") alignment = AlignmentType.RIGHT;
2084
+ const runs = await convertInlinesToTextRuns(cellNode.inlines, baseDir);
2085
+ cells.push(
2086
+ new TableCell({
2087
+ width: { size: colWidth, type: WidthType.DXA },
2088
+ shading: rowNode.isHeader ? { fill: "F1F5F9", type: ShadingType.CLEAR } : void 0,
2089
+ margins: { top: 100, bottom: 100, left: 120, right: 120 },
2090
+ borders: {
2091
+ top: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
2092
+ bottom: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
2093
+ left: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
2094
+ right: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" }
2095
+ },
2096
+ children: [
2097
+ new Paragraph({
2098
+ alignment,
2099
+ children: rowNode.isHeader ? runs.map((r) => r instanceof TextRun ? new TextRun({ ...r, bold: true, color: "0F172A" }) : r) : runs
2100
+ })
2101
+ ]
2102
+ })
2103
+ );
2104
+ }
2105
+ }
2106
+ tableRows.push(
2107
+ new TableRow({
2108
+ tableHeader: rowNode.isHeader,
2109
+ children: cells
2110
+ })
2111
+ );
2112
+ }
2113
+ const docxTable = new Table({
2114
+ width: { size: 100, type: WidthType.PERCENTAGE },
2115
+ columnWidths: Array(numCols).fill(colWidth),
2116
+ rows: tableRows
2117
+ });
2118
+ docElements.push(docxTable);
2119
+ docElements.push(new Paragraph({ spacing: { after: 140 } }));
2120
+ continue;
2121
+ }
2122
+ if (node.type === "list" && node.children) {
2123
+ for (const item of node.children) {
2124
+ const runs = await convertInlinesToTextRuns(item.inlines, baseDir);
2125
+ let prefix = "";
2126
+ if (item.checked !== void 0) {
2127
+ prefix = item.checked ? "[X] " : "[ ] ";
2128
+ }
2129
+ docElements.push(
2130
+ new Paragraph({
2131
+ bullet: node.ordered ? void 0 : { level: 0 },
2132
+ children: [
2133
+ ...prefix ? [new TextRun({ text: prefix, bold: true, font: "Consolas" })] : [],
2134
+ ...runs
2135
+ ],
2136
+ spacing: { before: 40, after: 40 }
2137
+ })
2138
+ );
2139
+ }
2140
+ docElements.push(new Paragraph({ spacing: { after: 80 } }));
2141
+ continue;
2142
+ }
2143
+ if (node.type === "thematicBreak") {
2144
+ docElements.push(
2145
+ new Paragraph({
2146
+ spacing: { before: 180, after: 180 },
2147
+ border: {
2148
+ bottom: {
2149
+ color: "E2E8F0",
2150
+ space: 4,
2151
+ style: BorderStyle.SINGLE,
2152
+ size: 6
2153
+ }
2154
+ }
2155
+ })
2156
+ );
2157
+ continue;
2158
+ }
2159
+ if (node.type === "htmlBlock" && node.rawHtml) {
2160
+ const isCard = node.rawHtml.includes("card") || node.rawHtml.includes("box") || node.rawHtml.includes("metric");
2161
+ const cleanInner = node.rawHtml.replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<\/p>/gi, "\n\n").replace(/<\/div>/gi, "\n").replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]+>/g, " ").replace(/[ \t]+/g, " ").replace(/\n\s+/g, "\n").trim();
2162
+ if (cleanInner) {
2163
+ const innerParagraphs = cleanInner.split("\n\n").filter(Boolean);
2164
+ const paraElements = [];
2165
+ for (const p of innerParagraphs) {
2166
+ const spans = parseInlineSpans(p.trim());
2167
+ const runs = await convertInlinesToTextRuns(spans, baseDir);
2168
+ if (runs.length > 0) {
2169
+ paraElements.push(
2170
+ new Paragraph({
2171
+ children: runs,
2172
+ spacing: { before: 30, after: 30 }
2173
+ })
2174
+ );
2175
+ }
2176
+ }
2177
+ if (isCard && paraElements.length > 0) {
2178
+ const cardTable = new Table({
2179
+ width: { size: 100, type: WidthType.PERCENTAGE },
2180
+ columnWidths: [9e3],
2181
+ rows: [
2182
+ new TableRow({
2183
+ children: [
2184
+ new TableCell({
2185
+ width: { size: 9e3, type: WidthType.DXA },
2186
+ shading: { fill: "F8FAFC", type: ShadingType.CLEAR },
2187
+ margins: { top: 140, bottom: 140, left: 180, right: 180 },
2188
+ borders: {
2189
+ top: { style: BorderStyle.SINGLE, size: 4, color: "E2E8F0" },
2190
+ bottom: { style: BorderStyle.SINGLE, size: 4, color: "E2E8F0" },
2191
+ left: { style: BorderStyle.SINGLE, size: 8, color: "33CDCF" },
2192
+ right: { style: BorderStyle.SINGLE, size: 4, color: "E2E8F0" }
2193
+ },
2194
+ children: paraElements
2195
+ })
2196
+ ]
2197
+ })
2198
+ ]
2199
+ });
2200
+ docElements.push(cardTable);
2201
+ docElements.push(new Paragraph({ spacing: { after: 120 } }));
2202
+ } else {
2203
+ for (const pe of paraElements) {
2204
+ docElements.push(pe);
2205
+ }
2206
+ }
2207
+ }
2208
+ continue;
2209
+ }
2210
+ }
2211
+ const headerObj = metadata.header || config.header;
2212
+ const footerObj = metadata.footer || config.footer;
2213
+ const headerTabStops = [
2214
+ { type: TabStopType.CENTER, position: 4513 },
2215
+ { type: TabStopType.RIGHT, position: 9026 }
2216
+ ];
2217
+ const docHeader = headerObj ? new Header2({
2218
+ children: [
2219
+ new Paragraph({
2220
+ tabStops: headerTabStops,
2221
+ children: [
2222
+ // Left zone
2223
+ ...headerObj.left ? [
2224
+ new TextRun({
2225
+ text: headerObj.left.replace("{title}", metadata.title || ""),
2226
+ color: "94A3B8",
2227
+ size: 18
2228
+ })
2229
+ ] : [],
2230
+ // Center zone (tab + text)
2231
+ ...headerObj.center ? [
2232
+ new TextRun({ text: " ", color: "94A3B8", size: 18 }),
2233
+ new TextRun({
2234
+ text: headerObj.center.replace("{title}", metadata.title || ""),
2235
+ color: "94A3B8",
2236
+ size: 18
2237
+ })
2238
+ ] : [],
2239
+ // Right zone (tab + text) — skip extra tab if center already used one
2240
+ ...headerObj.right ? [
2241
+ new TextRun({
2242
+ text: headerObj.left || headerObj.center ? " " : "",
2243
+ color: "94A3B8",
2244
+ size: 18
2245
+ }),
2246
+ new TextRun({
2247
+ text: headerObj.right.replace("{title}", metadata.title || ""),
2248
+ color: "94A3B8",
2249
+ size: 18
2250
+ })
2251
+ ] : []
2252
+ ]
2253
+ })
2254
+ ]
2255
+ }) : void 0;
2256
+ const docFooter = footerObj ? new Footer({
2257
+ children: [
2258
+ new Paragraph({
2259
+ tabStops: headerTabStops,
2260
+ children: [
2261
+ // Left zone
2262
+ ...footerObj.left ? [
2263
+ new TextRun({
2264
+ text: footerObj.left.replace("{page}", "").replace("{pages}", "").trim(),
2265
+ color: "94A3B8",
2266
+ size: 18
2267
+ })
2268
+ ] : [],
2269
+ // Right zone: always includes page number if right is configured or footer exists
2270
+ new TextRun({ text: " ", color: "94A3B8", size: 18 }),
2271
+ new TextRun({ text: "Page ", color: "94A3B8", size: 18 }),
2272
+ new TextRun({ children: [PageNumber.CURRENT], color: "94A3B8", size: 18 }),
2273
+ new TextRun({ text: " of ", color: "94A3B8", size: 18 }),
2274
+ new TextRun({ children: [PageNumber.TOTAL_PAGES], color: "94A3B8", size: 18 })
2275
+ ]
2276
+ })
2277
+ ]
2278
+ }) : void 0;
2279
+ const topMargin = parseMarginToTwip(((_d = metadata.margins) == null ? void 0 : _d.top) || ((_e = config.margins) == null ? void 0 : _e.top), 1440);
2280
+ const bottomMargin = parseMarginToTwip(((_f = metadata.margins) == null ? void 0 : _f.bottom) || ((_g = config.margins) == null ? void 0 : _g.bottom), 1440);
2281
+ const leftMargin = parseMarginToTwip(((_h = metadata.margins) == null ? void 0 : _h.left) || ((_i = config.margins) == null ? void 0 : _i.left), 1440);
2282
+ const rightMargin = parseMarginToTwip(((_j = metadata.margins) == null ? void 0 : _j.right) || ((_k = config.margins) == null ? void 0 : _k.right), 1440);
2283
+ const isLandscape = (metadata.orientation || config.orientation) === "landscape";
2284
+ const document = new Document({
2285
+ styles: {
2286
+ default: {
2287
+ document: {
2288
+ run: {
2289
+ font: "Segoe UI",
2290
+ size: 22,
2291
+ // 11pt
2292
+ color: "0F172A"
2293
+ }
2294
+ }
2295
+ }
2296
+ },
2297
+ sections: [
2298
+ {
2299
+ properties: {
2300
+ page: {
2301
+ size: {
2302
+ orientation: isLandscape ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT
2303
+ },
2304
+ margin: {
2305
+ top: topMargin,
2306
+ bottom: bottomMargin,
2307
+ left: leftMargin,
2308
+ right: rightMargin,
2309
+ header: 720,
2310
+ footer: 720
2311
+ }
2312
+ }
2313
+ },
2314
+ headers: docHeader ? { default: docHeader } : void 0,
2315
+ footers: docFooter ? { default: docFooter } : void 0,
2316
+ children: docElements
2317
+ }
2318
+ ]
2319
+ });
2320
+ return await Packer.toBuffer(document);
2321
+ }
2322
+
2323
+ // src/core/engine.ts
2324
+ async function compileMarkdown(inputFilePathOrContent, userConfig = {}, onProgress) {
2325
+ const startTime = Date.now();
2326
+ const config = { ...DEFAULT_CONFIG, ...userConfig };
2327
+ let rawMarkdown = "";
2328
+ let baseDir = process.cwd();
2329
+ let inputFileName = "document.md";
2330
+ let isFilePath = false;
2331
+ if (fs5.existsSync(inputFilePathOrContent)) {
2332
+ isFilePath = true;
2333
+ rawMarkdown = fs5.readFileSync(inputFilePathOrContent, "utf-8");
2334
+ baseDir = path5.dirname(path5.resolve(inputFilePathOrContent));
2335
+ inputFileName = path5.basename(inputFilePathOrContent);
2336
+ } else {
2337
+ rawMarkdown = inputFilePathOrContent;
2338
+ }
2339
+ onProgress == null ? void 0 : onProgress(`Parsing markdown AST: ${inputFileName}...`);
2340
+ const parsedDoc = parseMarkdownDocument(rawMarkdown);
2341
+ const baseName = inputFileName.replace(/\.(md|mdx|markdown)$/i, "");
2342
+ const outputDir = config.outputDir ? path5.isAbsolute(config.outputDir) ? config.outputDir : path5.resolve(process.cwd(), config.outputDir) : baseDir;
2343
+ if (!fs5.existsSync(outputDir)) {
2344
+ fs5.mkdirSync(outputDir, { recursive: true });
2345
+ }
2346
+ const formats = Array.isArray(config.to) ? config.to : [config.to || "docx", "pdf"];
2347
+ const generatedFiles = [];
2348
+ const errors = [];
2349
+ for (const fmt of formats) {
2350
+ try {
2351
+ if (fmt === "docx") {
2352
+ onProgress == null ? void 0 : onProgress(`Generating DOCX document: ${baseName}.docx...`);
2353
+ const docxBuffer = await buildDocxDocument(parsedDoc, config, baseDir);
2354
+ const docxPath = path5.join(outputDir, `${baseName}.docx`);
2355
+ fs5.writeFileSync(docxPath, docxBuffer);
2356
+ generatedFiles.push({
2357
+ format: "docx",
2358
+ filePath: docxPath,
2359
+ fileName: `${baseName}.docx`,
2360
+ sizeBytes: docxBuffer.length
2361
+ });
2362
+ } else if (fmt === "html") {
2363
+ onProgress == null ? void 0 : onProgress(`Generating HTML document: ${baseName}.html...`);
2364
+ const htmlString = await buildHtmlDocument(parsedDoc, config, baseDir);
2365
+ const htmlPath = path5.join(outputDir, `${baseName}.html`);
2366
+ fs5.writeFileSync(htmlPath, htmlString, "utf-8");
2367
+ generatedFiles.push({
2368
+ format: "html",
2369
+ filePath: htmlPath,
2370
+ fileName: `${baseName}.html`,
2371
+ sizeBytes: Buffer.byteLength(htmlString, "utf-8")
2372
+ });
2373
+ } else if (fmt === "pdf") {
2374
+ onProgress == null ? void 0 : onProgress(`Generating PDF document: ${baseName}.pdf...`);
2375
+ const pdfBuffer = await buildPdfDocument(parsedDoc, config, baseDir);
2376
+ const pdfPath = path5.join(outputDir, `${baseName}.pdf`);
2377
+ fs5.writeFileSync(pdfPath, pdfBuffer);
2378
+ generatedFiles.push({
2379
+ format: "pdf",
2380
+ filePath: pdfPath,
2381
+ fileName: `${baseName}.pdf`,
2382
+ sizeBytes: pdfBuffer.length
2383
+ });
2384
+ }
2385
+ } catch (err) {
2386
+ const errMsg = err instanceof Error ? err.message : String(err);
2387
+ errors.push(`Failed to generate ${fmt}: ${errMsg}`);
2388
+ }
2389
+ }
2390
+ const durationMs = Date.now() - startTime;
2391
+ return {
2392
+ inputFile: isFilePath ? inputFilePathOrContent : "inline-string",
2393
+ durationMs,
2394
+ metadata: parsedDoc.metadata,
2395
+ files: generatedFiles,
2396
+ errors
2397
+ };
2398
+ }
2399
+
2400
+ // src/ui/App.tsx
2401
+ import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
2402
+ var App = ({ inputFile, config, onComplete }) => {
2403
+ const [status, setStatus] = useState("Initializing...");
2404
+ const [isCompiling, setIsCompiling] = useState(true);
2405
+ const [result, setResult] = useState(null);
2406
+ useEffect(() => {
2407
+ async function run() {
2408
+ try {
2409
+ const res = await compileMarkdown(inputFile, config, (msg) => setStatus(msg));
2410
+ setResult(res);
2411
+ setIsCompiling(false);
2412
+ onComplete == null ? void 0 : onComplete(res);
2413
+ } catch (err) {
2414
+ const errMsg = err instanceof Error ? err.message : String(err);
2415
+ const errResult = {
2416
+ inputFile,
2417
+ durationMs: 0,
2418
+ metadata: {},
2419
+ files: [],
2420
+ errors: [errMsg]
2421
+ };
2422
+ setResult(errResult);
2423
+ setIsCompiling(false);
2424
+ onComplete == null ? void 0 : onComplete(errResult);
2425
+ }
2426
+ }
2427
+ run();
2428
+ }, [inputFile, config, onComplete]);
2429
+ return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", children: [
2430
+ /* @__PURE__ */ jsx4(Header, { inputFile, theme: config.theme }),
2431
+ /* @__PURE__ */ jsx4(LiveProgress, { status, isCompiling }),
2432
+ /* @__PURE__ */ jsx4(SummaryTable, { result })
2433
+ ] });
2434
+ };
2435
+ export {
2436
+ App
2437
+ };