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,493 @@
1
+ /**
2
+ * @fileoverview Asset resolver for converting image paths to base64 data URIs.
3
+ *
4
+ * This module handles:
5
+ * - Resolving relative paths from the Markdown file location
6
+ * - Resolving paths from a global assets directory (@/ prefix)
7
+ * - Expanding tilde (~) to user home directory (cross-platform)
8
+ * - Reading image files (SVG, PNG, JPG)
9
+ * - Converting to base64 data URIs
10
+ * - Warning on large images (configurable threshold)
11
+ * - Caching resolved assets during a single export
12
+ *
13
+ * @module asset-resolver
14
+ */
15
+
16
+ import fs from "node:fs/promises";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+
20
+ import { IMAGE_FORMATS, IMAGE_SIZE_WARNING_THRESHOLD } from "./types.mjs";
21
+
22
+ // ─────────────────────────────────────────────────────────────────────────────
23
+ // Asset Cache
24
+ // ─────────────────────────────────────────────────────────────────────────────
25
+
26
+ /**
27
+ * Simple in-memory cache for resolved assets.
28
+ * Cleared between exports via createAssetResolver().
29
+ */
30
+ class AssetCache {
31
+ constructor() {
32
+ /** @type {Map<string, import('./types.mjs').ResolvedAsset>} */
33
+ this.cache = new Map();
34
+ }
35
+
36
+ /**
37
+ * Get a cached asset.
38
+ * @param {string} key - Cache key (absolute path)
39
+ * @returns {import('./types.mjs').ResolvedAsset | undefined}
40
+ */
41
+ get(key) {
42
+ return this.cache.get(key);
43
+ }
44
+
45
+ /**
46
+ * Store an asset in cache.
47
+ * @param {string} key - Cache key (absolute path)
48
+ * @param {import('./types.mjs').ResolvedAsset} asset - Resolved asset
49
+ */
50
+ set(key, asset) {
51
+ this.cache.set(key, asset);
52
+ }
53
+
54
+ /**
55
+ * Check if an asset is cached.
56
+ * @param {string} key - Cache key (absolute path)
57
+ * @returns {boolean}
58
+ */
59
+ has(key) {
60
+ return this.cache.has(key);
61
+ }
62
+
63
+ /**
64
+ * Clear the cache.
65
+ */
66
+ clear() {
67
+ this.cache.clear();
68
+ }
69
+
70
+ /**
71
+ * Get cache statistics.
72
+ * @returns {{hits: number, misses: number, size: number}}
73
+ */
74
+ get stats() {
75
+ return {
76
+ size: this.cache.size,
77
+ };
78
+ }
79
+ }
80
+
81
+ // ─────────────────────────────────────────────────────────────────────────────
82
+ // Path Resolution
83
+ // ─────────────────────────────────────────────────────────────────────────────
84
+
85
+ /**
86
+ * Expand tilde (~) to the user's home directory.
87
+ * Works cross-platform (Unix/macOS and Windows).
88
+ *
89
+ * @param {string} filePath - Path that may start with ~
90
+ * @returns {string} Path with ~ expanded to home directory
91
+ *
92
+ * @example
93
+ * // On Unix/macOS with HOME=/Users/john
94
+ * expandTilde("~/docs/logo.svg") // => "/Users/john/docs/logo.svg"
95
+ *
96
+ * // On Windows with USERPROFILE=C:\Users\john
97
+ * expandTilde("~/docs/logo.svg") // => "C:\Users\john\docs\logo.svg"
98
+ */
99
+ export function expandTilde(filePath) {
100
+ if (!filePath || typeof filePath !== "string") {
101
+ return filePath;
102
+ }
103
+
104
+ // Check for tilde at start (~ or ~/ or ~\)
105
+ if (
106
+ filePath === "~" ||
107
+ filePath.startsWith("~/") ||
108
+ filePath.startsWith("~\\")
109
+ ) {
110
+ const homeDir = os.homedir();
111
+ if (filePath === "~") {
112
+ return homeDir;
113
+ }
114
+ // Replace ~ with home directory, preserving the path separator
115
+ return path.join(homeDir, filePath.slice(2));
116
+ }
117
+
118
+ return filePath;
119
+ }
120
+
121
+ /**
122
+ * Resolve an image path relative to a base path, with support for:
123
+ * - Tilde expansion (~) for home directory
124
+ * - Global assets directory (@/ prefix)
125
+ * - Relative paths from base file
126
+ * - Absolute paths
127
+ *
128
+ * @param {string} imagePath - Image path (relative, absolute, ~, or @/)
129
+ * @param {string} basePath - Base path (typically the Markdown file path)
130
+ * @param {string} [assetsDirectory] - Optional global assets directory for @/ paths
131
+ * @returns {string} Absolute path to the image
132
+ *
133
+ * @example
134
+ * // Relative path
135
+ * resolveImagePath("./logo.svg", "/home/user/doc.md")
136
+ * // => "/home/user/logo.svg"
137
+ *
138
+ * // Tilde expansion
139
+ * resolveImagePath("~/assets/logo.svg", "/home/user/doc.md")
140
+ * // => "/home/user/assets/logo.svg" (if home is /home/user)
141
+ *
142
+ * // Global assets with @/ prefix
143
+ * resolveImagePath("@/logo.svg", "/home/user/doc.md", "~/.config/markdown-pdf/assets")
144
+ * // => "/home/user/.config/markdown-pdf/assets/logo.svg"
145
+ */
146
+ export function resolveImagePath(imagePath, basePath, assetsDirectory = null) {
147
+ // Handle @/ prefix for global assets directory
148
+ if (imagePath.startsWith("@/") || imagePath.startsWith("@\\")) {
149
+ if (!assetsDirectory) {
150
+ throw new Error(
151
+ `Cannot resolve "${imagePath}": No assets_directory configured. ` +
152
+ `Set "assets_directory" in your settings to use @/ paths.`,
153
+ );
154
+ }
155
+ // Expand tilde in assets directory if present
156
+ const expandedAssetsDir = expandTilde(assetsDirectory);
157
+ const relativePath = imagePath.slice(2); // Remove @/ or @\
158
+ return path.resolve(expandedAssetsDir, relativePath);
159
+ }
160
+
161
+ // Expand tilde if present
162
+ const expandedPath = expandTilde(imagePath);
163
+
164
+ // If already absolute (or was made absolute by tilde expansion), return as-is
165
+ if (path.isAbsolute(expandedPath)) {
166
+ return expandedPath;
167
+ }
168
+
169
+ // Get the directory of the base file
170
+ const baseDir = path.dirname(basePath);
171
+
172
+ // Resolve relative to base directory
173
+ return path.resolve(baseDir, expandedPath);
174
+ }
175
+
176
+ /**
177
+ * Get the MIME type for an image file based on extension.
178
+ *
179
+ * @param {string} filePath - Path to the image file
180
+ * @returns {string | null} MIME type or null if unsupported
181
+ */
182
+ export function getMimeType(filePath) {
183
+ const ext = path.extname(filePath).toLowerCase();
184
+ return IMAGE_FORMATS[ext] || null;
185
+ }
186
+
187
+ /**
188
+ * Check if a file path has a supported image extension.
189
+ *
190
+ * @param {string} filePath - Path to check
191
+ * @returns {boolean}
192
+ */
193
+ export function isSupportedImage(filePath) {
194
+ return getMimeType(filePath) !== null;
195
+ }
196
+
197
+ // ─────────────────────────────────────────────────────────────────────────────
198
+ // Asset Resolution
199
+ // ─────────────────────────────────────────────────────────────────────────────
200
+
201
+ /**
202
+ * Read and encode an image file as a base64 data URI.
203
+ *
204
+ * @param {string} absolutePath - Absolute path to the image file
205
+ * @param {number} [warningThreshold=IMAGE_SIZE_WARNING_THRESHOLD] - Size threshold for warnings
206
+ * @returns {Promise<import('./types.mjs').ResolvedAsset>}
207
+ * @throws {Error} If file cannot be read or format is unsupported
208
+ */
209
+ export async function resolveAsset(
210
+ absolutePath,
211
+ warningThreshold = IMAGE_SIZE_WARNING_THRESHOLD,
212
+ ) {
213
+ // Check if file exists
214
+ try {
215
+ await fs.access(absolutePath);
216
+ } catch {
217
+ throw new Error(`Image file not found: ${absolutePath}`);
218
+ }
219
+
220
+ // Get MIME type
221
+ const mimeType = getMimeType(absolutePath);
222
+ if (!mimeType) {
223
+ const ext = path.extname(absolutePath) || "(no extension)";
224
+ throw new Error(
225
+ `Unsupported image format: ${ext}. Supported formats: ${Object.keys(IMAGE_FORMATS).join(", ")}`,
226
+ );
227
+ }
228
+
229
+ // Read file
230
+ const buffer = await fs.readFile(absolutePath);
231
+ const size = buffer.length;
232
+ const oversized = size > warningThreshold;
233
+
234
+ // For SVG files, we can use the raw content with proper encoding
235
+ // For binary formats (PNG, JPG), we use base64
236
+ let dataUri;
237
+
238
+ if (mimeType === "image/svg+xml") {
239
+ // SVG: Use UTF-8 encoding with URL-safe base64 or direct embedding
240
+ // Base64 is safer for complex SVGs with special characters
241
+ const base64 = buffer.toString("base64");
242
+ dataUri = `data:${mimeType};base64,${base64}`;
243
+ } else {
244
+ // Binary formats: Use base64
245
+ const base64 = buffer.toString("base64");
246
+ dataUri = `data:${mimeType};base64,${base64}`;
247
+ }
248
+
249
+ return {
250
+ dataUri,
251
+ mimeType,
252
+ size,
253
+ oversized,
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Resolve an image path to a data URI, with caching.
259
+ *
260
+ * @param {string} imagePath - Image path (relative or absolute)
261
+ * @param {string} basePath - Base path for resolving relative paths
262
+ * @param {AssetCache} cache - Asset cache instance
263
+ * @param {number} [warningThreshold] - Size threshold for warnings
264
+ * @param {string} [assetsDirectory] - Optional global assets directory for @/ paths
265
+ * @returns {Promise<{asset: import('./types.mjs').ResolvedAsset, absolutePath: string}>}
266
+ */
267
+ async function resolveWithCache(
268
+ imagePath,
269
+ basePath,
270
+ cache,
271
+ warningThreshold,
272
+ assetsDirectory,
273
+ ) {
274
+ const absolutePath = resolveImagePath(imagePath, basePath, assetsDirectory);
275
+
276
+ // Check cache
277
+ if (cache.has(absolutePath)) {
278
+ return {
279
+ asset: cache.get(absolutePath),
280
+ absolutePath,
281
+ };
282
+ }
283
+
284
+ // Resolve and cache
285
+ const asset = await resolveAsset(absolutePath, warningThreshold);
286
+ cache.set(absolutePath, asset);
287
+
288
+ return { asset, absolutePath };
289
+ }
290
+
291
+ // ─────────────────────────────────────────────────────────────────────────────
292
+ // Asset Resolver Factory
293
+ // ─────────────────────────────────────────────────────────────────────────────
294
+
295
+ /**
296
+ * @typedef {Object} AssetResolverOptions
297
+ * @property {string} basePath - Base path for resolving relative paths (typically the Markdown file)
298
+ * @property {string} [assetsDirectory] - Global assets directory for @/ paths (supports ~ expansion)
299
+ * @property {number} [warningThreshold=IMAGE_SIZE_WARNING_THRESHOLD] - Size threshold for warnings (bytes)
300
+ * @property {(message: string, path: string, size: number) => void} [onWarning] - Warning callback
301
+ */
302
+
303
+ /**
304
+ * @typedef {Object} AssetResolver
305
+ * @property {(imagePath: string) => Promise<string>} resolve - Resolve image path to data URI
306
+ * @property {(imagePath: string) => Promise<import('./types.mjs').ResolvedAsset>} resolveWithMeta - Resolve with metadata
307
+ * @property {() => string[]} getWarnings - Get all warnings generated during resolution
308
+ * @property {() => void} clearCache - Clear the asset cache
309
+ * @property {() => {resolved: number, warnings: string[]}} getStats - Get resolution statistics
310
+ */
311
+
312
+ /**
313
+ * Create an asset resolver instance for a single export operation.
314
+ *
315
+ * The resolver caches resolved assets and collects warnings for large files.
316
+ * Create a new resolver for each export to ensure a clean cache.
317
+ *
318
+ * @param {AssetResolverOptions} options - Resolver options
319
+ * @returns {AssetResolver}
320
+ *
321
+ * @example
322
+ * const resolver = createAssetResolver({
323
+ * basePath: '/path/to/document.md',
324
+ * warningThreshold: 500 * 1024, // 500KB
325
+ * });
326
+ *
327
+ * const dataUri = await resolver.resolve('./images/logo.svg');
328
+ */
329
+ export function createAssetResolver(options) {
330
+ const {
331
+ basePath,
332
+ assetsDirectory = null,
333
+ warningThreshold = IMAGE_SIZE_WARNING_THRESHOLD,
334
+ onWarning,
335
+ } = options;
336
+
337
+ const cache = new AssetCache();
338
+ const warnings = [];
339
+ let resolvedCount = 0;
340
+
341
+ // Expand tilde in assetsDirectory once at creation time
342
+ const expandedAssetsDirectory = assetsDirectory
343
+ ? expandTilde(assetsDirectory)
344
+ : null;
345
+
346
+ /**
347
+ * Format file size for display.
348
+ * @param {number} bytes
349
+ * @returns {string}
350
+ */
351
+ function formatSize(bytes) {
352
+ if (bytes < 1024) return `${bytes} B`;
353
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
354
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
355
+ }
356
+
357
+ /**
358
+ * Resolve an image path to a data URI string.
359
+ *
360
+ * @param {string} imagePath - Image path (relative or absolute)
361
+ * @returns {Promise<string>} Base64 data URI
362
+ */
363
+ async function resolve(imagePath) {
364
+ const result = await resolveWithMeta(imagePath);
365
+ return result.dataUri;
366
+ }
367
+
368
+ /**
369
+ * Resolve an image path with full metadata.
370
+ *
371
+ * @param {string} imagePath - Image path (relative or absolute)
372
+ * @returns {Promise<import('./types.mjs').ResolvedAsset>}
373
+ */
374
+ async function resolveWithMeta(imagePath) {
375
+ const { asset, absolutePath } = await resolveWithCache(
376
+ imagePath,
377
+ basePath,
378
+ cache,
379
+ warningThreshold,
380
+ expandedAssetsDirectory,
381
+ );
382
+
383
+ resolvedCount++;
384
+
385
+ // Generate warning for oversized assets
386
+ if (asset.oversized) {
387
+ const warningMessage = `Large image (${formatSize(asset.size)}): ${imagePath}. Consider optimizing for better performance.`;
388
+ warnings.push(warningMessage);
389
+
390
+ if (onWarning) {
391
+ onWarning(warningMessage, absolutePath, asset.size);
392
+ }
393
+ }
394
+
395
+ return asset;
396
+ }
397
+
398
+ /**
399
+ * Get all warnings generated during resolution.
400
+ * @returns {string[]}
401
+ */
402
+ function getWarnings() {
403
+ return [...warnings];
404
+ }
405
+
406
+ /**
407
+ * Clear the asset cache.
408
+ */
409
+ function clearCache() {
410
+ cache.clear();
411
+ }
412
+
413
+ /**
414
+ * Get resolution statistics.
415
+ * @returns {{resolved: number, cached: number, warnings: string[]}}
416
+ */
417
+ function getStats() {
418
+ return {
419
+ resolved: resolvedCount,
420
+ cached: cache.stats.size,
421
+ warnings: [...warnings],
422
+ };
423
+ }
424
+
425
+ return {
426
+ resolve,
427
+ resolveWithMeta,
428
+ getWarnings,
429
+ clearCache,
430
+ getStats,
431
+ };
432
+ }
433
+
434
+ // ─────────────────────────────────────────────────────────────────────────────
435
+ // Utility Functions
436
+ // ─────────────────────────────────────────────────────────────────────────────
437
+
438
+ /**
439
+ * Check if a string is already a data URI.
440
+ *
441
+ * @param {string} value - String to check
442
+ * @returns {boolean}
443
+ */
444
+ export function isDataUri(value) {
445
+ return typeof value === "string" && value.startsWith("data:");
446
+ }
447
+
448
+ /**
449
+ * Extract the MIME type from a data URI.
450
+ *
451
+ * @param {string} dataUri - Data URI string
452
+ * @returns {string | null} MIME type or null if invalid
453
+ */
454
+ export function getMimeTypeFromDataUri(dataUri) {
455
+ if (!isDataUri(dataUri)) return null;
456
+
457
+ const match = dataUri.match(/^data:([^;,]+)/);
458
+ return match ? match[1] : null;
459
+ }
460
+
461
+ /**
462
+ * Validate that a data URI is a supported image format.
463
+ *
464
+ * @param {string} dataUri - Data URI to validate
465
+ * @returns {boolean}
466
+ */
467
+ export function isValidImageDataUri(dataUri) {
468
+ const mimeType = getMimeTypeFromDataUri(dataUri);
469
+ if (!mimeType) return false;
470
+
471
+ return Object.values(IMAGE_FORMATS).includes(mimeType);
472
+ }
473
+
474
+ /**
475
+ * Estimate the decoded size of a base64 data URI.
476
+ *
477
+ * @param {string} dataUri - Data URI string
478
+ * @returns {number} Estimated size in bytes
479
+ */
480
+ export function estimateDataUriSize(dataUri) {
481
+ if (!isDataUri(dataUri)) return 0;
482
+
483
+ // Find the base64 content after the comma
484
+ const commaIndex = dataUri.indexOf(",");
485
+ if (commaIndex === -1) return 0;
486
+
487
+ const base64Content = dataUri.slice(commaIndex + 1);
488
+
489
+ // Base64 encoding increases size by ~33%, so decoded size is ~75% of encoded
490
+ // Also account for padding characters
491
+ const padding = (base64Content.match(/=+$/) || [""])[0].length;
492
+ return Math.floor((base64Content.length * 3) / 4) - padding;
493
+ }