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