@masumdev/markforge 0.1.0

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