From 9960f63650f429a4268f57451dc9635d5d7fc071 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Tue, 9 Sep 2025 15:58:24 +0200 Subject: [PATCH] refactor: extract EmbedProcessor and fix WebP conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extract embed processing logic from MarkdownPreprocessor to new EmbedProcessor module - Fix WebP image conversion that was broken during refactoring: - Update ImageMagick command from deprecated 'convert' to modern 'magick' - Fix field name mismatch: use 'sizeOrAlt' instead of 'alt' in plugin/EmbedProcessor - Use PathResolver for proper ImageMagick executable path resolution - Restore comprehensive embed processing including images, PDFs, and files - Add proper error handling and fallback for WebP conversion failures - Maintain size parameter parsing (e.g., "400x300") vs alt text differentiation Resolves WebP conversion issues and completes Step 2.3 of refactoring plan. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/converters/MarkdownPreprocessor.ts | 177 +------------ .../preprocessors/EmbedProcessor.ts | 245 ++++++++++++++++++ src/plugin/EmbedProcessor.ts | 80 +++++- 3 files changed, 329 insertions(+), 173 deletions(-) create mode 100644 src/converters/preprocessors/EmbedProcessor.ts diff --git a/src/converters/MarkdownPreprocessor.ts b/src/converters/MarkdownPreprocessor.ts index 64daaae..1894c83 100644 --- a/src/converters/MarkdownPreprocessor.ts +++ b/src/converters/MarkdownPreprocessor.ts @@ -5,6 +5,7 @@ import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor'; import { WikilinkProcessor, WikilinkConfig, WikilinkProcessorConfig } from './preprocessors/WikilinkProcessor'; +import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProcessor'; export interface PreprocessorOptions { /** Include metadata extraction in processing */ @@ -77,11 +78,10 @@ export class MarkdownPreprocessor { private noteTitle?: string; private frontmatterProcessor: FrontmatterProcessor; private wikilinkProcessor: WikilinkProcessor; + private embedProcessor: EmbedProcessor; // Regex patterns for Obsidian syntax private readonly WIKILINK_PATTERN = /\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g; - private readonly EMBED_PATTERN = /!\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g; - private readonly EMBED_SIZE_PATTERN = /(\d+)(?:x(\d+))?/; private readonly CALLOUT_PATTERN = /^>\s*\[!([\w-]+)\]([+-]?)\s*(.*)$/gm; private readonly MULTI_LINE_CALLOUT_PATTERN = /^(>\s*\[!([\w-]+)\]([+-]?)\s*(.*(?:\n(?:>.*|$))*?))/gm; private readonly TAG_PATTERN = /#(?:[^\s#]+)/g; @@ -105,6 +105,11 @@ export class MarkdownPreprocessor { baseUrl: this.options.baseUrl }; this.wikilinkProcessor = new WikilinkProcessor(wikilinkProcessorConfig); + + const embedProcessorConfig: EmbedProcessorConfig = { + wikilinkProcessor: this.wikilinkProcessor + }; + this.embedProcessor = new EmbedProcessor(embedProcessorConfig); } /** @@ -146,7 +151,7 @@ export class MarkdownPreprocessor { result.content = this.filterUnnecessaryLinks(result.content, result); // Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added) - result.content = this.parseEmbeds(result.content, result); + result.content = this.embedProcessor.processEmbeds(result.content, result); // Step 6: Convert wikilinks (after embeds are processed) result.content = this.wikilinkProcessor.processWikilinks(result.content, result); @@ -211,167 +216,6 @@ export class MarkdownPreprocessor { - /** - * Convert embed syntax to standard markdown references - */ - private parseEmbeds(content: string, result: PreprocessingResult): string { - return content.replace(this.EMBED_PATTERN, (match, embedPath, sizeOrAlt) => { - try { - const cleanPath = embedPath.trim(); - - if (!cleanPath) { - result.warnings.push(`Empty embed path found: ${match}`); - return match; - } - - // Parse file extension and path - const fileExtension = this.getFileExtension(cleanPath); - const fileType = this.determineFileType(fileExtension); - - // Handle different file types - switch (fileType) { - case 'image': - return this.processImageEmbed(cleanPath, sizeOrAlt, result); - - case 'pdf': - return this.processPdfEmbed(cleanPath, sizeOrAlt, result); - - case 'file': - return this.processFileEmbed(cleanPath, sizeOrAlt, result); - - default: - // This should never happen with the simplified type system - result.warnings.push(`Unexpected file type for embed: ${cleanPath}`); - return this.processFileEmbed(cleanPath, sizeOrAlt, result); - } - - } catch (error) { - result.warnings.push(`Failed to process embed: ${match} - ${error.message}`); - return match; // Return original on error - } - }); - } - - /** - * Get file extension from path - */ - private getFileExtension(filePath: string): string { - const lastDot = filePath.lastIndexOf('.'); - return lastDot > 0 ? filePath.substring(lastDot).toLowerCase() : ''; - } - - /** - * Determine file type based on extension - * Simplified to 3 types: image (displayed), pdf (embedded with preview), file (embedded) - */ - private determineFileType(extension: string): 'image' | 'pdf' | 'file' { - const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.ico', '.tiff']; - - if (imageExtensions.includes(extension)) return 'image'; - if (extension === '.pdf') return 'pdf'; - - // All other file types (including DOCX, videos, audio, etc.) are treated as files to be embedded - return 'file'; - } - - /** - * Process image embeds with size parameters - */ - private processImageEmbed(imagePath: string, sizeOrAlt: string | undefined, result: PreprocessingResult): string { - const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(imagePath); - - // For now, we'll mark this for async processing and return a placeholder - // The actual copying will be handled in the main export process - const fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1); - const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension - - // Create a marker that the export process can detect and replace - const marker = `IMAGE_EMBED_MARKER:${imagePath}:${baseName}:${sizeOrAlt || ''}`; - - // Add to processing queue for later copying - if (!result.metadata.imageEmbeds) { - result.metadata.imageEmbeds = []; - } - result.metadata.imageEmbeds.push({ - originalPath: imagePath, - sanitizedPath: sanitizedPath, - fileName: fileName, - baseName: baseName, - sizeOrAlt: sizeOrAlt, - marker: marker - }); - - result.warnings.push(`Image embed queued for processing: ${imagePath}`); - - return marker; - } - - - /** - * Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed - */ - private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string { - const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(pdfPath); - - // For now, we'll mark this for async processing and return a placeholder - // The actual conversion will be handled in the main export process - const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1); - const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension - - // Create a marker that the export process can detect and replace with Typst code - const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`; - - // Add to processing queue for later conversion - if (!result.metadata.pdfEmbeds) { - result.metadata.pdfEmbeds = []; - } - result.metadata.pdfEmbeds.push({ - originalPath: pdfPath, - sanitizedPath: sanitizedPath, - fileName: fileName, - baseName: baseName, - options: options, - marker: marker - }); - - result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`); - - return marker; - } - - /** - * Process generic file embeds - Convert to attachment using Typst's pdf.embed - */ - private processFileEmbed(filePath: string, options: string | undefined, result: PreprocessingResult): string { - const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(filePath); - - // For now, we'll mark this for async processing and return a placeholder - // The actual embedding will be handled in the main export process - const fileName = filePath.substring(filePath.lastIndexOf('/') + 1); - const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension - const fileExtension = this.getFileExtension(fileName); - - // Create a marker that the export process can detect and replace with Typst code - const marker = `FILE_EMBED_MARKER:${filePath}:${baseName}:${options || ''}`; - - // Add to processing queue for later conversion - if (!result.metadata.fileEmbeds) { - result.metadata.fileEmbeds = []; - } - result.metadata.fileEmbeds.push({ - originalPath: filePath, - sanitizedPath: sanitizedPath, - fileName: fileName, - baseName: baseName, - fileType: fileExtension, - options: options, - marker: marker - }); - - result.warnings.push(`File embed queued for processing with Typst pdf.embed: ${filePath}`); - - return marker; - } /** * Convert Obsidian callouts to standard blockquotes with styling markers @@ -789,6 +633,11 @@ export class MarkdownPreprocessor { wikilinkConfig: this.wikilinkConfig, baseUrl: this.options.baseUrl }); + + // Update EmbedProcessor since it depends on WikilinkProcessor + this.embedProcessor.updateConfig({ + wikilinkProcessor: this.wikilinkProcessor + }); } } diff --git a/src/converters/preprocessors/EmbedProcessor.ts b/src/converters/preprocessors/EmbedProcessor.ts new file mode 100644 index 0000000..867d658 --- /dev/null +++ b/src/converters/preprocessors/EmbedProcessor.ts @@ -0,0 +1,245 @@ +/** + * EmbedProcessor - Handles conversion of Obsidian embed syntax to markdown references + * Processes images, PDFs, and generic file embeds with appropriate markers for later processing + */ + +import { WikilinkProcessor } from './WikilinkProcessor'; + +export interface EmbedProcessorConfig { + /** WikilinkProcessor instance for path sanitization */ + wikilinkProcessor: WikilinkProcessor; +} + +// Note: PreprocessingResult is imported from the parent MarkdownPreprocessor module +export interface PreprocessingResult { + /** Processed markdown content */ + content: string; + /** Extracted metadata including tags and frontmatter */ + metadata: { + tags: string[]; + frontmatter?: Record; + title?: string; + wordCount: number; + pdfEmbeds?: Array<{ + originalPath: string; + sanitizedPath: string; + fileName: string; + baseName: string; + options?: string; + marker: string; + }>; + imageEmbeds?: Array<{ + originalPath: string; + sanitizedPath: string; + fileName: string; + baseName: string; + sizeOrAlt?: string; + marker: string; + }>; + fileEmbeds?: Array<{ + originalPath: string; + sanitizedPath: string; + fileName: string; + baseName: string; + fileType: string; + options?: string; + marker: string; + }>; + }; + /** Processing errors and warnings */ + errors: string[]; + /** Processing warnings */ + warnings: string[]; +} + +export class EmbedProcessor { + private wikilinkProcessor: WikilinkProcessor; + + // Regex patterns for embed matching + private readonly EMBED_PATTERN = /!\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g; + private readonly EMBED_SIZE_PATTERN = /(\d+)(?:x(\d+))?/; + + constructor(config: EmbedProcessorConfig) { + this.wikilinkProcessor = config.wikilinkProcessor; + } + + /** + * Convert embed syntax to standard markdown references + */ + public processEmbeds(content: string, result: PreprocessingResult): string { + return content.replace(this.EMBED_PATTERN, (match, embedPath, sizeOrAlt) => { + try { + const cleanPath = embedPath.trim(); + + if (!cleanPath) { + result.warnings.push(`Empty embed path found: ${match}`); + return match; + } + + // Parse file extension and path + const fileExtension = this.getFileExtension(cleanPath); + const fileType = this.determineFileType(fileExtension); + + // Handle different file types + switch (fileType) { + case 'image': + return this.processImageEmbed(cleanPath, sizeOrAlt, result); + + case 'pdf': + return this.processPdfEmbed(cleanPath, sizeOrAlt, result); + + case 'file': + return this.processFileEmbed(cleanPath, sizeOrAlt, result); + + default: + // This should never happen with the simplified type system + result.warnings.push(`Unexpected file type for embed: ${cleanPath}`); + return this.processFileEmbed(cleanPath, sizeOrAlt, result); + } + + } catch (error) { + result.warnings.push(`Failed to process embed: ${match} - ${error.message}`); + return match; // Return original on error + } + }); + } + + /** + * Get file extension from path + */ + private getFileExtension(filePath: string): string { + const lastDot = filePath.lastIndexOf('.'); + return lastDot > 0 ? filePath.substring(lastDot).toLowerCase() : ''; + } + + /** + * Determine file type based on extension + * Simplified to 3 types: image (displayed), pdf (embedded with preview), file (embedded) + */ + private determineFileType(extension: string): 'image' | 'pdf' | 'file' { + const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.ico', '.tiff']; + + if (imageExtensions.includes(extension)) return 'image'; + if (extension === '.pdf') return 'pdf'; + + // All other file types (including DOCX, videos, audio, etc.) are treated as files to be embedded + return 'file'; + } + + /** + * Process image embeds with size parameters + */ + private processImageEmbed(imagePath: string, sizeOrAlt: string | undefined, result: PreprocessingResult): string { + const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(imagePath); + + // For now, we'll mark this for async processing and return a placeholder + // The actual copying will be handled in the main export process + const fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1); + const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension + + // Create a marker that the export process can detect and replace + const marker = `IMAGE_EMBED_MARKER:${imagePath}:${baseName}:${sizeOrAlt || ''}`; + + // Add to processing queue for later copying + if (!result.metadata.imageEmbeds) { + result.metadata.imageEmbeds = []; + } + result.metadata.imageEmbeds.push({ + originalPath: imagePath, + sanitizedPath: sanitizedPath, + fileName: fileName, + baseName: baseName, + sizeOrAlt: sizeOrAlt, + marker: marker + }); + + result.warnings.push(`Image embed queued for processing: ${imagePath}`); + + return marker; + } + + /** + * Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed + */ + private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string { + const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(pdfPath); + + // For now, we'll mark this for async processing and return a placeholder + // The actual conversion will be handled in the main export process + const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1); + const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension + + // Create a marker that the export process can detect and replace with Typst code + const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`; + + // Add to processing queue for later conversion + if (!result.metadata.pdfEmbeds) { + result.metadata.pdfEmbeds = []; + } + result.metadata.pdfEmbeds.push({ + originalPath: pdfPath, + sanitizedPath: sanitizedPath, + fileName: fileName, + baseName: baseName, + options: options, + marker: marker + }); + + result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`); + + return marker; + } + + /** + * Process generic file embeds - Convert to attachment using Typst's pdf.embed + * Note: This handles all non-image, non-PDF files including videos, audio, documents, etc. + */ + private processFileEmbed(filePath: string, options: string | undefined, result: PreprocessingResult): string { + const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(filePath); + + // For now, we'll mark this for async processing and return a placeholder + // The actual embedding will be handled in the main export process + const fileName = filePath.substring(filePath.lastIndexOf('/') + 1); + const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension + const fileExtension = this.getFileExtension(fileName); + + // Create a marker that the export process can detect and replace with Typst code + const marker = `FILE_EMBED_MARKER:${filePath}:${baseName}:${options || ''}`; + + // Add to processing queue for later conversion + if (!result.metadata.fileEmbeds) { + result.metadata.fileEmbeds = []; + } + result.metadata.fileEmbeds.push({ + originalPath: filePath, + sanitizedPath: sanitizedPath, + fileName: fileName, + baseName: baseName, + fileType: fileExtension, + options: options, + marker: marker + }); + + result.warnings.push(`File embed queued for processing with Typst pdf.embed: ${filePath}`); + + return marker; + } + + /** + * Update configuration + */ + public updateConfig(config: Partial): void { + if (config.wikilinkProcessor) { + this.wikilinkProcessor = config.wikilinkProcessor; + } + } + + /** + * Get current configuration + */ + public getConfig(): EmbedProcessorConfig { + return { + wikilinkProcessor: this.wikilinkProcessor + }; + } +} \ No newline at end of file diff --git a/src/plugin/EmbedProcessor.ts b/src/plugin/EmbedProcessor.ts index 236aa73..cbb779a 100644 --- a/src/plugin/EmbedProcessor.ts +++ b/src/plugin/EmbedProcessor.ts @@ -136,27 +136,89 @@ export class EmbedProcessor { if (!fullImagePath) { console.warn(`Export: Image file not found: ${decodedPath}`); // Keep the original marker or replace with placeholder - const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.alt || imageEmbed.originalPath}]`; + const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`; updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); continue; } - // Get relative path from vault base for the image - const relativeImagePath = path.relative(vaultBasePath, fullImagePath); + // Handle WebP conversion if needed + let finalImagePath = fullImagePath; + const fileExtension = path.extname(fullImagePath).toLowerCase(); - // Replace the marker with Markdown image syntax (Pandoc will convert to Typst) - const markdownImage = imageEmbed.alt ? - `![${imageEmbed.alt}](${relativeImagePath})` : - `![](${relativeImagePath})`; + if (fileExtension === '.webp') { + // Convert WebP to PNG using ImageMagick + const originalImageName = path.basename(fullImagePath); + const pngFileName = originalImageName.replace(/\.webp$/i, '.png'); + const vaultTempImagesDir = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images'); + await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); + + const convertedImagePath = path.join(vaultTempImagesDir, pngFileName); + + console.log(`Export: Converting WebP to PNG: ${originalImageName} -> ${pngFileName}`); + + const { exec } = require('child_process'); + const util = require('util'); + const execAsync = util.promisify(exec); + + try { + // Use PathResolver to get the correct ImageMagick path + const { PathResolver } = await import('./PathResolver'); + const pathResolver = new PathResolver(this.plugin); + const imagemagickPath = pathResolver.resolveExecutablePath( + this.plugin.settings.executablePaths.imagemagickPath, + 'magick' + ); + + if (!imagemagickPath) { + throw new Error('ImageMagick not found - please install ImageMagick or configure the path in settings'); + } + + // Use resolved ImageMagick path to convert WebP to PNG + await execAsync(`"${imagemagickPath}" "${fullImagePath}" "${convertedImagePath}"`); + console.log(`Export: Successfully converted WebP to PNG: ${pngFileName}`); + finalImagePath = convertedImagePath; + } catch (convertError) { + console.error(`Export: Failed to convert WebP image: ${convertError.message}`); + // Fall back to original path and let Typst/Pandoc handle the error + console.warn(`Export: Proceeding with original WebP file: ${fullImagePath}`); + } + } - updatedContent = updatedContent.replace(imageEmbed.marker, markdownImage); + // Get relative path from vault base for the final image + const relativeImagePath = path.relative(vaultBasePath, finalImagePath); + + // Create the appropriate markdown output based on size/alt text + let imageOutput; + if (imageEmbed.sizeOrAlt) { + // Check if it's size information (width x height pattern) + const sizeMatch = imageEmbed.sizeOrAlt.match(/^(\d+)(?:x(\d+))?$/); + if (sizeMatch) { + const width = sizeMatch[1]; + const height = sizeMatch[2]; + + // Create image with size attributes (optimized for Pandoc → Typst conversion) + if (height) { + imageOutput = `${imageEmbed.baseName}`; + } else { + imageOutput = `${imageEmbed.baseName}`; + } + } else { + // Treat as alt text + imageOutput = `![${imageEmbed.sizeOrAlt}](${relativeImagePath})`; + } + } else { + // Standard image reference + imageOutput = `![${imageEmbed.baseName}](${relativeImagePath})`; + } + + updatedContent = updatedContent.replace(imageEmbed.marker, imageOutput); } catch (error) { const { fallback } = ExportErrorHandler.handleProcessingError( 'image embed', imageEmbed.originalPath, error, - `[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]` + `[⚠️ **Image processing error:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]` ); updatedContent = updatedContent.replace(imageEmbed.marker, fallback); }