markdown-pdf-export 0.0.0-stage → 2.0.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.
@@ -0,0 +1,595 @@
1
+ /**
2
+ * @fileoverview Front matter parser for Markdown documents.
3
+ *
4
+ * This module handles:
5
+ * - Extracting YAML front matter from Markdown content
6
+ * - Parsing the `pdf:` configuration block
7
+ * - Extracting document metadata (title, author, date)
8
+ * - Collecting custom variables for placeholder resolution
9
+ * - Validating the extracted configuration
10
+ *
11
+ * @module frontmatter-parser
12
+ */
13
+
14
+ // ── Lazy-loaded npm dependency ────────────────────────────────────────────────
15
+ // Loaded dynamically so the MCP handshake can succeed before `npm install` runs.
16
+ let parseYaml = null;
17
+
18
+ /**
19
+ * Ensure the `yaml` package is loaded. Must be called (and awaited) before
20
+ * any function in this module that depends on YAML parsing.
21
+ */
22
+ export async function ensureYamlLoaded() {
23
+ if (!parseYaml) {
24
+ parseYaml = (await import("yaml")).parse;
25
+ }
26
+ }
27
+
28
+ import { validateFrontMatterConfig } from "./schema-validator.mjs";
29
+
30
+ // ─────────────────────────────────────────────────────────────────────────────
31
+ // Constants
32
+ // ─────────────────────────────────────────────────────────────────────────────
33
+
34
+ /**
35
+ * Front matter delimiter.
36
+ * @type {string}
37
+ */
38
+ const FRONTMATTER_DELIMITER = "---";
39
+
40
+ /**
41
+ * Key for PDF configuration in front matter.
42
+ * @type {string}
43
+ */
44
+ const PDF_CONFIG_KEY = "pdf";
45
+
46
+ /**
47
+ * Known front matter fields that have special handling.
48
+ * @type {Set<string>}
49
+ */
50
+ const KNOWN_FIELDS = new Set(["title", "author", "date", PDF_CONFIG_KEY]);
51
+
52
+ // ─────────────────────────────────────────────────────────────────────────────
53
+ // Types
54
+ // ─────────────────────────────────────────────────────────────────────────────
55
+
56
+ /**
57
+ * @typedef {Object} ParsedFrontMatter
58
+ * @property {string|null} title - Document title from front matter
59
+ * @property {string|null} author - Document author
60
+ * @property {string|null} date - Document date
61
+ * @property {import('./types.mjs').FrontMatterPdfConfig|null} pdfConfig - PDF configuration
62
+ * @property {Object.<string, any>} customVariables - Custom variables for placeholders
63
+ * @property {Object.<string, any>} raw - Raw parsed YAML object
64
+ */
65
+
66
+ /**
67
+ * @typedef {Object} SplitResult
68
+ * @property {string} frontMatter - Raw YAML front matter string (without delimiters)
69
+ * @property {string} body - Markdown body (after front matter)
70
+ * @property {boolean} hasFrontMatter - Whether front matter was found
71
+ */
72
+
73
+ /**
74
+ * @typedef {Object} ParseResult
75
+ * @property {ParsedFrontMatter} data - Parsed front matter data
76
+ * @property {string} body - Markdown body (after front matter)
77
+ * @property {import('./types.mjs').ValidationResult} validation - Validation result
78
+ * @property {Error|null} parseError - YAML parse error, if any
79
+ */
80
+
81
+ // ─────────────────────────────────────────────────────────────────────────────
82
+ // Front Matter Extraction
83
+ // ─────────────────────────────────────────────────────────────────────────────
84
+
85
+ /**
86
+ * Check if content starts with front matter delimiter.
87
+ *
88
+ * @param {string} content - Markdown content
89
+ * @returns {boolean}
90
+ */
91
+ export function hasFrontMatter(content) {
92
+ if (typeof content !== "string") {
93
+ return false;
94
+ }
95
+
96
+ return (
97
+ content.startsWith(`${FRONTMATTER_DELIMITER}\n`) ||
98
+ content.startsWith(`${FRONTMATTER_DELIMITER}\r\n`)
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Split content into front matter and body.
104
+ *
105
+ * @param {string} content - Full Markdown content
106
+ * @returns {SplitResult}
107
+ */
108
+ export function splitFrontMatter(content) {
109
+ if (typeof content !== "string" || !hasFrontMatter(content)) {
110
+ return {
111
+ frontMatter: "",
112
+ body: content || "",
113
+ hasFrontMatter: false,
114
+ };
115
+ }
116
+
117
+ // Find the closing delimiter
118
+ // Look for \n---\n or \r\n---\r\n
119
+ const startIndex = content.indexOf("\n") + 1; // After first ---\n
120
+
121
+ // Find the closing delimiter
122
+ let endIndex = content.indexOf(`\n${FRONTMATTER_DELIMITER}\n`, startIndex);
123
+ let delimiterLength = 5; // \n---\n
124
+
125
+ if (endIndex === -1) {
126
+ // Try Windows line endings
127
+ endIndex = content.indexOf(`\r\n${FRONTMATTER_DELIMITER}\r\n`, startIndex);
128
+ delimiterLength = 7; // \r\n---\r\n
129
+ }
130
+
131
+ if (endIndex === -1) {
132
+ // Try end of file (no newline after closing ---)
133
+ endIndex = content.indexOf(`\n${FRONTMATTER_DELIMITER}`, startIndex);
134
+ if (endIndex !== -1) {
135
+ const afterDelim = content.substring(endIndex + 4);
136
+ if (afterDelim === "" || afterDelim === "\n" || afterDelim === "\r\n") {
137
+ delimiterLength = 4 + afterDelim.length;
138
+ } else {
139
+ endIndex = -1; // Not a valid closing delimiter
140
+ }
141
+ }
142
+ }
143
+
144
+ if (endIndex === -1) {
145
+ // No closing delimiter found - treat as no front matter
146
+ return {
147
+ frontMatter: "",
148
+ body: content,
149
+ hasFrontMatter: false,
150
+ };
151
+ }
152
+
153
+ const frontMatter = content.substring(startIndex, endIndex);
154
+ const body = content.substring(endIndex + delimiterLength);
155
+
156
+ return {
157
+ frontMatter,
158
+ body,
159
+ hasFrontMatter: true,
160
+ };
161
+ }
162
+
163
+ // ─────────────────────────────────────────────────────────────────────────────
164
+ // YAML Parsing
165
+ // ─────────────────────────────────────────────────────────────────────────────
166
+
167
+ /**
168
+ * Parse YAML front matter string.
169
+ *
170
+ * @param {string} yamlString - YAML content
171
+ * @returns {{data: Object|null, error: Error|null}}
172
+ */
173
+ export function parseYamlFrontMatter(yamlString) {
174
+ if (!yamlString || typeof yamlString !== "string" || !yamlString.trim()) {
175
+ return { data: null, error: null };
176
+ }
177
+
178
+ try {
179
+ const data = parseYaml(yamlString);
180
+
181
+ // YAML can parse to non-objects (e.g., just a string)
182
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
183
+ return { data: null, error: null };
184
+ }
185
+
186
+ return { data, error: null };
187
+ } catch (error) {
188
+ return { data: null, error };
189
+ }
190
+ }
191
+
192
+ // ─────────────────────────────────────────────────────────────────────────────
193
+ // Data Extraction
194
+ // ─────────────────────────────────────────────────────────────────────────────
195
+
196
+ /**
197
+ * Extract title from front matter or find first H1 in body.
198
+ *
199
+ * @param {Object|null} frontMatter - Parsed front matter
200
+ * @param {string} body - Markdown body
201
+ * @param {string} [filename] - Filename as fallback
202
+ * @returns {string|null}
203
+ */
204
+ export function extractTitle(frontMatter, body, filename = null) {
205
+ // Priority 1: Front matter title
206
+ if (frontMatter?.title) {
207
+ const title = String(frontMatter.title).trim();
208
+ // Remove quotes if present
209
+ return title.replace(/^['"]|['"]$/g, "");
210
+ }
211
+
212
+ // Priority 2: First H1 in body
213
+ if (body) {
214
+ const h1Match = body.match(/^#\s+(.+)$/m);
215
+ if (h1Match) {
216
+ return h1Match[1].trim();
217
+ }
218
+ }
219
+
220
+ // Priority 3: Filename stem
221
+ if (filename) {
222
+ const stem = filename.replace(/\.[^.]+$/, "");
223
+ return stem;
224
+ }
225
+
226
+ return null;
227
+ }
228
+
229
+ /**
230
+ * Extract author from front matter.
231
+ *
232
+ * @param {Object|null} frontMatter - Parsed front matter
233
+ * @returns {string|null}
234
+ */
235
+ export function extractAuthor(frontMatter) {
236
+ if (!frontMatter?.author) {
237
+ return null;
238
+ }
239
+
240
+ // Handle array of authors
241
+ if (Array.isArray(frontMatter.author)) {
242
+ return frontMatter.author.map(String).join(", ");
243
+ }
244
+
245
+ return String(frontMatter.author).trim();
246
+ }
247
+
248
+ /**
249
+ * Extract date from front matter.
250
+ *
251
+ * @param {Object|null} frontMatter - Parsed front matter
252
+ * @returns {string|null}
253
+ */
254
+ export function extractDate(frontMatter) {
255
+ if (!frontMatter?.date) {
256
+ return null;
257
+ }
258
+
259
+ // Handle Date object
260
+ if (frontMatter.date instanceof Date) {
261
+ return frontMatter.date.toISOString().slice(0, 10);
262
+ }
263
+
264
+ return String(frontMatter.date).trim();
265
+ }
266
+
267
+ /**
268
+ * Extract PDF configuration from front matter.
269
+ *
270
+ * @param {Object|null} frontMatter - Parsed front matter
271
+ * @returns {import('./types.mjs').FrontMatterPdfConfig|null}
272
+ */
273
+ export function extractPdfConfig(frontMatter) {
274
+ if (!frontMatter || !frontMatter[PDF_CONFIG_KEY]) {
275
+ return null;
276
+ }
277
+
278
+ const config = frontMatter[PDF_CONFIG_KEY];
279
+
280
+ // Must be an object
281
+ if (typeof config !== "object" || Array.isArray(config) || config === null) {
282
+ return null;
283
+ }
284
+
285
+ return config;
286
+ }
287
+
288
+ /**
289
+ * Extract custom variables from front matter.
290
+ * These are any fields not in the known fields list.
291
+ *
292
+ * @param {Object|null} frontMatter - Parsed front matter
293
+ * @returns {Object.<string, any>}
294
+ */
295
+ export function extractCustomVariables(frontMatter) {
296
+ if (!frontMatter || typeof frontMatter !== "object") {
297
+ return {};
298
+ }
299
+
300
+ const variables = {};
301
+
302
+ for (const [key, value] of Object.entries(frontMatter)) {
303
+ if (!KNOWN_FIELDS.has(key) && value !== null && value !== undefined) {
304
+ // Convert to string for simple values, keep objects/arrays as-is
305
+ if (typeof value === "object") {
306
+ variables[key.toLowerCase()] = value;
307
+ } else {
308
+ variables[key.toLowerCase()] = String(value);
309
+ }
310
+ }
311
+ }
312
+
313
+ return variables;
314
+ }
315
+
316
+ // ─────────────────────────────────────────────────────────────────────────────
317
+ // Main Parser
318
+ // ─────────────────────────────────────────────────────────────────────────────
319
+
320
+ /**
321
+ * Parse front matter from Markdown content.
322
+ *
323
+ * @param {string} content - Full Markdown content
324
+ * @param {Object} [options] - Parse options
325
+ * @param {string} [options.filename] - Filename for title fallback
326
+ * @param {boolean} [options.validate=true] - Whether to validate PDF config
327
+ * @returns {ParseResult}
328
+ *
329
+ * @example
330
+ * const content = `---
331
+ * title: My Document
332
+ * author: Jane Doe
333
+ * pdf:
334
+ * header:
335
+ * left_image: ./logo.svg
336
+ * ---
337
+ *
338
+ * # Content here
339
+ * `;
340
+ *
341
+ * const result = parseFrontMatter(content, { filename: 'doc.md' });
342
+ * console.log(result.data.title); // "My Document"
343
+ * console.log(result.data.pdfConfig); // { header: { left_image: './logo.svg' } }
344
+ */
345
+ export function parseFrontMatter(content, options = {}) {
346
+ const { filename, validate = true } = options;
347
+
348
+ // Default result
349
+ const emptyResult = {
350
+ data: {
351
+ title: filename ? filename.replace(/\.[^.]+$/, "") : null,
352
+ author: null,
353
+ date: null,
354
+ pdfConfig: null,
355
+ customVariables: {},
356
+ raw: {},
357
+ },
358
+ body: content || "",
359
+ validation: { valid: true, errors: [], warnings: [] },
360
+ parseError: null,
361
+ };
362
+
363
+ // Handle non-string input
364
+ if (typeof content !== "string") {
365
+ return emptyResult;
366
+ }
367
+
368
+ // Split front matter from body
369
+ const {
370
+ frontMatter,
371
+ body,
372
+ hasFrontMatter: found,
373
+ } = splitFrontMatter(content);
374
+
375
+ if (!found) {
376
+ // Try to extract title from H1
377
+ emptyResult.data.title = extractTitle(null, content, filename);
378
+ return emptyResult;
379
+ }
380
+
381
+ // Parse YAML
382
+ const { data: raw, error: parseError } = parseYamlFrontMatter(frontMatter);
383
+
384
+ if (parseError) {
385
+ return {
386
+ data: {
387
+ title: filename ? filename.replace(/\.[^.]+$/, "") : null,
388
+ author: null,
389
+ date: null,
390
+ pdfConfig: null,
391
+ customVariables: {},
392
+ raw: {},
393
+ },
394
+ body,
395
+ validation: { valid: true, errors: [], warnings: [] },
396
+ parseError,
397
+ };
398
+ }
399
+
400
+ if (!raw) {
401
+ return {
402
+ ...emptyResult,
403
+ body,
404
+ data: {
405
+ ...emptyResult.data,
406
+ title: extractTitle(null, body, filename),
407
+ },
408
+ };
409
+ }
410
+
411
+ // Extract data
412
+ const pdfConfig = extractPdfConfig(raw);
413
+
414
+ // Validate PDF config if requested
415
+ let validation = { valid: true, errors: [], warnings: [] };
416
+ if (validate && pdfConfig) {
417
+ validation = validateFrontMatterConfig(pdfConfig);
418
+ }
419
+
420
+ return {
421
+ data: {
422
+ title: extractTitle(raw, body, filename),
423
+ author: extractAuthor(raw),
424
+ date: extractDate(raw),
425
+ pdfConfig,
426
+ customVariables: extractCustomVariables(raw),
427
+ raw,
428
+ },
429
+ body,
430
+ validation,
431
+ parseError: null,
432
+ };
433
+ }
434
+
435
+ // ─────────────────────────────────────────────────────────────────────────────
436
+ // Convenience Functions
437
+ // ─────────────────────────────────────────────────────────────────────────────
438
+
439
+ /**
440
+ * Extract only the PDF configuration from content.
441
+ * Useful when you only need the config and don't need other metadata.
442
+ *
443
+ * @param {string} content - Markdown content
444
+ * @returns {import('./types.mjs').FrontMatterPdfConfig|null}
445
+ */
446
+ export function extractPdfConfigFromContent(content) {
447
+ const { data } = parseFrontMatter(content, { validate: false });
448
+ return data.pdfConfig;
449
+ }
450
+
451
+ /**
452
+ * Check if content has PDF configuration in front matter.
453
+ *
454
+ * @param {string} content - Markdown content
455
+ * @returns {boolean}
456
+ */
457
+ export function hasPdfConfig(content) {
458
+ return extractPdfConfigFromContent(content) !== null;
459
+ }
460
+
461
+ /**
462
+ * Get just the body content without front matter.
463
+ *
464
+ * @param {string} content - Full Markdown content
465
+ * @returns {string}
466
+ */
467
+ export function getBody(content) {
468
+ const { body } = splitFrontMatter(content);
469
+ return body;
470
+ }
471
+
472
+ /**
473
+ * Create front matter YAML string from an object.
474
+ * Useful for generating or modifying front matter.
475
+ *
476
+ * @param {Object} data - Data to convert to YAML
477
+ * @returns {string} YAML string with delimiters
478
+ */
479
+ export function createFrontMatter(data) {
480
+ if (!data || typeof data !== "object" || Object.keys(data).length === 0) {
481
+ return "";
482
+ }
483
+
484
+ // Import stringify from yaml - we'll construct manually for simplicity
485
+ const lines = ["---"];
486
+
487
+ for (const [key, value] of Object.entries(data)) {
488
+ if (value === null || value === undefined) {
489
+ continue;
490
+ }
491
+
492
+ if (typeof value === "string") {
493
+ // Quote strings that might be ambiguous
494
+ if (
495
+ value.includes(":") ||
496
+ value.includes("#") ||
497
+ value.startsWith("'") ||
498
+ value.startsWith('"')
499
+ ) {
500
+ lines.push(`${key}: "${value.replace(/"/g, '\\"')}"`);
501
+ } else {
502
+ lines.push(`${key}: ${value}`);
503
+ }
504
+ } else if (typeof value === "number" || typeof value === "boolean") {
505
+ lines.push(`${key}: ${value}`);
506
+ } else if (typeof value === "object") {
507
+ // For objects, we'd need proper YAML serialization
508
+ // For now, just note that this is a simplified implementation
509
+ lines.push(`${key}:`);
510
+ lines.push(` # Complex object - use yaml.stringify for full support`);
511
+ }
512
+ }
513
+
514
+ lines.push("---");
515
+ return lines.join("\n") + "\n";
516
+ }
517
+
518
+ // ─────────────────────────────────────────────────────────────────────────────
519
+ // Parser Factory
520
+ // ─────────────────────────────────────────────────────────────────────────────
521
+
522
+ /**
523
+ * @typedef {Object} FrontMatterParserOptions
524
+ * @property {boolean} [validate=true] - Whether to validate PDF config
525
+ * @property {boolean} [extractH1=true] - Whether to extract title from H1
526
+ */
527
+
528
+ /**
529
+ * @typedef {Object} FrontMatterParser
530
+ * @property {(content: string, filename?: string) => ParseResult} parse - Parse content
531
+ * @property {(content: string) => boolean} hasFrontMatter - Check for front matter
532
+ * @property {(content: string) => boolean} hasPdfConfig - Check for PDF config
533
+ * @property {(content: string) => string} getBody - Get body without front matter
534
+ */
535
+
536
+ /**
537
+ * Create a front matter parser with preset options.
538
+ *
539
+ * @param {FrontMatterParserOptions} [options={}] - Parser options
540
+ * @returns {FrontMatterParser}
541
+ *
542
+ * @example
543
+ * const parser = createFrontMatterParser({ validate: true });
544
+ *
545
+ * const result = parser.parse(markdownContent, 'document.md');
546
+ * if (result.validation.valid) {
547
+ * console.log('Config is valid:', result.data.pdfConfig);
548
+ * }
549
+ */
550
+ export function createFrontMatterParser(options = {}) {
551
+ const { validate = true } = options;
552
+
553
+ return {
554
+ /**
555
+ * Parse front matter from content.
556
+ *
557
+ * @param {string} content - Markdown content
558
+ * @param {string} [filename] - Filename for title fallback
559
+ * @returns {ParseResult}
560
+ */
561
+ parse(content, filename) {
562
+ return parseFrontMatter(content, { filename, validate });
563
+ },
564
+
565
+ /**
566
+ * Check if content has front matter.
567
+ *
568
+ * @param {string} content - Markdown content
569
+ * @returns {boolean}
570
+ */
571
+ hasFrontMatter(content) {
572
+ return hasFrontMatter(content);
573
+ },
574
+
575
+ /**
576
+ * Check if content has PDF configuration.
577
+ *
578
+ * @param {string} content - Markdown content
579
+ * @returns {boolean}
580
+ */
581
+ hasPdfConfig(content) {
582
+ return hasPdfConfig(content);
583
+ },
584
+
585
+ /**
586
+ * Get body without front matter.
587
+ *
588
+ * @param {string} content - Markdown content
589
+ * @returns {string}
590
+ */
591
+ getBody(content) {
592
+ return getBody(content);
593
+ },
594
+ };
595
+ }