Add Docstrings

This commit is contained in:
AlexKucera committed 2025-11-05 08:03:52 +01:00
1 parent 7ac9e1f489
commit 281c02210a
17 files changed
+5380 -177

No files matched your search

+2
View File
@@ -70,3 +70,5 @@ CLAUDE.md
repomix-output.xml
guidance.md
coverage/
+1778 -15
View File
File diff suppressed because it is too large. Load diff
+10 -2
View File
@@ -8,6 +8,10 @@
"lint": "eslint src/ main.ts",
"dev": "npm run typecheck && node esbuild.config.mjs",
"build": "npm run typecheck && npm run lint && node esbuild.config.mjs production",
"test": "vitest run",
"test:watch": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest run --coverage",
"package": "node scripts/package-plugin.js",
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
@@ -23,17 +27,21 @@
"devDependencies": {
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.34.0",
"@types/node": "^16.11.6",
"@types/node": "^20.19.24",
"@typescript-eslint/eslint-plugin": "5.29.0",
"@typescript-eslint/parser": "5.29.0",
"@vitest/coverage-v8": "^4.0.6",
"@vitest/ui": "^4.0.6",
"archiver": "^7.0.1",
"builtin-modules": "3.3.0",
"esbuild": "0.17.3",
"globals": "^16.3.0",
"happy-dom": "^20.0.10",
"obsidian": "latest",
"tslib": "2.4.0",
"typescript": "^5.9.2",
"typescript-eslint": "^8.43.0"
"typescript-eslint": "^8.43.0",
"vitest": "^4.0.6"
},
"dependencies": {
"gray-matter": "^4.0.3",
+445 -9
View File
@@ -1,6 +1,35 @@
/**
* MarkdownPreprocessor - Converts Obsidian-specific markdown syntax to standard markdown
* compatible with Pandoc for Typst PDF export
* Markdown preprocessing pipeline for Obsidian-to-Pandoc conversion.
*
* This module provides the central preprocessing system that transforms Obsidian's
* proprietary markdown syntax into standard markdown compatible with Pandoc and Typst.
* It coordinates multiple specialized processors to handle:
* - YAML frontmatter extraction and formatting
* - Wikilink conversion to standard markdown links
* - Obsidian embed syntax (![[...]]) to standard images/includes
* - Callout blocks (>[!note]) to custom Typst environments
* - Email block formatting for email exports
* - Remote image detection and download queue management
* - Metadata extraction (tags, title, frontmatter)
*
* The preprocessor runs in a specific order to avoid conflicts:
* 1. Horizontal rule normalization (prevent YAML delimiter confusion)
* 2. Frontmatter extraction and processing
* 3. Email block formatting
* 4. Unnecessary link filtering (Open: links, Mail.app links)
* 5. Embed processing (![[image]], ![[pdf]])
* 6. Remote image detection (![](https://...))
* 7. Wikilink conversion ([[link]] → [link](link.md))
* 8. Callout block conversion
* 9. Title extraction
*
* Key features:
* - Stateless processing (each call is independent)
* - Comprehensive metadata extraction for export pipeline
* - Configurable wikilink and frontmatter handling
* - Remote resource tracking for download coordination
* - Error and warning reporting for user feedback
* - Modular processor architecture for maintainability
*/
import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor';
@@ -11,6 +40,13 @@ import { MetadataExtractor } from './preprocessors/MetadataExtractor';
import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor';
import * as path from 'path';
/**
* Configuration options for markdown preprocessing behavior.
*
* @property preserveFrontmatter - Keep YAML frontmatter in output (true) or strip it (false)
* @property baseUrl - Base URL for relative link resolution (optional)
* @property printFrontmatter - Display frontmatter as formatted text at document start (optional)
*/
export interface PreprocessorOptions {
/** Preserve existing frontmatter */
preserveFrontmatter: boolean;
@@ -20,7 +56,24 @@ export interface PreprocessorOptions {
printFrontmatter?: boolean;
}
/**
* Result of markdown preprocessing operation.
*
* Contains the processed content, extracted metadata, and any errors or warnings
* encountered during processing. The metadata includes information needed by
* downstream export components like embedded resources and frontmatter data.
*
* @property content - Processed markdown content ready for Pandoc
* @property metadata - Extracted metadata and resource tracking
* @property metadata.tags - Extracted tags from frontmatter and content
* @property metadata.frontmatter - Parsed YAML frontmatter object
* @property metadata.title - Document title (from frontmatter or H1)
* @property metadata.pdfEmbeds - PDF files embedded via ![[file.pdf]]
* @property metadata.imageEmbeds - Images embedded via ![[image.png]] or ![](url)
* @property metadata.fileEmbeds - Other files embedded via ![[file.ext]]
* @property errors - Critical processing errors
* @property warnings - Non-critical processing warnings
*/
export interface PreprocessingResult {
/** Processed markdown content */
content: string;
@@ -61,6 +114,36 @@ export interface PreprocessingResult {
warnings: string[];
}
/**
* Configuration for MarkdownPreprocessor initialization.
*
* Provides all settings needed to initialize the preprocessor and its
* constituent processors. This configuration is typically built from plugin
* settings and file context.
*
* @property vaultPath - Absolute path to vault root for file resolution
* @property options - Preprocessing behavior configuration
* @property wikilinkConfig - Wikilink conversion settings
* @property noteTitle - Optional title to prepend as H1 heading
*
* @example
* ```typescript
* const config: MarkdownPreprocessorConfig = {
* vaultPath: '/Users/name/vault',
* options: {
* preserveFrontmatter: true,
* printFrontmatter: false,
* baseUrl: ''
* },
* wikilinkConfig: {
* format: 'md',
* extension: '.md'
* },
* noteTitle: 'My Document'
* };
* const preprocessor = new MarkdownPreprocessor(config);
* ```
*/
export interface MarkdownPreprocessorConfig {
/** Vault path for file resolution */
vaultPath: string;
@@ -72,6 +155,72 @@ export interface MarkdownPreprocessorConfig {
noteTitle?: string;
}
/**
* Central markdown preprocessing coordinator for Obsidian-to-Pandoc conversion.
*
* This class orchestrates multiple specialized processors to transform Obsidian's
* proprietary markdown into standard markdown that Pandoc can process. It ensures
* processors run in the correct order to avoid syntax conflicts and maintains
* comprehensive metadata about the conversion.
*
* The preprocessor is stateless - each process() call is independent and doesn't
* affect previous or future calls. Configuration can be updated between calls via
* updateConfig().
*
* Architecture:
* - Delegates to specialized processors for specific syntax
* - Maintains processing order to prevent conflicts
* - Aggregates metadata from all processors
* - Provides error and warning reporting
*
* Processing Pipeline:
* 1. Horizontal rules (prevent YAML confusion)
* 2. Frontmatter (extract metadata, optionally format)
* 3. Email blocks (custom email formatting)
* 4. Link filtering (remove unnecessary links)
* 5. Embeds (convert ![[...]] syntax)
* 6. Remote images (detect and queue for download)
* 7. Wikilinks (convert [[...]] to standard links)
* 8. Callouts (convert >[!type] blocks)
* 9. Title extraction (from H1 or frontmatter)
*
* @example
* ```typescript
* // Initialize preprocessor
* const preprocessor = new MarkdownPreprocessor({
* vaultPath: '/path/to/vault',
* options: {
* preserveFrontmatter: true,
* printFrontmatter: false
* },
* wikilinkConfig: {
* format: 'md',
* extension: '.md'
* },
* noteTitle: 'My Note'
* });
*
* // Process markdown
* const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]';
* const result = await preprocessor.process(obsidianMarkdown);
*
* console.log(result.content); // Standard markdown
* console.log(result.metadata.imageEmbeds); // Image processing info
* console.log(result.errors); // Any errors encountered
* ```
*
* @example
* ```typescript
* // Update configuration for different export
* preprocessor.updateConfig({
* options: { preserveFrontmatter: false },
* noteTitle: 'Different Title'
* });
*
* // Process with new configuration
* const newResult = await preprocessor.process(markdown);
* ```
*/
export class MarkdownPreprocessor {
private vaultPath: string;
private options: PreprocessorOptions;
@@ -113,7 +262,72 @@ export class MarkdownPreprocessor {
}
/**
* Main processing method that converts Obsidian markdown to standard markdown
* Processes Obsidian markdown and converts it to standard Pandoc-compatible markdown.
*
* This is the main entry point for preprocessing. It runs all configured processors
* in the correct order, aggregates metadata from each stage, and returns a complete
* result with processed content and comprehensive metadata.
*
* The method is async to support future extensions (though current processors are sync).
* Processing is stateless - each call operates independently on the provided content.
*
* Processing Order (critical for avoiding conflicts):
* 1. Horizontal rules → Prevent YAML delimiter confusion
* 2. Frontmatter → Extract metadata, optionally format
* 3. Email blocks → Custom formatting for email exports
* 4. Link filtering → Remove Open: and Mail.app links
* 5. Embeds → Convert ![[...]] syntax first (before wikilinks add .md)
* 6. Remote images → Detect and queue ![](https://...) for download
* 7. Wikilinks → Convert [[...]] after embeds processed
* 8. Callouts → Convert >[!type] blocks to Typst environments
* 9. Title extraction → From H1 or frontmatter
*
* @param content - Raw Obsidian markdown content to process
* @returns Preprocessing result with converted content, metadata, and diagnostics
*
* @example
* ```typescript
* // Process note with various Obsidian syntax
* const markdown = `---
* title: My Note
* tags: [export, pdf]
* ---
*
* # My Note
*
* Internal link: [[other-note]]
* Image: ![[screenshot.png]]
* Callout: > [!note] This is important
* `;
*
* const result = await preprocessor.process(markdown);
*
* // Check for errors
* if (result.errors.length > 0) {
* console.error('Processing errors:', result.errors);
* }
*
* // Access processed content
* console.log(result.content); // Standard markdown
*
* // Access extracted metadata
* console.log(result.metadata.title); // "My Note"
* console.log(result.metadata.tags); // ["export", "pdf"]
* console.log(result.metadata.imageEmbeds); // [{originalPath, ...}]
* ```
*
* @example
* ```typescript
* // Handle remote images
* const markdown = '![Remote](https://example.com/image.png)';
* const result = await preprocessor.process(markdown);
*
* // Remote images are queued for download
* result.metadata.imageEmbeds.forEach(embed => {
* console.log(`Download: ${embed.originalPath}`);
* // Export pipeline will download and embed these
* });
* ```
*/
public async process(content: string): Promise<PreprocessingResult> {
const result: PreprocessingResult = {
@@ -167,8 +381,51 @@ export class MarkdownPreprocessor {
}
/**
* Process standard markdown images and track remote URLs for download
* Remote images are marked for later download and embedding
* Processes standard markdown images and queues remote URLs for download.
*
* This method scans the content for standard markdown image syntax `![alt](url)`
* and detects remote images (http:// or https://). Remote images are:
* - Replaced with marker placeholders in the content
* - Added to the imageEmbeds metadata for download by the export pipeline
* - Tracked with a warning message for user visibility
*
* Local images (file paths without http/https) are left unchanged for normal
* processing. This allows the export pipeline to handle them separately from
* remote resources that need downloading.
*
* The marker format is: `IMAGE_EMBED_MARKER:{url}:{baseName}:{alt}`
* This allows the export pipeline to:
* - Download the remote image
* - Replace the marker with the local path
* - Preserve the alt text for accessibility
*
* @param content - Markdown content to process
* @param result - Processing result to update with remote image metadata
* @returns Content with remote images replaced by markers
* @private
*
* @example
* ```typescript
* // Remote image detected and queued
* const markdown = '![Photo](https://example.com/image.png)';
* const result = { metadata: {}, warnings: [], errors: [] };
* const processed = this.processStandardMarkdownImages(markdown, result);
*
* // Content has marker: 'IMAGE_EMBED_MARKER:https://...:image:Photo'
* // result.metadata.imageEmbeds has entry for download
* // result.warnings includes "Remote URL image queued for download"
* ```
*
* @example
* ```typescript
* // Local image left unchanged
* const markdown = '![Local](local-image.png)';
* const result = { metadata: {}, warnings: [], errors: [] };
* const processed = this.processStandardMarkdownImages(markdown, result);
*
* // Content unchanged: '![Local](local-image.png)'
* // No entries added to metadata or warnings
* ```
*/
private processStandardMarkdownImages(content: string, result: PreprocessingResult): string {
// Pattern to match standard markdown images: ![alt](url)
@@ -219,7 +476,66 @@ export class MarkdownPreprocessor {
}
/**
* Update configuration
* Updates the preprocessor configuration dynamically.
*
* This method allows modifying preprocessor settings after initialization without
* creating a new instance. It supports partial updates - only the provided fields
* are changed, leaving others intact. The method also propagates relevant changes
* to dependent processors (WikilinkProcessor, EmbedProcessor) to maintain consistency.
*
* When updating wikilink configuration or base URL, the changes cascade to:
* 1. WikilinkProcessor - Updated with new wikilink settings and base URL
* 2. EmbedProcessor - Receives updated WikilinkProcessor reference
*
* This cascading update ensures that all processors use consistent configuration
* throughout the preprocessing pipeline.
*
* Configuration updates are useful for:
* - Changing export settings between different notes
* - Applying user preference changes without reinitialization
* - Switching between different export contexts (web vs. local)
* - Testing different configuration combinations
*
* @param config - Partial configuration update (only specified fields are changed)
*
* @example
* ```typescript
* // Update base URL for web export
* preprocessor.updateConfig({
* options: { baseUrl: 'https://example.com/notes' }
* });
*
* // Process note with web-friendly links
* const result = await preprocessor.process(markdown);
* // Links will use the new base URL
* ```
*
* @example
* ```typescript
* // Change wikilink format for different export
* preprocessor.updateConfig({
* wikilinkConfig: {
* format: 'html',
* extension: '.html'
* }
* });
*
* // Process with HTML-style links
* const result = await preprocessor.process(markdown);
* // [[note]] becomes [note](note.html)
* ```
*
* @example
* ```typescript
* // Update multiple settings at once
* preprocessor.updateConfig({
* vaultPath: '/new/vault/path',
* options: {
* preserveFrontmatter: false,
* printFrontmatter: true
* }
* });
* ```
*/
public updateConfig(config: Partial<MarkdownPreprocessorConfig>): void {
if (config.vaultPath) {
@@ -247,7 +563,48 @@ export class MarkdownPreprocessor {
}
/**
* Get current configuration
* Retrieves the current preprocessor configuration.
*
* This method returns a snapshot of the preprocessor's current settings,
* including vault path, processing options, and wikilink configuration.
* The returned object is a plain data object that can be:
* - Inspected for debugging
* - Serialized for logging or caching
* - Modified and passed to updateConfig() for changes
* - Used to create a new preprocessor with the same settings
*
* Note: The returned configuration does not include the noteTitle field,
* as this is typically set per-export rather than persisted in the
* preprocessor configuration.
*
* @returns Current preprocessor configuration object
*
* @example
* ```typescript
* // Inspect current settings
* const config = preprocessor.getConfig();
* console.log('Vault path:', config.vaultPath);
* console.log('Preserve frontmatter:', config.options.preserveFrontmatter);
* console.log('Wikilink format:', config.wikilinkConfig.format);
* ```
*
* @example
* ```typescript
* // Clone preprocessor with same configuration
* const currentConfig = preprocessor.getConfig();
* const clonedPreprocessor = new MarkdownPreprocessor({
* ...currentConfig,
* noteTitle: 'Different Title'
* });
* ```
*
* @example
* ```typescript
* // Modify and reapply configuration
* const config = preprocessor.getConfig();
* config.options.baseUrl = 'https://new-url.com';
* preprocessor.updateConfig(config);
* ```
*/
public getConfig(): MarkdownPreprocessorConfig {
return {
@@ -258,12 +615,91 @@ export class MarkdownPreprocessor {
}
}
// Default configurations
/**
* Default preprocessor options for standard Markdown processing.
*
* These defaults are designed to work well for most Obsidian-to-Pandoc conversions:
* - **preserveFrontmatter: true** - Keeps YAML frontmatter in the output, allowing
* Pandoc and Typst to access metadata (title, author, date, custom variables).
* Set to false if you want to strip frontmatter entirely.
* - **baseUrl: ''** - Empty base URL means links remain relative to the vault.
* Set this when exporting to web to make links absolute (e.g., 'https://example.com/notes').
*
* These values are used when creating a new MarkdownPreprocessor without explicit
* options. They can be overridden via the MarkdownPreprocessorConfig constructor
* parameter or modified later via updateConfig().
*
* @example
* ```typescript
* // Use defaults implicitly
* const preprocessor = new MarkdownPreprocessor({
* vaultPath: '/vault',
* options: DEFAULT_PREPROCESSOR_OPTIONS, // Explicit use of defaults
* wikilinkConfig: DEFAULT_WIKILINK_CONFIG
* });
* ```
*
* @example
* ```typescript
* // Override defaults for web export
* const webOptions = {
* ...DEFAULT_PREPROCESSOR_OPTIONS,
* baseUrl: 'https://blog.example.com/notes'
* };
* ```
*/
export const DEFAULT_PREPROCESSOR_OPTIONS: PreprocessorOptions = {
preserveFrontmatter: true,
baseUrl: ''
};
/**
* Default wikilink conversion configuration for Markdown output.
*
* These defaults convert Obsidian wikilinks to standard Markdown links:
* - **format: 'md'** - Convert to Markdown format `[text](link.md)`
* Other possible values: 'html' for `[text](link.html)`, 'wiki' to preserve `[[link]]`
* - **extension: '.md'** - Add .md extension to converted links
* Ensures [[note]] becomes [note](note.md) for proper cross-reference handling
*
* This configuration is passed to WikilinkProcessor during preprocessing and
* ensures consistent link handling throughout the conversion pipeline.
*
* These values work well for Pandoc conversion, as Pandoc expects standard
* Markdown links with file extensions. For web publishing, you might want to
* use format: 'html' and extension: '.html' instead.
*
* @example
* ```typescript
* // Use defaults for standard Markdown output
* const preprocessor = new MarkdownPreprocessor({
* vaultPath: '/vault',
* options: DEFAULT_PREPROCESSOR_OPTIONS,
* wikilinkConfig: DEFAULT_WIKILINK_CONFIG // [[note]] → [note](note.md)
* });
* ```
*
* @example
* ```typescript
* // Override for HTML export
* const htmlWikilinkConfig = {
* ...DEFAULT_WIKILINK_CONFIG,
* format: 'html',
* extension: '.html'
* };
* // [[note]] → [note](note.html)
* ```
*
* @example
* ```typescript
* // Preserve wikilinks (no conversion)
* const preserveWikilinks = {
* format: 'wiki',
* extension: ''
* };
* // [[note]] → [[note]] (unchanged)
* ```
*/
export const DEFAULT_WIKILINK_CONFIG: WikilinkConfig = {
format: 'md',
extension: '.md'
+214 -18
View File
@@ -1,6 +1,17 @@
/**
* Pandoc to Typst PDF Converter
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine
* Pandoc to Typst PDF Converter.
*
* This module provides the main conversion engine for transforming Markdown files
* to PDF documents using the Pandoc → Typst → PDF pipeline. It coordinates all
* aspects of the conversion process including:
* - Temporary file and directory management
* - Command building and execution
* - Progress reporting
* - Resource cleanup
* - Error handling
*
* The converter supports both file-based and content-based conversions, automatically
* managing temporary directories and cleanup on process termination.
*/
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
@@ -11,6 +22,52 @@ import { PathUtils } from '../core/PathUtils';
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor';
/**
* Main converter class for Markdown → Typst → PDF conversion.
*
* This class orchestrates the PDF export process by delegating to specialized
* components (PandocCommandBuilder, PandocExecutor) while managing temporary
* resources and providing progress feedback.
*
* Key features:
* - File and content-based conversion support
* - Automatic temporary directory management
* - Process cleanup on termination (exit, SIGINT, SIGTERM, exceptions)
* - Progress callback support for UI updates
* - Configurable Pandoc and Typst settings
*
* Lifecycle:
* 1. Constructor initializes command builder and executor
* 2. Conversion methods create temp directories and build commands
* 3. Executor runs Pandoc with Typst engine
* 4. Cleanup automatically removes temporary files
* 5. dispose() for manual cleanup when done
*
* @example
* ```typescript
* const converter = new PandocTypstConverter(
* plugin,
* { template: 'modern', variables: { ... } },
* { ppi: 144 }
* );
*
* try {
* const result = await converter.convertToPDF(
* 'input.md',
* 'output.pdf',
* (message, progress) => console.log(`${progress}%: ${message}`)
* );
*
* if (result.success) {
* console.log('PDF created:', result.outputPath);
* } else {
* console.error('Conversion failed:', result.error);
* }
* } finally {
* await converter.dispose();
* }
* ```
*/
export class PandocTypstConverter {
private tempDir: string | null = null;
private cleanupHandlers: (() => void)[] = [];
@@ -19,10 +76,34 @@ export class PandocTypstConverter {
private pandocExecutor: PandocExecutor;
/**
* Create a new PandocTypstConverter instance
* @param plugin The main plugin instance for accessing settings
* @param pandocOptions Configuration options for Pandoc
* @param typstSettings Settings specific to Typst engine
* Creates a new PandocTypstConverter instance with configuration.
*
* Initializes the converter with the plugin instance and configuration options
* for both Pandoc and Typst. Sets up cleanup handlers to ensure temporary
* files are removed on process termination.
*
* @param plugin - The main plugin instance for accessing app and settings
* @param pandocOptions - Configuration options for Pandoc conversion (template, variables, etc.)
* @param typstSettings - Settings specific to Typst rendering engine (ppi, font-paths, etc.)
*
* @example
* ```typescript
* const converter = new PandocTypstConverter(
* this.plugin,
* {
* template: 'modern',
* variables: {
* pageSize: 'a4',
* bodyFont: 'Georgia'
* },
* metadata: { title: 'My Document' }
* },
* {
* ppi: 144,
* fontPaths: ['/usr/share/fonts']
* }
* );
* ```
*/
constructor(
plugin: obsidianTypstPDFExport,
@@ -37,15 +118,46 @@ export class PandocTypstConverter {
}
/**
* Convert a markdown file to PDF using Pandoc with Typst engine
* @param inputPath Path to the input markdown file
* @param outputPath Path where the PDF should be saved
* @param progressCallback Optional callback for progress updates
* @returns Promise resolving to conversion result
* Converts a Markdown file to PDF using the Pandoc → Typst → PDF pipeline.
*
* This is the primary conversion method that handles the complete export process:
* 1. Creates temporary directory for intermediate files
* 2. Builds Pandoc command with configured options
* 3. Executes Pandoc with Typst engine
* 4. Reports progress via optional callback
* 5. Returns result with success status and output path
*
* The method automatically manages temporary files and provides progress updates
* at key stages. If conversion fails, returns error information in the result
* object rather than throwing.
*
* @param inputPath - Absolute path to the input Markdown file
* @param outputPath - Absolute path where the PDF should be saved
* @param progressCallback - Optional callback for progress updates (message, percentage)
* @returns Promise resolving to conversion result with success flag and optional error
*
* @example
* ```typescript
* const result = await converter.convertToPDF(
* '/path/to/note.md',
* '/path/to/output.pdf',
* (message, progress) => {
* console.log(`${progress}%: ${message}`);
* // Update UI progress bar
* }
* );
*
* if (result.success) {
* console.log('PDF created at:', result.outputPath);
* } else {
* console.error('Conversion failed:', result.error);
* console.log('Pandoc output:', result.stdout);
* }
* ```
*/
async convertToPDF(
inputPath: string,
outputPath: string,
inputPath: string,
outputPath: string,
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
try {
@@ -89,7 +201,43 @@ export class PandocTypstConverter {
}
/**
* Convert markdown content to PDF
* Converts Markdown content (string) to PDF without requiring a file.
*
* This is a convenience method for converting Markdown content directly from
* memory without needing an existing file. It creates a temporary file,
* delegates to convertToPDF, then cleans up the temporary file.
*
* Useful for:
* - Converting dynamically generated content
* - Processing in-memory Markdown transformations
* - Testing conversion without file system operations
*
* Note: This method merges the provided options with existing pandocOptions.
*
* @param content - Markdown content to convert
* @param outputPath - Absolute path where the PDF should be saved
* @param options - Additional Pandoc options to merge with existing settings
* @param progressCallback - Optional callback for progress updates (message, percentage)
* @returns Promise resolving to conversion result with success flag and optional error
*
* @example
* ```typescript
* const markdown = `
* # My Document
* This is **dynamically generated** content.
* `;
*
* const result = await converter.convertMarkdownToPDF(
* markdown,
* '/path/to/output.pdf',
* { variables: { title: 'Generated Doc' } },
* (msg, pct) => updateProgress(pct)
* );
*
* if (result.success) {
* console.log('Created PDF from content');
* }
* ```
*/
async convertMarkdownToPDF(
content: string,
@@ -131,7 +279,17 @@ export class PandocTypstConverter {
}
/**
* Set up cleanup handlers for temporary files
* Sets up automatic cleanup handlers for process termination events.
*
* Registers the cleanup method to run on various process termination events
* to ensure temporary files are removed even if the process exits unexpectedly.
* Handlers are registered for:
* - Normal exit
* - SIGINT (Ctrl+C)
* - SIGTERM (kill command)
* - Uncaught exceptions
*
* @private
*/
private setupCleanup(): void {
const cleanup = () => {
@@ -146,7 +304,16 @@ export class PandocTypstConverter {
/**
* Clean up temporary files and directories
* Cleans up temporary files and directories.
*
* This method executes all registered cleanup handlers and removes the temporary
* directory created by the converter. Cleanup failures are logged but don't throw
* to avoid interfering with normal operation or other cleanup operations.
*
* Called automatically on process termination or manually via dispose().
*
* @private
* @returns Promise that resolves when cleanup is complete
*/
private async cleanup(): Promise<void> {
try {
@@ -171,7 +338,19 @@ export class PandocTypstConverter {
}
/**
* Ensure temporary directory exists
* Ensures a temporary directory exists for intermediate conversion files.
*
* Creates a temporary directory on first call and reuses it for subsequent calls.
* The directory is created inside the plugin folder if vaultBasePath is available,
* otherwise falls back to vault-level temp directories.
*
* The temporary directory is used for:
* - Temporary Markdown files
* - Intermediate Typst files (if debug mode enabled)
* - Processed resource files
*
* @private
* @returns Promise resolving to the temporary directory path
*/
private async ensureTempDirectory(): Promise<string> {
if (!this.tempDir) {
@@ -194,7 +373,24 @@ export class PandocTypstConverter {
/**
* Dispose of the converter and clean up resources
* Disposes of the converter and cleans up all resources.
*
* This method should be called when done with the converter to ensure temporary
* files are removed. While cleanup happens automatically on process termination,
* calling dispose explicitly allows for immediate cleanup and is recommended
* when the converter is no longer needed.
*
* @returns Promise that resolves when cleanup is complete
*
* @example
* ```typescript
* const converter = new PandocTypstConverter(plugin, options);
* try {
* await converter.convertToPDF(input, output);
* } finally {
* await converter.dispose(); // Cleanup even if conversion fails
* }
* ```
*/
async dispose(): Promise<void> {
await this.cleanup();
+439 -8
View File
@@ -1,6 +1,39 @@
/**
* PDF to Image Converter using pdf-to-img
* Converts PDF files to PNG images for preview in Typst exports
* PDF to Image conversion for embedded PDF files in Obsidian notes.
*
* This module provides a robust conversion system for transforming PDF files into
* images suitable for embedding in Typst-generated PDFs. Since Typst has limited
* native PDF embedding capabilities, this converter extracts the first page of
* embedded PDFs and converts them to high-quality PNG or JPEG images.
*
* Key features:
* - Singleton pattern for resource efficiency and state management
* - First-page-only conversion for preview purposes
* - Configurable image quality and dimensions
* - Multi-strategy PDF processing (pdf-to-img library with ImageMagick fallback)
* - Automatic format conversion and optimization
* - File discovery for handling various filename patterns
* - Comprehensive error handling and validation
*
* Conversion Pipeline:
* 1. PDF validation (file exists, valid format, readable)
* 2. Output directory preparation
* 3. CLI execution via pdf-to-img or ImageMagick
* 4. Generated file discovery (handles naming variations)
* 5. Image optimization (format conversion, dimension detection)
* 6. Result packaging with metadata
*
* The converter delegates to specialized utilities:
* - PdfProcessor: PDF validation and metadata extraction
* - PdfCliExecutor: Command-line tool execution
* - FileDiscovery: Generated file location
* - ImageOptimizer: Format conversion and dimension detection
*
* Architecture Notes:
* - Singleton pattern ensures consistent state across exports
* - Plugin reference enables vault file operations
* - Modular design allows easy extension for multi-page conversion
* - Error results preserve context for debugging
*/
import * as path from 'path';
@@ -11,6 +44,51 @@ import { FileDiscovery } from './pdf/FileDiscovery';
import type { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils';
/**
* Configuration options for PDF to image conversion.
*
* These options control the quality, dimensions, and format of generated images.
* All options are optional with sensible defaults optimized for embedding in PDFs.
*
* @property scale - Rendering scale factor for image quality (default: 2.0)
* Higher values produce sharper images but larger file sizes. 2.0 is optimal
* for HiDPI displays and print-quality PDFs. Use 1.0 for web-optimized exports.
* @property maxWidth - Maximum output image width in pixels (default: 800)
* Images wider than this are scaled down proportionally. Prevents excessive
* file sizes while maintaining readability in typical PDF layouts.
* @property maxHeight - Maximum output image height in pixels (default: 600)
* Images taller than this are scaled down proportionally. Balances quality
* with file size for typical document heights.
* @property format - Output image format (default: 'png')
* - 'png': Lossless compression, best for diagrams and text
* - 'jpeg': Lossy compression, smaller files for photos
* @property quality - JPEG compression quality 1-100 (default: 90)
* Only applies when format is 'jpeg'. Higher values preserve more detail
* but increase file size. 90 provides excellent quality with good compression.
*
* @example
* ```typescript
* // High-quality conversion for print
* const printOptions: PdfConversionOptions = {
* scale: 3.0,
* maxWidth: 1200,
* maxHeight: 900,
* format: 'png'
* };
* ```
*
* @example
* ```typescript
* // Web-optimized conversion
* const webOptions: PdfConversionOptions = {
* scale: 1.0,
* maxWidth: 600,
* maxHeight: 450,
* format: 'jpeg',
* quality: 85
* };
* ```
*/
export interface PdfConversionOptions {
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
scale?: number;
@@ -24,6 +102,58 @@ export interface PdfConversionOptions {
quality?: number;
}
/**
* Result of PDF to image conversion operation.
*
* This interface provides comprehensive information about the conversion outcome,
* including file paths, dimensions, and success status. The result always includes
* a success flag - when false, the error field provides diagnostic information.
*
* @property imagePath - Absolute path to the generated image file
* Empty string if conversion failed. Use this path to embed the image in Typst.
* @property originalDimensions - Original PDF page dimensions in pixels
* Width and height of the PDF page before conversion. Set to {0, 0} on failure.
* Note: Currently estimates based on converted image due to library limitations.
* @property imageDimensions - Generated image dimensions in pixels
* Actual width and height of the output image file. May differ from original
* due to scaling, format conversion, or optimization. Set to {0, 0} on failure.
* @property success - Conversion success flag
* True if image was generated successfully, false if any error occurred.
* Always check this before using imagePath or dimension data.
* @property error - Error message if conversion failed
* Present only when success is false. Contains diagnostic information about
* what went wrong (file not found, invalid PDF, conversion failure, etc.).
*
* @example
* ```typescript
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
*
* if (result.success) {
* console.log('Image created:', result.imagePath);
* console.log('Dimensions:', result.imageDimensions);
* // Use result.imagePath in Typst template
* } else {
* console.error('Conversion failed:', result.error);
* // Fallback to placeholder or skip embed
* }
* ```
*
* @example
* ```typescript
* // Handle dimension information
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
*
* if (result.success) {
* const aspectRatio = result.imageDimensions.width / result.imageDimensions.height;
* console.log('Aspect ratio:', aspectRatio.toFixed(2));
*
* // Adjust Typst layout based on dimensions
* if (aspectRatio > 1.5) {
* // Wide image - use landscape layout
* }
* }
* ```
*/
export interface PdfConversionResult {
/** Path to the generated image file */
imagePath: string;
@@ -43,15 +173,124 @@ export interface PdfConversionResult {
error?: string;
}
/**
* Singleton converter for transforming PDF files into embeddable images.
*
* This class provides the primary interface for PDF to image conversion in the
* export pipeline. It implements the singleton pattern to ensure consistent state
* and resource management across multiple conversion operations.
*
* Key Responsibilities:
* - First-page extraction from PDF files
* - High-quality image generation with configurable options
* - PDF validation and metadata extraction
* - Integration with Obsidian vault file system
* - Error handling and result reporting
*
* Architecture:
* The converter delegates to specialized utility classes:
* - **PdfProcessor**: PDF file validation and metadata
* - **PdfCliExecutor**: Command-line tool execution (pdf-to-img, ImageMagick)
* - **FileDiscovery**: Generated file location and verification
* - **ImageOptimizer**: Format conversion and dimension detection
* - **PathUtils**: Obsidian vault file operations
*
* Singleton Pattern:
* Use `getInstance()` to obtain the converter instance. The singleton ensures:
* - Single plugin reference across all conversions
* - Consistent configuration and state
* - Efficient resource usage
* - Simplified dependency injection
*
* Usage Flow:
* 1. Get instance with plugin reference: `PdfToImageConverter.getInstance(plugin)`
* 2. Convert PDF: `await converter.convertFirstPageToImage(path, outDir, options)`
* 3. Check result.success and use result.imagePath in Typst template
* 4. Handle errors via result.error message
*
* @example
* ```typescript
* // Initialize converter with plugin reference
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* // Convert PDF with default options
* const result = await converter.convertFirstPageToImage(
* '/vault/attachments/document.pdf',
* '/vault/.obsidian/plugins/typst-pdf-export/temp-images'
* );
*
* if (result.success) {
* console.log('Converted to:', result.imagePath);
* // Embed result.imagePath in Typst template
* } else {
* console.error('Conversion failed:', result.error);
* }
* ```
*
* @example
* ```typescript
* // High-quality conversion with custom options
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* const result = await converter.convertFirstPageToImage(
* pdfPath,
* outputDir,
* {
* scale: 3.0, // 3x rendering for print quality
* maxWidth: 1200, // Larger dimensions
* format: 'png' // Lossless format
* }
* );
* ```
*/
export class PdfToImageConverter {
private static instance: PdfToImageConverter;
private plugin: obsidianTypstPDFExport | undefined;
/**
* Private constructor for singleton pattern.
*
* Use getInstance() to obtain the converter instance instead of constructing directly.
*
* @param plugin - Optional plugin reference for vault operations
* @private
*/
private constructor(plugin?: obsidianTypstPDFExport) {
this.plugin = plugin;
}
/**
* Gets or creates the singleton PdfToImageConverter instance.
*
* This method ensures only one converter instance exists throughout the application
* lifecycle. If a plugin reference is provided on subsequent calls, it updates the
* stored reference to ensure vault operations work correctly.
*
* Thread Safety:
* This implementation is safe for single-threaded JavaScript execution.
* The singleton is created on first access and reused thereafter.
*
* @param plugin - Optional plugin reference (updates stored reference if provided)
* @returns The singleton PdfToImageConverter instance
*
* @example
* ```typescript
* // First call creates instance
* const converter1 = PdfToImageConverter.getInstance(this.plugin);
*
* // Subsequent calls return same instance
* const converter2 = PdfToImageConverter.getInstance();
* console.log(converter1 === converter2); // true
* ```
*
* @example
* ```typescript
* // Update plugin reference after initialization
* const converter = PdfToImageConverter.getInstance(); // No plugin initially
* // ... later ...
* PdfToImageConverter.getInstance(this.plugin); // Updates plugin reference
* ```
*/
public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter {
if (!PdfToImageConverter.instance) {
PdfToImageConverter.instance = new PdfToImageConverter(plugin);
@@ -63,11 +302,93 @@ export class PdfToImageConverter {
}
/**
* Convert the first page of a PDF to an image
* Converts the first page of a PDF file to a high-quality image.
*
* This is the primary conversion method that orchestrates the complete PDF-to-image
* pipeline. It handles validation, conversion, optimization, and error reporting in
* a single operation suitable for embedding in Typst exports.
*
* Conversion Pipeline:
* 1. **Validation**: Verify PDF file exists and is valid
* 2. **Directory Setup**: Ensure output directory exists (via vault adapter)
* 3. **CLI Execution**: Run pdf-to-img or ImageMagick to convert first page
* 4. **File Discovery**: Locate generated image (handles various naming patterns)
* 5. **Optimization**: Convert format and detect dimensions
* 6. **Result Packaging**: Return success with image path and metadata
*
* Error Handling:
* Each stage reports specific errors via PdfConversionResult. Common failures:
* - File not found or inaccessible
* - Invalid or corrupted PDF format
* - CLI tool execution failure
* - Output file not found after conversion
* - Image optimization failure
*
* All errors are captured and returned in result.error, never thrown as exceptions.
*
* Performance:
* - First-page-only conversion is fast (~1-2 seconds typical)
* - Uses CLI tools for native-quality rendering
* - Temporary files cleaned up automatically by caller
* - Suitable for batch processing multiple PDFs
*
* @param pdfPath - Absolute path to PDF file to convert
* @param outputDir - Absolute path to output directory for generated image
* @param options - Optional conversion configuration (defaults to HiDPI quality)
* @returns Promise resolving to conversion result with success status and metadata
*
* @example
* ```typescript
* // Basic conversion with defaults
* const converter = PdfToImageConverter.getInstance(this.plugin);
* const result = await converter.convertFirstPageToImage(
* '/vault/attachments/report.pdf',
* '/vault/.obsidian/plugins/typst-pdf-export/temp-images'
* );
*
* if (result.success) {
* console.log('Image:', result.imagePath);
* console.log('Size:', result.imageDimensions.width, 'x', result.imageDimensions.height);
* // Use result.imagePath in Typst: #image("path")
* } else {
* new Notice(`PDF conversion failed: ${result.error}`);
* }
* ```
*
* @example
* ```typescript
* // High-quality conversion for print
* const result = await converter.convertFirstPageToImage(
* pdfPath,
* outputDir,
* {
* scale: 3.0,
* maxWidth: 1600,
* maxHeight: 1200,
* format: 'png'
* }
* );
* ```
*
* @example
* ```typescript
* // Batch convert multiple PDFs
* const converter = PdfToImageConverter.getInstance(this.plugin);
* const pdfPaths = ['/vault/doc1.pdf', '/vault/doc2.pdf', '/vault/doc3.pdf'];
*
* for (const pdfPath of pdfPaths) {
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
* if (result.success) {
* console.log(`✓ ${path.basename(pdfPath)}`);
* } else {
* console.error(`✗ ${path.basename(pdfPath)}: ${result.error}`);
* }
* }
* ```
*/
public async convertFirstPageToImage(
pdfPath: string,
outputDir: string,
pdfPath: string,
outputDir: string,
options: PdfConversionOptions = {}
): Promise<PdfConversionResult> {
try {
@@ -180,14 +501,124 @@ export class PdfToImageConverter {
}
/**
* Check if a file is a valid PDF
* Validates whether a file is a readable PDF document.
*
* This utility method provides quick PDF validation before attempting conversion.
* It checks both file existence and PDF format validity by delegating to PdfProcessor.
*
* Validation includes:
* - File exists and is accessible
* - File has PDF magic bytes (header signature)
* - File is not corrupted or truncated
*
* Use this for pre-flight checks before expensive conversion operations or to
* filter PDF files from mixed file lists.
*
* @param filePath - Absolute path to file to validate
* @returns Promise resolving to true if file is valid PDF, false otherwise
*
* @example
* ```typescript
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* // Validate before conversion
* if (await converter.isValidPdf(pdfPath)) {
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
* // Process result...
* } else {
* new Notice('Not a valid PDF file');
* }
* ```
*
* @example
* ```typescript
* // Filter PDF files from attachments
* const attachments = app.vault.getFiles();
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* const validPdfs = [];
* for (const file of attachments) {
* if (file.extension === 'pdf' && await converter.isValidPdf(file.path)) {
* validPdfs.push(file);
* }
* }
* console.log(`Found ${validPdfs.length} valid PDFs`);
* ```
*/
public async isValidPdf(filePath: string): Promise<boolean> {
return await PdfProcessor.isValidPdf(filePath);
}
/**
* Get PDF metadata (page count, dimensions, etc.)
* Retrieves metadata about a PDF file without converting it.
*
* This method extracts essential PDF information including page count and page
* dimensions. It's useful for:
* - Determining if multi-page conversion is needed
* - Checking PDF dimensions before conversion
* - Pre-flight validation with detailed error messages
* - UI display of PDF properties
*
* The method delegates to PdfProcessor for actual metadata extraction. On success,
* returns page count and first page dimensions. On failure, returns error details.
*
* Note: Dimensions are for the first page only. Multi-page PDFs may have varying
* page sizes, but this implementation focuses on first-page conversion.
*
* @param filePath - Absolute path to PDF file
* @returns Promise resolving to metadata object with page count, dimensions, and success status
*
* @example
* ```typescript
* const converter = PdfToImageConverter.getInstance(this.plugin);
* const info = await converter.getPdfInfo(pdfPath);
*
* if (info.success) {
* console.log(`Pages: ${info.pageCount}`);
* console.log(`Size: ${info.dimensions.width}x${info.dimensions.height}px`);
*
* if (info.pageCount > 1) {
* new Notice(`PDF has ${info.pageCount} pages - only first will be converted`);
* }
* } else {
* console.error('Failed to read PDF info:', info.error);
* }
* ```
*
* @example
* ```typescript
* // Adjust conversion options based on PDF dimensions
* const info = await converter.getPdfInfo(pdfPath);
*
* if (info.success) {
* const isLandscape = info.dimensions.width > info.dimensions.height;
*
* const options: PdfConversionOptions = {
* maxWidth: isLandscape ? 1200 : 800,
* maxHeight: isLandscape ? 800 : 1200
* };
*
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir, options);
* }
* ```
*
* @example
* ```typescript
* // Check PDF before showing conversion dialog
* const info = await converter.getPdfInfo(pdfPath);
*
* if (!info.success) {
* new Notice(`Cannot process PDF: ${info.error}`);
* return;
* }
*
* // Show dialog with PDF details
* new PDFConversionModal(
* this.app,
* pdfPath,
* `${info.pageCount} pages, ${info.dimensions.width}x${info.dimensions.height}px`
* ).open();
* ```
*/
public async getPdfInfo(filePath: string): Promise<{
pageCount: number;
+244 -9
View File
@@ -1,6 +1,50 @@
/**
* Pandoc Command Builder
* Handles construction of Pandoc command-line arguments for Typst PDF conversion
* Command-line argument builder for Pandoc-to-Typst PDF conversion.
*
* This module constructs complete Pandoc command-line arguments for converting
* preprocessed Markdown to Typst format, which is then compiled to PDF by the
* Typst engine. It orchestrates several key aspects of the conversion:
* - Input/output path specification
* - Typst PDF engine configuration
* - Template loading and variable passing
* - Resource path resolution for embedded media
* - Diagnostic and error reporting options
*
* Key Features:
* - Modular argument construction via specialized methods
* - Template system with universal wrapper for dynamic template selection
* - Comprehensive variable mapping from export config to Typst variables
* - Smart resource path resolution for Obsidian attachments
* - Enhanced diagnostics for debugging conversion failures
* - Safe path handling with automatic quoting via spawn
*
* Architecture:
* The builder delegates to specialized components:
* - **TypstVariableMapper**: Maps export config to Typst variables
* - **ResourcePathResolver**: Finds attachment directories in vault
* - **PathResolver**: Resolves executable paths with fallback logic
* - **PathUtils**: Obsidian vault file system operations
*
* Command Structure:
* ```bash
* pandoc input.md \
* -o output.pdf \
* --from markdown-smart \
* --pdf-engine=typst \
* --standalone \
* --no-citeproc \
* --embed-resources \
* --resource-path /vault/attachments \
* --template universal-wrapper.typ \
* -V template_path=default.typ \
* -V page_width=210mm \
* ... (more variables)
* --pdf-engine-opt --diagnostic-format=short
* ```
*
* The universal wrapper template receives the actual template path as a variable,
* allowing dynamic template selection without requiring separate wrapper files
* for each template.
*/
import * as path from 'path';
@@ -11,12 +55,58 @@ import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils';
/**
* Builder for Pandoc command-line arguments in the Markdown → Typst → PDF pipeline.
*
* This class encapsulates the complex logic for constructing Pandoc command arguments
* that correctly configure Typst PDF generation. It manages several interdependent
* concerns including template loading, variable mapping, resource path resolution,
* and diagnostic configuration.
*
* Design Philosophy:
* - Single responsibility: Only builds command arguments, doesn't execute
* - Modular construction: Each argument category handled by dedicated method
* - Dependency injection: Receives plugin reference for configuration access
* - Async-safe: Handles file system checks without blocking
*
* The builder pattern allows testing argument construction independently from
* command execution, and makes it easy to modify argument logic without touching
* the execution layer.
*
* @example
* ```typescript
* const builder = new PandocCommandBuilder(this.plugin);
*
* const args = await builder.buildPandocArgs(
* '/vault/note.md',
* '/vault/exports/note.pdf',
* {
* template: 'default',
* vaultBasePath: '/vault',
* pluginDir: '/vault/.obsidian/plugins/typst-pdf-export',
* typstPath: 'typst',
* exportConfig: { pageSize: 'a4', orientation: 'portrait' }
* }
* );
*
* // Execute with spawn
* spawn('pandoc', args);
* ```
*/
export class PandocCommandBuilder {
private plugin: obsidianTypstPDFExport;
private variableMapper: TypstVariableMapper;
private resourcePathResolver: ResourcePathResolver;
private pathResolver: PathResolver;
/**
* Creates a new PandocCommandBuilder.
*
* Initializes all dependent components (variable mapper, resource path resolver,
* path resolver) that the builder needs to construct complete command arguments.
*
* @param plugin - Plugin instance for accessing configuration and vault operations
*/
constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin;
this.variableMapper = new TypstVariableMapper(plugin);
@@ -25,7 +115,72 @@ export class PandocCommandBuilder {
}
/**
* Build pandoc command-line arguments
* Builds complete Pandoc command-line arguments for Typst PDF generation.
*
* This is the primary interface method that orchestrates all argument construction.
* It delegates to specialized private methods for each category of arguments,
* ensuring proper ordering and completeness.
*
* Argument Order (important for Pandoc):
* 1. Input file path
* 2. Output file specification (-o)
* 3. Input format (--from markdown-smart)
* 4. PDF engine configuration (--pdf-engine=typst)
* 5. Standalone mode (--standalone)
* 6. Citation processing (--no-citeproc)
* 7. Resource embedding (--embed-resources)
* 8. Resource paths (--resource-path, multiple)
* 9. Template configuration (--template, -V template_path)
* 10. Typst variables (-V key=value, multiple)
* 11. Engine options (--pdf-engine-opt, multiple)
* 12. Diagnostics (--pdf-engine-opt --diagnostic-format=short)
*
* Side Effects:
* - Changes process.cwd() if vaultBasePath is provided
* - Reads file system to verify template existence
* - May throw Error if universal wrapper template not found
*
* @param inputPath - Absolute path to preprocessed Markdown input file
* @param outputPath - Absolute path for generated PDF output file
* @param pandocOptions - Configuration for Pandoc execution and Typst variables
* @returns Promise resolving to array of command-line arguments for Pandoc
*
* @throws {Error} If universal wrapper template not found
*
* @example
* ```typescript
* // Basic usage
* const builder = new PandocCommandBuilder(this.plugin);
* const args = await builder.buildPandocArgs(
* '/vault/preprocessed.md',
* '/vault/output.pdf',
* {
* template: 'modern',
* vaultBasePath: '/vault',
* typstPath: '/usr/local/bin/typst',
* exportConfig: {
* pageSize: 'letter',
* margins: { top: '1in', bottom: '1in' }
* }
* }
* );
* console.log('Pandoc args:', args.join(' '));
* ```
*
* @example
* ```typescript
* // With custom engine options
* const args = await builder.buildPandocArgs(
* inputPath,
* outputPath,
* {
* template: 'article',
* typstSettings: {
* engineOptions: ['--root', '/custom/root', '--font-path', '/fonts']
* }
* }
* );
* ```
*/
async buildPandocArgs(inputPath: string, outputPath: string, pandocOptions: PandocOptions): Promise<string[]> {
const args: string[] = [];
@@ -78,7 +233,20 @@ export class PandocCommandBuilder {
}
/**
* Add resource paths for attachment resolution
* Adds resource paths to command arguments for Obsidian attachment resolution.
*
* This method enables Pandoc to find embedded images, PDFs, and other attachments
* referenced in the markdown content. It uses ResourcePathResolver to discover all
* attachment directories in the vault and adds them via --resource-path flags.
*
* Multiple --resource-path arguments can be provided, and Pandoc searches them in
* order when resolving relative paths in the markdown. This allows attachments to
* be stored in various locations (root-level, nested folders, etc.) and still be
* found during conversion.
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including vaultBasePath for resource discovery
* @private
*/
private async addResourcePaths(args: string[], pandocOptions: PandocOptions): Promise<void> {
if (!pandocOptions.vaultBasePath) {
@@ -96,7 +264,29 @@ export class PandocCommandBuilder {
/**
* Add template configuration to pandoc arguments
* Adds template configuration using the universal wrapper pattern.
*
* This method implements the plugin's template system using a universal wrapper
* template that dynamically loads the actual template via a Typst import. This
* approach allows template selection at runtime without maintaining separate
* wrapper files for each template.
*
* Template Resolution:
* 1. Locate universal-wrapper.pandoc.typ in plugin templates directory
* 2. Verify wrapper exists (throws if missing)
* 3. Add wrapper as Pandoc --template
* 4. Add templates directory to resource paths (enables Typst imports)
* 5. Pass actual template path as template_path variable
*
* Path Handling:
* - Absolute template paths are made relative to vault root for Typst imports
* - Relative paths are passed through unchanged
* - spawn automatically handles path quoting for spaces
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including template path and plugin directory
* @throws {Error} If universal wrapper template not found
* @private
*/
private async addTemplateConfiguration(args: string[], pandocOptions: PandocOptions): Promise<void> {
// Use universal wrapper with --template and pass actual template as template_path variable
@@ -130,19 +320,52 @@ export class PandocCommandBuilder {
}
/**
* Add all Typst variables using the variable mapper
* Adds all Typst template variables mapped from export configuration.
*
* This method delegates to TypstVariableMapper to transform the export configuration
* into Typst template variables. These variables control typography, layout, margins,
* and other formatting aspects of the final PDF.
*
* Variable Mapping:
* - ExportConfig fields → Typst variable names (e.g., pageSize → page_size)
* - Plugin settings provide fallback values for missing config fields
* - Values converted to Typst-compatible formats (e.g., "2.5cm" for margins)
* - Variables passed via -V key=value arguments to Pandoc
*
* Example Variables:
* - page_width, page_height: Page dimensions
* - margin_top, margin_bottom, margin_left, margin_right: Margins
* - body_font, heading_font, monospace_font: Typography
* - font_size: Base font size
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including exportConfig and plugin settings
* @private
*/
private addTypstVariables(args: string[], pandocOptions: PandocOptions): void {
// Map all variables (ExportConfig + plugin settings fallbacks) using the variable mapper
const typstVariables = this.variableMapper.mapAllVariablesToTypst(pandocOptions);
// Convert to pandoc arguments and add to args
const variableArgs = this.variableMapper.convertVariablesToPandocArgs(typstVariables);
args.push(...variableArgs);
}
/**
* Add Typst engine options to pandoc arguments
* Adds custom Typst engine options for advanced configuration.
*
* This method passes additional command-line options directly to the Typst engine
* via Pandoc's --pdf-engine-opt flag. These options can override Typst's default
* behavior for specific use cases.
*
* Common Engine Options:
* - --root /path: Set Typst root directory for imports
* - --font-path /fonts: Add custom font directories
* - --input key=value: Pass additional variables to Typst
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including typstSettings.engineOptions
* @private
*/
private addTypstEngineOptions(args: string[], pandocOptions: PandocOptions): void {
if (pandocOptions.typstSettings?.engineOptions) {
@@ -153,7 +376,19 @@ export class PandocCommandBuilder {
}
/**
* Add enhanced Typst diagnostics for better error reporting
* Adds Typst diagnostic configuration for enhanced error reporting.
*
* This method enables short-format diagnostics in Typst, which provide cleaner
* and more readable error messages when compilation fails. The short format is
* easier to parse and present to users compared to the verbose default format.
*
* Diagnostic Format:
* - Short: Concise error messages with file:line:column locations
* - Default (verbose): Detailed multi-line error reports with context
*
* @param args - Command arguments array to append to
* @param pandocOptions - Pandoc options (currently unused but kept for consistency)
* @private
*/
private addTypstDiagnostics(args: string[], pandocOptions: PandocOptions): void {
// Add Typst diagnostic options for better error reporting
+258 -17
View File
@@ -4,26 +4,148 @@ import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main';
/**
* Handles pandoc process execution, monitoring, and error parsing.
* Manages the spawning and lifecycle of pandoc processes for document conversion.
* Process executor for Pandoc command-line conversions with progress monitoring.
*
* This class manages the complete lifecycle of Pandoc subprocess execution including:
* - Process spawning with augmented PATH and working directory configuration
* - Real-time stdout/stderr streaming and parsing
* - Progress monitoring and user feedback via callbacks
* - Timeout enforcement to prevent hanging conversions
* - Error extraction and formatting for user-friendly messages
* - Graceful process termination and cleanup
*
* Key Features:
* - **Augmented PATH**: Ensures Pandoc and Typst are found in common locations
* - **Working Directory**: Sets vault root as CWD for proper attachment resolution
* - **Progress Callbacks**: Updates UI during conversion stages
* - **Timeout Protection**: Kills hung processes after configurable duration
* - **Error Parsing**: Extracts meaningful error messages from raw output
* - **Promise-based API**: Clean async interface for callers
*
* Process Lifecycle:
* 1. Resolve Pandoc executable path with PathResolver
* 2. Determine working directory (vault root preferred)
* 3. Augment PATH environment with common binary locations
* 4. Spawn Pandoc process with stdio piping
* 5. Set up timeout handler for hanging processes
* 6. Stream and parse stdout/stderr for progress
* 7. Handle process completion or error
* 8. Clean up timeout handler and resolve promise
*
* The executor is designed to work reliably across different environments (macOS,
* Linux, Windows) by handling path resolution and environment variables carefully.
*
* @example
* ```typescript
* const executor = new PandocExecutor(this.plugin);
*
* const result = await executor.executePandoc(
* ['input.md', '-o', 'output.pdf', '--pdf-engine=typst'],
* {
* pandocPath: 'pandoc',
* vaultBasePath: '/vault',
* timeout: 120000
* },
* (message, progress) => {
* console.log(`${progress}%: ${message}`);
* }
* );
*
* if (result.success) {
* console.log('Conversion succeeded');
* } else {
* console.error('Error:', result.error);
* }
* ```
*/
export class PandocExecutor {
private pathResolver: PathResolver;
/**
* Creates a new PandocExecutor.
*
* @param plugin - Plugin instance for accessing PathResolver configuration
*/
constructor(plugin: obsidianTypstPDFExport) {
this.pathResolver = new PathResolver(plugin);
}
/**
* Execute pandoc process with the given arguments
* @param args Command line arguments for pandoc
* @param pandocOptions Configuration options including paths and timeout
* @param progressCallback Optional callback for progress updates
* @returns Promise resolving to conversion result
* Executes Pandoc process with comprehensive monitoring and error handling.
*
* This is the primary execution method that spawns a Pandoc subprocess, monitors
* its progress, enforces timeouts, and returns a detailed result. The method is
* fully asynchronous and promise-based for clean integration with async workflows.
*
* Process Configuration:
* - **Executable Resolution**: Uses PathResolver to find Pandoc (handles custom paths)
* - **Working Directory**: Sets vault root for relative path resolution
* - **PATH Augmentation**: Adds common binary locations to ensure tool discovery
* - **Stdio Piping**: Captures stdout/stderr for progress parsing and error reporting
*
* Progress Monitoring:
* The progressCallback receives updates at various stages:
* - 45%: Reading input (parsing phase)
* - 60%: Processing document (conversion phase)
* - 75%: Generating output (template application)
* - 85%: Running Typst engine (PDF generation)
* - 90%: Complete
*
* Timeout Handling:
* - Default: 60 seconds (configurable via pandocOptions.timeout)
* - Process killed with SIGTERM on timeout
* - Returns error result with timeout message
* - Prevents hung processes from blocking export queue
*
* Error Handling:
* - Non-zero exit code → Parses stderr for meaningful error
* - Process spawn failure → Returns startup error
* - Timeout → Returns timeout error
* - All errors include diagnostic context for debugging
*
* @param args - Complete command-line arguments for Pandoc (from PandocCommandBuilder)
* @param pandocOptions - Configuration including paths, timeout, and working directory
* @param progressCallback - Optional callback for real-time progress updates
* @returns Promise resolving to ConversionResult with success status and output
*
* @example
* ```typescript
* // Basic execution
* const executor = new PandocExecutor(this.plugin);
* const result = await executor.executePandoc(args, options);
*
* if (!result.success) {
* new Notice(`Conversion failed: ${result.error}`);
* }
* ```
*
* @example
* ```typescript
* // With progress callback for UI updates
* const result = await executor.executePandoc(
* args,
* options,
* (message, progress) => {
* progressModal.update(message, progress);
* }
* );
* ```
*
* @example
* ```typescript
* // With custom timeout for large documents
* const result = await executor.executePandoc(
* args,
* {
* ...options,
* timeout: 300000 // 5 minutes for large PDF
* }
* );
* ```
*/
async executePandoc(
args: string[],
pandocOptions: PandocOptions,
args: string[],
pandocOptions: PandocOptions,
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
return new Promise((resolve) => {
@@ -122,9 +244,59 @@ export class PandocExecutor {
}
/**
* Parse progress information from pandoc output and update progress callback
* @param output Raw output from pandoc stderr
* @param progressCallback Optional callback to update progress
* Parses Pandoc's stderr output to detect conversion progress and update the UI.
*
* This method implements heuristic progress detection by scanning stderr output for
* specific keywords that indicate which phase of the conversion pipeline is active.
* While Pandoc doesn't provide structured progress events, certain log patterns
* reliably appear during specific phases.
*
* Detection Heuristics:
* - **"parsing" or "reading"** → 45% (Input parsing phase)
* - Pandoc is reading and parsing the markdown input
* - AST construction is underway
* - **"writing" or "generating"** → 75% (Output generation phase)
* - Pandoc is generating Typst markup from the AST
* - Template application is occurring
* - **"typst"** → 85% (PDF generation phase)
* - Typst engine is compiling to PDF
* - Final rendering in progress
*
* Progress updates are only sent if a progressCallback was provided. Multiple
* matches to the same pattern won't duplicate callbacks - only one update per
* phase is typical.
*
* Enhancement Opportunities:
* - Parse Typst's own progress output for more granular PDF generation updates
* - Detect specific error keywords to provide early warning
* - Track file processing count for multi-file conversions
*
* @param output - Raw text from Pandoc's stderr stream
* @param progressCallback - Optional callback to invoke with progress updates
* @private
*
* @example
* ```typescript
* // Typical stderr patterns that trigger updates:
* parseProgressFromOutput('[INFO] Parsing markdown...', callback);
* // → Triggers: callback('Reading input...', 45)
*
* parseProgressFromOutput('[INFO] Writing typst output...', callback);
* // → Triggers: callback('Generating output...', 75)
*
* parseProgressFromOutput('Running typst compile...', callback);
* // → Triggers: callback('Running Typst engine...', 85)
* ```
*
* @example
* ```typescript
* // Used in stderr stream handler:
* pandocProcess.stderr?.on('data', (data: Buffer) => {
* const output = data.toString();
* stderr += output;
* this.parseProgressFromOutput(output, progressCallback);
* });
* ```
*/
private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void {
// Basic progress parsing - could be enhanced based on pandoc output patterns
@@ -138,10 +310,79 @@ export class PandocExecutor {
}
/**
* Extract meaningful error messages from pandoc output
* @param stderr Standard error output from pandoc
* @param stdout Standard output from pandoc
* @returns Formatted error message
* Extracts meaningful, user-friendly error messages from Pandoc's raw output.
*
* This method implements a multi-tier fallback strategy to find the most relevant
* error information from Pandoc's stderr and stdout streams. Pandoc and Typst can
* produce verbose diagnostic output, so this method filters to find the most
* actionable error message for users.
*
* Extraction Strategy (in priority order):
* 1. **Pattern Matching**: Scan all output for common error indicators
* - Case-insensitive "error:" matches most Pandoc/Typst errors
* - Case-sensitive "Error:" catches Python and other tool errors
* - "failed" indicates operation failures
* - "Fatal" indicates critical termination errors
* - "pandoc:" catches Pandoc-specific diagnostic messages
*
* 2. **First Stderr Line**: If no pattern matches, use first non-empty stderr line
* - Assumes most important error appears early in stderr
* - Filters out empty lines for cleaner messages
*
* 3. **Generic Fallback**: If no stderr content, return generic error
* - Indicates process failure with no diagnostic output
* - Should be rare in practice
*
* Error Pattern Examples:
* - `Error: Could not find template: custom.typ` (Pandoc template error)
* - `pandoc: Cannot find file input.md` (File not found)
* - `error: font not found: "NonexistentFont"` (Typst font error)
* - `Fatal error: out of memory` (Resource exhaustion)
* - `failed to compile: syntax error at line 42` (Typst compilation error)
*
* The extracted message is displayed directly to users in error notices, so it
* should be concise and actionable without requiring interpretation.
*
* @param stderr - Complete stderr output captured from Pandoc process
* @param stdout - Complete stdout output captured from Pandoc process
* @returns User-friendly error message suitable for display in Notice
* @private
*
* @example
* ```typescript
* // Template not found error
* const stderr = "Error: Could not find template: custom.typ\nUsage: pandoc...";
* const error = this.extractErrorMessage(stderr, '');
* // Returns: "Error: Could not find template: custom.typ"
* ```
*
* @example
* ```typescript
* // Typst compilation error
* const stderr = "typst compile failed\nerror: undefined function `foo`\n at line 15";
* const error = this.extractErrorMessage(stderr, '');
* // Returns: "error: undefined function `foo`"
* ```
*
* @example
* ```typescript
* // Generic failure with no specific error
* const stderr = "";
* const stdout = "Some non-error output";
* const error = this.extractErrorMessage(stderr, stdout);
* // Returns: "Unknown error occurred during conversion"
* ```
*
* @example
* ```typescript
* // Used in process close handler:
* pandocProcess.on('close', (code: number | null) => {
* if (!success) {
* result.error = this.extractErrorMessage(stderr, stdout);
* new Notice(`Export failed: ${result.error}`);
* }
* });
* ```
*/
private extractErrorMessage(stderr: string, stdout: string): string {
// Look for common error patterns
@@ -154,7 +395,7 @@ export class PandocExecutor {
];
const allOutput = (stderr + '\n' + stdout).split('\n');
for (const line of allOutput) {
for (const pattern of errorPatterns) {
if (pattern.test(line)) {
+234 -5
View File
@@ -1,11 +1,29 @@
/**
* Dependency checking utilities for Obsidian Typst PDF Export plugin
* Dependency checking utilities for Obsidian Typst PDF Export plugin.
*
* This module provides comprehensive dependency checking for the three external
* tools required by the plugin:
* - Pandoc: Converts Markdown to Typst markup
* - Typst: Compiles Typst markup to PDF
* - ImageMagick: Handles PDF-to-image conversion for embedded PDFs (optional)
*
* The module offers both async and sync checking methods, automatic startup
* validation, and user-facing status display functionality.
*/
import { DEPENDENCY_CONSTANTS } from './constants';
import { ExportErrorHandler } from './ExportErrorHandler';
import { ExecutableChecker, DependencyInfo } from './ExecutableChecker';
/**
* Complete result of a dependency check operation.
*
* @property pandoc - Detailed information about Pandoc installation
* @property typst - Detailed information about Typst installation
* @property imagemagick - Detailed information about ImageMagick installation
* @property allAvailable - True if all dependencies are available
* @property missingDependencies - Array of names of missing dependencies
*/
export interface DependencyCheckResult {
pandoc: DependencyInfo;
typst: DependencyInfo;
@@ -14,6 +32,46 @@ export interface DependencyCheckResult {
missingDependencies: string[];
}
/**
* Utilities for checking external dependency availability and versions.
*
* This class provides static methods for validating that Pandoc, Typst, and
* ImageMagick are properly installed and accessible. It supports both async
* and sync operations, configurable executable paths, and user notifications.
*
* Key features:
* - Comprehensive async checking with version detection
* - Fast sync checking for startup validation
* - User-facing status display with formatted output
* - Silent background checking with error notifications
* - Support for custom executable paths and search directories
*
* @example
* ```typescript
* // Comprehensive check with version information
* const result = await DependencyChecker.checkAllDependencies(
* settings.pandocPath,
* settings.typstPath,
* settings.imagemagickPath,
* settings.additionalPaths
* );
*
* if (!result.allAvailable) {
* console.error('Missing:', result.missingDependencies);
* } else {
* console.log(`Pandoc ${result.pandoc.version} found`);
* }
*
* // Quick startup check
* const missing = DependencyChecker.checkDependenciesSync(
* settings.pandocPath,
* settings.typstPath
* );
* if (missing.length > 0) {
* console.error('Missing dependencies:', missing);
* }
* ```
*/
export class DependencyChecker {
@@ -23,7 +81,51 @@ export class DependencyChecker {
/**
* Comprehensive dependency check (async) - returns detailed information
* Performs comprehensive dependency checking with version detection (async).
*
* This method checks all three required external tools (Pandoc, Typst, and
* ImageMagick) in parallel for maximum efficiency. It resolves executable
* paths, verifies availability, and extracts version information using regex
* patterns.
*
* The method supports custom executable paths from user settings and falls
* back to searching system PATH if paths are not specified. Additional search
* directories can be provided to help locate tools in non-standard locations.
*
* @param pandocPath - Optional custom path to Pandoc executable
* @param typstPath - Optional custom path to Typst executable
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
* @param additionalPaths - Additional directories to search for executables
* @returns Detailed dependency check result including version information
*
* @example
* ```typescript
* // Check with default paths (searches system PATH)
* const result = await DependencyChecker.checkAllDependencies();
* if (result.allAvailable) {
* console.log('All dependencies found!');
* console.log(`Pandoc: ${result.pandoc.version}`);
* console.log(`Typst: ${result.typst.version}`);
* }
*
* // Check with custom paths and additional search directories
* const result = await DependencyChecker.checkAllDependencies(
* '/usr/local/bin/pandoc',
* '/opt/typst/bin/typst',
* '/usr/bin/convert',
* ['/opt/local/bin', '/usr/local/opt/bin']
* );
*
* // Handle missing dependencies
* if (!result.allAvailable) {
* console.error('Missing:', result.missingDependencies.join(', '));
* result.missingDependencies.forEach(name => {
* const dep = name === 'Pandoc' ? result.pandoc :
* name === 'Typst' ? result.typst : result.imagemagick;
* console.error(`${name} not found at: ${dep.executablePath}`);
* });
* }
* ```
*/
public static async checkAllDependencies(
pandocPath?: string,
@@ -58,7 +160,52 @@ export class DependencyChecker {
}
/**
* Quick dependency check (synchronous) - returns list of missing dependencies
* Performs fast synchronous dependency checking without version detection.
*
* This is a simplified version of checkAllDependencies that only checks if
* executables can be run successfully (exit code 0), without extracting version
* information. It's designed for scenarios where async operations are not
* possible (e.g., plugin initialization) or when only availability matters.
*
* The method checks all three tools sequentially and returns a list of missing
* dependency names. Empty array indicates all dependencies are available.
*
* @param pandocPath - Optional custom path to Pandoc executable
* @param typstPath - Optional custom path to Typst executable
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
* @param additionalPaths - Additional directories to search for executables
* @returns Array of missing dependency names (empty if all available)
*
* @example
* ```typescript
* // Quick startup check in plugin onload()
* const missing = DependencyChecker.checkDependenciesSync(
* this.settings.pandocPath,
* this.settings.typstPath,
* this.settings.imagemagickPath
* );
*
* if (missing.length > 0) {
* new Notice(`Missing dependencies: ${missing.join(', ')}`);
* return;
* }
*
* // Check with additional search paths
* const missing = DependencyChecker.checkDependenciesSync(
* undefined, // Use default Pandoc
* undefined, // Use default Typst
* undefined, // Use default ImageMagick
* ['/opt/local/bin', '~/.local/bin']
* );
*
* // React based on specific missing tools
* if (missing.includes('Pandoc')) {
* console.error('Pandoc is required for Markdown conversion');
* }
* if (missing.includes('Typst')) {
* console.error('Typst is required for PDF generation');
* }
* ```
*/
public static checkDependenciesSync(
pandocPath?: string,
@@ -87,7 +234,47 @@ export class DependencyChecker {
}
/**
* Show dependency status modal
* Displays dependency status in a user-facing notice with version information.
*
* This method performs a comprehensive dependency check and displays the results
* in an Obsidian notice modal. The notice includes:
* - Status of each dependency (version or "Not found")
* - Overall availability message
* - Installation instructions if dependencies are missing
*
* The notice is displayed for 12 seconds to give users time to read the detailed
* information. This method is typically called from the plugin's settings or via
* a command palette action.
*
* @param pandocPath - Optional custom path to Pandoc executable
* @param typstPath - Optional custom path to Typst executable
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
* @param additionalPaths - Additional directories to search for executables
* @returns Promise that resolves when the status has been displayed
*
* @example
* ```typescript
* // Display status from settings panel
* await DependencyChecker.showDependencyStatus(
* this.plugin.settings.pandocPath,
* this.plugin.settings.typstPath,
* this.plugin.settings.imagemagickPath
* );
*
* // Display status via command palette
* this.addCommand({
* id: 'check-dependencies',
* name: 'Check Dependencies',
* callback: async () => {
* await DependencyChecker.showDependencyStatus(
* this.settings.pandocPath,
* this.settings.typstPath,
* this.settings.imagemagickPath,
* this.settings.additionalPaths
* );
* }
* });
* ```
*/
public static async showDependencyStatus(
pandocPath?: string,
@@ -117,7 +304,49 @@ ${dependencyResult.allAvailable
}
/**
* Check dependencies silently on startup and show notice if missing
* Performs silent dependency checking on plugin startup with error notifications.
*
* This method is designed for plugin initialization and performs a fast synchronous
* check of all dependencies. It only displays a notice if dependencies are missing,
* keeping the user experience clean when everything is working correctly.
*
* If dependencies are missing, a notice is shown for 8 seconds directing the user
* to run the full "Check Dependencies" command for detailed information. If an
* error occurs during checking, it's handled gracefully via ExportErrorHandler.
*
* This method should be called early in the plugin lifecycle (typically in onload)
* to ensure users are aware of missing dependencies before attempting exports.
*
* @param pandocPath - Optional custom path to Pandoc executable
* @param typstPath - Optional custom path to Typst executable
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
* @param additionalPaths - Additional directories to search for executables
* @returns Promise that resolves when the check is complete
*
* @example
* ```typescript
* // Call during plugin initialization
* export default class MyPlugin extends Plugin {
* async onload() {
* await this.loadSettings();
*
* // Silent startup check - only shows notice if problems exist
* await DependencyChecker.checkDependenciesAsync(
* this.settings.pandocPath,
* this.settings.typstPath,
* this.settings.imagemagickPath,
* this.settings.additionalPaths
* );
*
* // Continue with plugin initialization
* this.registerCommands();
* }
* }
*
* // User will see a notice only if dependencies are missing:
* // "Typst PDF Export: Missing dependencies: Pandoc, Typst.
* // Run 'Check Dependencies' command for details."
* ```
*/
public static async checkDependenciesAsync(
pandocPath?: string,
+175 -10
View File
@@ -1,10 +1,24 @@
/**
* Executable checking utilities for Obsidian Typst PDF Export plugin
* Handles path resolution, version detection, and availability checking for external executables
* Executable checking utilities for Obsidian Typst PDF Export plugin.
*
* This module provides comprehensive utilities for checking external executable
* availability and versions. It handles:
* - Path resolution with support for system PATH and additional paths
* - Version detection using configurable regex patterns
* - Both async and sync operations for different use cases
* - Cross-platform path handling (Unix and Windows)
*/
import { DEPENDENCY_CONSTANTS } from './constants';
/**
* Information about a checked dependency executable.
*
* @property name - Human-readable name of the dependency (e.g., "Pandoc")
* @property version - Detected version string, or null if unavailable
* @property isAvailable - Whether the executable was found and executed successfully
* @property executablePath - The resolved path to the executable
*/
export interface DependencyInfo {
name: string;
version: string | null;
@@ -13,12 +27,55 @@ export interface DependencyInfo {
}
/**
* Utilities for checking executable availability and versions
* Utilities for checking executable availability and versions.
*
* This class provides static methods for:
* - Resolving executable paths from user input or system PATH
* - Augmenting PATH with common system directories
* - Checking if executables are available
* - Detecting executable versions using regex patterns
*
* All methods support additional search paths to extend the default system PATH,
* ensuring executables can be found in non-standard locations.
*
* @example
* ```typescript
* // Resolve path to pandoc executable
* const pandocPath = await ExecutableChecker.resolveExecutablePath(
* settings.pandocPath,
* 'pandoc',
* settings.additionalPaths
* );
*
* // Check if pandoc is available and get version
* const info = await ExecutableChecker.checkDependency(
* 'Pandoc',
* pandocPath,
* '--version',
* /pandoc (\d+\.\d+(?:\.\d+)?)/
* );
*
* if (info.isAvailable) {
* console.log(`Pandoc ${info.version} found at ${info.executablePath}`);
* }
* ```
*/
export class ExecutableChecker {
/**
* Build an augmented PATH that includes common system paths and additional paths
* Builds an augmented PATH string that includes common system paths and additional paths.
*
* This method combines the current process PATH with:
* 1. Home-relative paths (e.g., ~/.local/bin, ~/.cargo/bin)
* 2. Common absolute paths (e.g., /usr/local/bin, /opt/homebrew/bin)
* 3. User-provided additional paths
*
* The resulting PATH helps find executables in non-standard locations that
* might not be in the user's shell PATH when running from Obsidian.
*
* @param additionalPaths - Optional array of additional paths to include
* @returns The augmented PATH string with all paths separated by colons
* @private
*/
private static getAugmentedPath(additionalPaths: string[] = []): string {
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
@@ -35,7 +92,15 @@ export class ExecutableChecker {
}
/**
* Build an augmented environment with extended PATH
* Builds an augmented environment object with extended PATH.
*
* Creates a new environment object that inherits all current process environment
* variables but with an augmented PATH that includes common system directories
* and any additional paths specified.
*
* @param additionalPaths - Optional array of additional paths to include in PATH
* @returns Environment object suitable for child_process spawn/exec
* @private
*/
private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
return {
@@ -45,7 +110,22 @@ export class ExecutableChecker {
}
/**
* Try to find an executable using which command
* Attempts to find an executable's full path using the `which` command.
*
* This method spawns a `which` subprocess with an augmented PATH to locate
* the executable. It's more reliable than simple PATH searches as it uses
* the system's own executable resolution logic.
*
* @param executableName - Name of the executable to find (e.g., 'pandoc')
* @param additionalPaths - Optional additional paths to search
* @returns The full path to the executable, or null if not found
* @private
*
* @example
* ```typescript
* const pandocPath = await findExecutableWithWhich('pandoc', ['/opt/local/bin']);
* // Returns: '/usr/local/bin/pandoc' or null
* ```
*/
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
const { spawn } = require('child_process');
@@ -91,7 +171,35 @@ export class ExecutableChecker {
}
/**
* Resolve executable path - async version
* Resolves an executable path from user input or system PATH (async version).
*
* Resolution logic:
* 1. If userPath contains a '/', treat it as an absolute/relative path and use as-is
* 2. If userPath is just a name or empty, search for the executable using `which`
* 3. If `which` fails, fall back to the executable name (relies on runtime PATH)
*
* This method is useful for allowing users to specify either full paths or just
* executable names in plugin settings.
*
* @param userPath - User-provided path or executable name (can be undefined/empty)
* @param defaultName - Default executable name to use if userPath is empty
* @param additionalPaths - Additional directories to search for the executable
* @returns Resolved path to use for spawning the executable
*
* @example
* ```typescript
* // User provided full path
* const path1 = await resolveExecutablePath('/usr/local/bin/pandoc', 'pandoc');
* // Returns: '/usr/local/bin/pandoc'
*
* // User provided just name
* const path2 = await resolveExecutablePath('pandoc', 'pandoc');
* // Returns: '/usr/bin/pandoc' (found via which)
*
* // User provided nothing
* const path3 = await resolveExecutablePath('', 'typst', ['/opt/bin']);
* // Returns: '/opt/bin/typst' (found via which with additional path)
* ```
*/
public static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
// If user provided a full path (contains /), use it as-is
@@ -113,7 +221,18 @@ export class ExecutableChecker {
}
/**
* Resolve executable path - sync version
* Resolves an executable path from user input or system PATH (synchronous version).
*
* This is the synchronous counterpart to `resolveExecutablePath`. Use this when
* async operations are not possible (e.g., in constructors or sync initialization).
* The resolution logic is identical to the async version.
*
* @param userPath - User-provided path or executable name (can be undefined/empty)
* @param defaultName - Default executable name to use if userPath is empty
* @param additionalPaths - Additional directories to search for the executable
* @returns Resolved path to use for spawning the executable
*
* @see {@link resolveExecutablePath} for detailed resolution logic and examples
*/
public static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
// If user provided a full path (contains /), use it as-is
@@ -147,7 +266,37 @@ export class ExecutableChecker {
}
/**
* Check if a dependency is available and get its version - async version
* Checks if a dependency executable is available and extracts its version (async version).
*
* This method:
* 1. Spawns the executable with the version command (e.g., '--version')
* 2. Captures stdout and parses version using the provided regex
* 3. Returns comprehensive dependency information
*
* Security: Uses spawn instead of exec to prevent command injection. Arguments
* are passed separately from the command.
*
* @param name - Human-readable name for the dependency (e.g., "Pandoc")
* @param executablePath - Path to the executable to check
* @param versionCommand - Command argument for version (e.g., '--version')
* @param versionRegex - Regex with capture group for version number
* @returns DependencyInfo object with availability and version information
*
* @example
* ```typescript
* const info = await ExecutableChecker.checkDependency(
* 'Pandoc',
* '/usr/bin/pandoc',
* '--version',
* /pandoc (\d+\.\d+(?:\.\d+)?)/
* );
*
* if (info.isAvailable) {
* console.log(`Found ${info.name} version ${info.version}`);
* } else {
* console.error(`${info.name} not available at ${info.executablePath}`);
* }
* ```
*/
public static async checkDependency(
name: string,
@@ -209,7 +358,23 @@ export class ExecutableChecker {
}
/**
* Quick sync check if a dependency is available
* Performs a quick synchronous check if a dependency is available.
*
* This is a simplified version of `checkDependency` that only checks if the
* executable can be run successfully (exit code 0), without parsing version
* information. Useful for fast availability checks during initialization.
*
* @param executablePath - Path to the executable to check
* @param versionCommand - Command argument to test (e.g., '--version')
* @returns True if the executable runs successfully, false otherwise
*
* @example
* ```typescript
* const pandocAvailable = ExecutableChecker.checkDependencySync('/usr/bin/pandoc', '--version');
* if (!pandocAvailable) {
* console.error('Pandoc not available');
* }
* ```
*/
public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
const { spawnSync } = require('child_process');
+321 -18
View File
@@ -1,16 +1,43 @@
/**
* Centralized error handling utilities for export operations
* Centralized error handling utilities for export operations.
*
* This module provides a unified interface for handling all types of errors that
* can occur during PDF export operations. It standardizes error logging, user
* notifications, and error message formatting across the plugin.
*
* Key features:
* - Consistent error messaging and logging
* - Batch export result tracking and reporting
* - User-facing notices with appropriate durations
* - Support for different log levels (error, warn, info)
* - Specialized handlers for different error types (dependency, processing, validation)
*/
import { Notice } from 'obsidian';
import { EXPORT_CONSTANTS } from './constants';
/**
* Result summary for batch export operations.
*
* @property successful - Number of files exported successfully
* @property failed - Number of files that failed to export
* @property errors - Array of error messages for failed exports
*/
export interface BatchExportResult {
successful: number;
failed: number;
errors: string[];
}
/**
* Structured error information for export operations.
*
* @property fileName - Optional file name where the error occurred
* @property operation - Description of the operation that failed (e.g., "Pandoc conversion")
* @property error - The error object or message
* @property shouldShowNotice - Whether to display a user-facing notice (default: false)
* @property logLevel - Logging severity level (default: 'error')
*/
export interface ExportError {
fileName?: string;
operation: string;
@@ -19,9 +46,73 @@ export interface ExportError {
logLevel?: 'error' | 'warn' | 'info';
}
/**
* Centralized error handler for all export-related errors.
*
* This class provides static utility methods for handling various error scenarios
* in the PDF export pipeline. It ensures consistent error reporting to both users
* (via Obsidian notices) and developers (via console logs).
*
* The handler supports:
* - Single and batch export error tracking
* - Context-specific error messages (dependencies, validation, processing)
* - Configurable notice durations based on error severity
* - Graceful error recovery with fallback content
*
* @example
* ```typescript
* // Handle single export error
* try {
* await exportFile(file);
* } catch (error) {
* ExportErrorHandler.handleSingleExportError(error);
* }
*
* // Track batch export results
* const batch = ExportErrorHandler.createBatchTracker();
* for (const file of files) {
* try {
* await exportFile(file);
* batch.recordSuccess();
* } catch (error) {
* batch.recordError(file.name, error);
* }
* }
* ExportErrorHandler.handleBatchResult(batch.getResult(), 'Folder export');
*
* // Handle processing error with fallback
* try {
* return await processImage(path);
* } catch (error) {
* const { fallback } = ExportErrorHandler.handleProcessingError(
* 'Image',
* path,
* error,
* '![Image unavailable]'
* );
* return fallback;
* }
* ```
*/
export class ExportErrorHandler {
/**
* Handle batch export results with consistent messaging
* Displays batch export results with user-friendly summary messages.
*
* This method analyzes batch export results and shows appropriate notices
* based on the outcome. For fully successful exports, shows a success message.
* For partial or complete failures, shows a summary with counts and logs
* detailed errors to the console.
*
* @param result - The batch export result containing success/failure counts and errors
* @param operationDescription - Description of the operation (e.g., 'Export', 'Folder export')
*
* @example
* ```typescript
* const batch = { successful: 8, failed: 2, errors: ['file1: error', 'file2: error'] };
* ExportErrorHandler.handleBatchResult(batch, 'Folder export');
* // Shows: "Folder export complete: 8 successful, 2 failed"
* // Logs detailed errors to console
* ```
*/
public static handleBatchResult(
result: BatchExportResult,
@@ -44,7 +135,36 @@ export class ExportErrorHandler {
}
/**
* Handle individual export errors consistently
* Handles individual export errors with configurable logging and notifications.
*
* This method provides flexible error handling that supports different log levels
* and optional user notices. It normalizes error messages, logs them at the
* appropriate level, and optionally displays a notice to the user.
*
* @param exportError - Structured error information including operation context
* @returns Formatted error message string suitable for collection or display
*
* @example
* ```typescript
* // Handle with notice
* const message = ExportErrorHandler.handleExportError({
* fileName: 'document.md',
* operation: 'Pandoc conversion',
* error: new Error('Invalid syntax'),
* shouldShowNotice: true,
* logLevel: 'error'
* });
* // Shows notice: "Pandoc conversion failed: Invalid syntax"
* // Returns: "document.md: Invalid syntax"
*
* // Handle silently (just logging)
* const message = ExportErrorHandler.handleExportError({
* operation: 'Image processing',
* error: 'File not found',
* logLevel: 'warn'
* });
* // Logs warning but no notice
* ```
*/
public static handleExportError(exportError: ExportError): string {
const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError;
@@ -74,7 +194,44 @@ export class ExportErrorHandler {
}
/**
* Handle processing errors for embeds and similar operations
* Handles processing errors with fallback content generation.
*
* This method is designed for operations that can gracefully degrade when errors
* occur, such as embed processing or image handling. It logs the error and returns
* both an error message and fallback content to use in place of the failed operation.
*
* The fallback content ensures exports can continue even when individual embeds or
* resources fail to process, providing a visible indication of the failure in the
* output document.
*
* @param operation - Description of the operation (e.g., 'Image', 'PDF embed')
* @param itemPath - Path to the item being processed
* @param error - The error that occurred
* @param fallbackContent - Optional custom fallback content (auto-generated if not provided)
* @returns Object with error message and fallback content to use
*
* @example
* ```typescript
* try {
* return await processWikilink(link);
* } catch (error) {
* const { fallback } = ExportErrorHandler.handleProcessingError(
* 'Wikilink',
* '[[MyNote]]',
* error,
* '[Link unavailable]'
* );
* return fallback; // Use fallback in output
* }
*
* // Without custom fallback
* const { fallback } = ExportErrorHandler.handleProcessingError(
* 'Image',
* 'path/to/image.png',
* new Error('Not found')
* );
* // fallback: "[⚠️ **Image processing error:** path/to/image.png]"
* ```
*/
public static handleProcessingError(
operation: string,
@@ -96,7 +253,39 @@ export class ExportErrorHandler {
}
/**
* Create a batch export tracker for consistent error collection
* Creates a batch export tracker for systematic result collection.
*
* This method returns an object with methods to track successes and failures
* during batch export operations. It maintains counters and collects error
* messages, providing a clean API for recording results as exports progress.
*
* The tracker automatically logs individual errors to the console and formats
* error messages with file names for later reporting. Use getResult() to obtain
* the final BatchExportResult for display with handleBatchResult().
*
* @returns Object with tracker state and methods for recording results
*
* @example
* ```typescript
* const batch = ExportErrorHandler.createBatchTracker();
*
* for (const file of filesToExport) {
* try {
* await exportFile(file);
* batch.recordSuccess();
* } catch (error) {
* batch.recordError(file.name, error);
* }
* }
*
* // Display final results
* const result = batch.getResult();
* ExportErrorHandler.handleBatchResult(result, 'Folder export');
* // result: { successful: 8, failed: 2, errors: ['file1.md: Error message', ...] }
*
* // Direct access to tracker state
* console.log(`Progress: ${batch.tracker.successful} / ${filesToExport.length}`);
* ```
*/
public static createBatchTracker(): {
tracker: BatchExportResult;
@@ -128,7 +317,22 @@ export class ExportErrorHandler {
}
/**
* Handle single file export errors with proper notices
* Handles single file export errors with console logging and user notice.
*
* This is a convenience method for simple export error scenarios where the
* error should always be logged and shown to the user. Use this for single
* file exports or when you don't need the complexity of structured error handling.
*
* @param error - The error that occurred during export
*
* @example
* ```typescript
* try {
* await exportCurrentNote();
* } catch (error) {
* ExportErrorHandler.handleSingleExportError(error);
* }
* ```
*/
public static handleSingleExportError(error: Error | string): void {
const errorMessage = error instanceof Error ? error.message : String(error);
@@ -137,7 +341,24 @@ export class ExportErrorHandler {
}
/**
* Handle dependency or configuration errors
* Handles dependency checking or configuration errors with optional notices.
*
* This method is specifically for errors that occur during dependency validation
* or configuration loading. It supports silent error handling (logging only) or
* user-visible notices with extended duration for readability.
*
* @param dependency - Name of the dependency or configuration item
* @param error - The error that occurred
* @param showNotice - Whether to display a user-facing notice (default: true)
*
* @example
* ```typescript
* try {
* await checkPandocVersion();
* } catch (error) {
* ExportErrorHandler.handleDependencyError('Pandoc', error);
* }
* ```
*/
public static handleDependencyError(
dependency: string,
@@ -146,7 +367,7 @@ export class ExportErrorHandler {
): void {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`Error checking ${dependency}:`, error);
if (showNotice) {
new Notice(
`${dependency} error: ${errorMessage}`,
@@ -156,28 +377,67 @@ export class ExportErrorHandler {
}
/**
* Show export progress notice
* Displays a progress or informational notice with configurable duration.
*
* @param message - The message to display
* @param timeout - Optional duration in milliseconds (0 = persist until dismissed)
* @returns The Notice object for potential manual dismissal
*
* @example
* ```typescript
* const notice = ExportErrorHandler.showProgressNotice('Exporting...', 0);
* await performExport();
* notice.hide(); // Dismiss when done
* ```
*/
public static showProgressNotice(message: string, timeout?: number): Notice {
return new Notice(message, timeout || 0);
}
/**
* Show export cancellation notice
* Displays a cancellation notice when user aborts an export operation.
*
* @example
* ```typescript
* if (userCancelled) {
* ExportErrorHandler.showCancellationNotice();
* }
* ```
*/
public static showCancellationNotice(): void {
new Notice('Export cancelled');
}
/**
* Show settings validation error
* Displays a validation error for invalid settings or input.
*
* @param field - Name of the field that failed validation
* @param validationMessage - Explanation of why validation failed
*
* @example
* ```typescript
* if (pageSize < 0) {
* ExportErrorHandler.showValidationError('page size', 'must be positive');
* }
* ```
*/
public static showValidationError(field: string, validationMessage: string): void {
new Notice(`Invalid ${field}: ${validationMessage}`);
}
/**
* Show template loading error
* Displays an error when template loading fails.
*
* @param error - The error that occurred during template loading
*
* @example
* ```typescript
* try {
* await loadTemplate(name);
* } catch (error) {
* ExportErrorHandler.showTemplateError(error);
* }
* ```
*/
public static showTemplateError(error: Error | string): void {
const errorMessage = error instanceof Error ? error.message : String(error);
@@ -185,40 +445,83 @@ export class ExportErrorHandler {
}
/**
* Show font caching error
* Displays an error when font caching fails, with fallback notification.
*
* @param error - The error that occurred during font caching
* @param showFallback - Whether to show additional fallback notice (default: true)
*
* @example
* ```typescript
* try {
* await cacheSystemFonts();
* } catch (error) {
* ExportErrorHandler.showFontError(error);
* }
* ```
*/
public static showFontError(error: Error | string, showFallback: boolean = true): void {
const errorMessage = error instanceof Error ? error.message : String(error);
new Notice(`Font caching failed: ${errorMessage}. Using fallback fonts.`, 5000);
if (showFallback) {
new Notice('Font list may be incomplete. Check debug mode for details.', 3000);
}
}
/**
* Show export success notice
* Displays a success notice when export completes successfully.
*
* @param outputPath - Path where the PDF was saved
*
* @example
* ```typescript
* ExportErrorHandler.showExportSuccess('/path/to/output.pdf');
* ```
*/
public static showExportSuccess(outputPath: string): void {
new Notice(`PDF exported successfully to ${outputPath}`);
}
/**
* Show file not found warning
* Displays a warning when no active file is available for export.
*
* @param context - Description of the expected file type (e.g., 'Markdown')
*
* @example
* ```typescript
* if (!activeFile) {
* ExportErrorHandler.showFileNotFoundWarning('Markdown');
* }
* ```
*/
public static showFileNotFoundWarning(context: string): void {
new Notice(`Please open a ${context} file to export`);
}
/**
* Show no files warning
* Displays a warning when no files are available for batch export.
*
* @param context - Description of the file type (default: 'files')
*
* @example
* ```typescript
* if (files.length === 0) {
* ExportErrorHandler.showNoFilesWarning('Markdown files');
* }
* ```
*/
public static showNoFilesWarning(context: string = 'files'): void {
new Notice(`No ${context} to export`);
}
/**
* Show settings reset confirmation
* Displays a confirmation notice when settings are reset to defaults.
*
* @example
* ```typescript
* resetToDefaults();
* ExportErrorHandler.showSettingsReset();
* ```
*/
public static showSettingsReset(): void {
new Notice('Settings reset to defaults');
+175 -9
View File
@@ -1,11 +1,30 @@
/**
* Helper utilities for preparing export modal settings
* Helper utilities for preparing export modal settings.
*
* This module provides utilities for transforming plugin settings and file context
* into the format expected by the export configuration modal. It handles both single
* and multi-file export scenarios, extracting defaults from plugin settings and
* building template variable objects.
*
* Key features:
* - Automatic template variable extraction from plugin settings
* - Multi-file export support with automatic title generation
* - Landscape mode width adjustment for single-page exports
* - Clean separation between single and multi-file modal preparation
*/
import { TFile } from 'obsidian';
import { obsidianTypstPDFExportSettings } from './settings';
import { ExportConfigModalSettings } from '../ui/modal/modalTypes';
/**
* Input parameters for modal settings preparation.
*
* @property file - Primary file for the export
* @property additionalFiles - Additional files for multi-file export (optional)
* @property availableTemplates - List of available template names
* @property settings - Plugin settings to extract defaults from
*/
export interface ModalSettingsInput {
/** Primary file for the export */
file: TFile;
@@ -17,9 +36,75 @@ export interface ModalSettingsInput {
settings: obsidianTypstPDFExportSettings;
}
/**
* Utility class for preparing export modal configuration from plugin settings.
*
* This class transforms plugin settings into the format required by the export
* configuration modal. It extracts defaults for all export options and builds
* template variable objects that can be customized in the modal before export.
*
* The helper handles special cases like:
* - Multi-file export title formatting ("5 files" instead of filename)
* - Landscape orientation width adjustments for single-page exports
* - Template variable extraction from typography and page setup settings
*
* @example
* ```typescript
* // Single file export
* const modalSettings = ModalSettingsHelper.prepareForSingleFile(
* file,
* ['default', 'modern', 'article'],
* this.plugin.settings
* );
* const modal = new ExportConfigModal(this.app, modalSettings, async (config) => {
* await this.exportWithConfig(config);
* });
*
* // Multi-file export
* const modalSettings = ModalSettingsHelper.prepareForMultiFile(
* selectedFiles,
* ['default', 'modern'],
* this.plugin.settings
* );
* // Modal title will show "5 files" if 5 files selected
* ```
*/
export class ModalSettingsHelper {
/**
* Prepare modal settings from plugin defaults and file context
* Prepares modal settings from plugin defaults and file context.
*
* This is the core method that transforms plugin settings and file information
* into the format expected by ExportConfigModal. It automatically detects multi-file
* scenarios, builds template variables from plugin settings, and extracts export
* defaults.
*
* For multi-file exports, the modal title is set to "{count} files" instead of
* the primary file name. Template variables include automatic width adjustment
* for landscape single-page exports.
*
* @param input - Configuration object containing file(s), templates, and settings
* @returns Partial modal settings ready for ExportConfigModal initialization
*
* @example
* ```typescript
* // Single file
* const settings = ModalSettingsHelper.prepareModalSettings({
* file: activeFile,
* availableTemplates: ['default', 'modern'],
* settings: this.settings
* });
* // settings.noteTitle = "My Note"
*
* // Multiple files
* const settings = ModalSettingsHelper.prepareModalSettings({
* file: files[0],
* additionalFiles: files.slice(1),
* availableTemplates: ['default'],
* settings: this.settings
* });
* // settings.noteTitle = "5 files"
* // settings.files = [file1, file2, file3, file4, file5]
* ```
*/
public static prepareModalSettings(input: ModalSettingsInput): Partial<ExportConfigModalSettings> {
const { file, additionalFiles, availableTemplates, settings } = input;
@@ -50,7 +135,33 @@ export class ModalSettingsHelper {
}
/**
* Build template variables object from plugin settings
* Builds template variables object from plugin settings.
*
* This method extracts typography and page setup settings and formats them
* as template variables suitable for Typst compilation. It handles special cases
* like automatic width adjustment for landscape single-page exports.
*
* Variables include:
* - Page setup: pageSize, orientation, flipped, margins (top/bottom/left/right)
* - Typography: bodyFont, headingFont, monospaceFont, bodyFontSize
* - Format-specific: width='auto' for landscape single-page mode
*
* @param settings - Plugin settings containing typography and page setup configuration
* @returns Object with template variables ready for Pandoc/Typst
* @private
*
* @example
* ```typescript
* const vars = ModalSettingsHelper.buildTemplateVariables(settings);
* // {
* // pageSize: 'a4',
* // orientation: 'landscape',
* // flipped: true, // auto-set for landscape
* // marginTop: '71',
* // bodyFont: 'Georgia',
* // width: 'auto' // for landscape single-page
* // }
* ```
*/
private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record<string, string | number | boolean | undefined> {
const baseVariables = {
@@ -80,11 +191,35 @@ export class ModalSettingsHelper {
}
/**
* Helper for single file export modal settings
* Convenience method for preparing modal settings for single file export.
*
* This is a simplified wrapper around prepareModalSettings for the common case
* of exporting a single file. It automatically sets up the modal with the file's
* basename as the title and extracts all defaults from plugin settings.
*
* @param file - The file to export
* @param availableTemplates - List of available template names
* @param settings - Plugin settings for default extraction
* @returns Partial modal settings for single file export
*
* @example
* ```typescript
* const activeFile = this.app.workspace.getActiveFile();
* if (activeFile) {
* const modalSettings = ModalSettingsHelper.prepareForSingleFile(
* activeFile,
* this.templateManager.getAvailableTemplates(),
* this.settings
* );
* new ExportConfigModal(this.app, modalSettings, async (config) => {
* await this.exportFile(activeFile, config);
* }).open();
* }
* ```
*/
public static prepareForSingleFile(
file: TFile,
availableTemplates: string[],
file: TFile,
availableTemplates: string[],
settings: obsidianTypstPDFExportSettings
): Partial<ExportConfigModalSettings> {
return this.prepareModalSettings({
@@ -95,11 +230,42 @@ export class ModalSettingsHelper {
}
/**
* Helper for multi-file export modal settings
* Convenience method for preparing modal settings for multi-file export.
*
* This method handles batch export scenarios where multiple files should be
* exported together. It automatically splits the files array into primary and
* additional files, and sets the modal title to show the file count.
*
* The first file in the array becomes the primary file (used for initial path
* resolution), and the remaining files are treated as additional files for the
* batch export.
*
* @param files - Array of files to export (must contain at least one file)
* @param availableTemplates - List of available template names
* @param settings - Plugin settings for default extraction
* @returns Partial modal settings for multi-file export with "{count} files" title
*
* @example
* ```typescript
* // Export all files in a folder
* const folder = this.app.vault.getAbstractFileByPath('my-folder');
* if (folder instanceof TFolder) {
* const files = folder.children.filter(f => f instanceof TFile) as TFile[];
* const modalSettings = ModalSettingsHelper.prepareForMultiFile(
* files,
* this.templateManager.getAvailableTemplates(),
* this.settings
* );
* // modalSettings.noteTitle = "15 files" (if 15 files)
* new ExportConfigModal(this.app, modalSettings, async (config) => {
* await this.exportFiles(files, config);
* }).open();
* }
* ```
*/
public static prepareForMultiFile(
files: TFile[],
availableTemplates: string[],
files: TFile[],
availableTemplates: string[],
settings: obsidianTypstPDFExportSettings
): Partial<ExportConfigModalSettings> {
const [primaryFile, ...additionalFiles] = files;
+130 -8
View File
@@ -5,11 +5,50 @@ import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
import type { App, PluginManifest } from 'obsidian';
import * as path from 'path';
/**
* Centralized path utilities for safe Obsidian API operations.
*
* This class provides a unified interface for path operations that work correctly
* with both vault-relative and absolute filesystem paths. It handles cross-platform
* path normalization and provides safe wrappers around Obsidian's vault adapter.
*
* Key features:
* - Automatic path normalization for cross-platform compatibility
* - Safe handling of absolute and relative paths
* - FileSystemAdapter validation for desktop-only operations
* - Error handling with user notifications
*
* @example
* ```typescript
* const pathUtils = new PathUtils(app);
* const vaultPath = pathUtils.getVaultPath();
* const pluginDir = pathUtils.getPluginDir(manifest);
* const fullPath = pathUtils.joinPath(vaultPath, pluginDir, 'templates');
* ```
*/
export class PathUtils {
/**
* Creates a new PathUtils instance.
*
* @param app - The Obsidian App instance used for vault operations
*/
constructor(private app: App) {}
/**
* Get vault base path safely with FileSystemAdapter check
* Gets the absolute filesystem path to the vault root directory.
*
* This method requires desktop Obsidian as it relies on FileSystemAdapter.
* If the adapter is not available (e.g., mobile), it will show a notice
* and throw an error.
*
* @returns The absolute path to the vault root directory
* @throws {Error} If FileSystemAdapter is not available (non-desktop environment)
*
* @example
* ```typescript
* const vaultPath = pathUtils.getVaultPath();
* // Returns: '/Users/username/Documents/MyVault'
* ```
*/
getVaultPath(): string {
const adapter = this.app.vault.adapter;
@@ -21,15 +60,44 @@ export class PathUtils {
}
/**
* Get plugin directory path
* Gets the vault-relative path to the plugin directory.
*
* Extracts the directory path from the plugin manifest and normalizes it
* for cross-platform compatibility. This is typically something like
* '.obsidian/plugins/plugin-name'.
*
* @param pluginManifest - The plugin's manifest containing directory information
* @returns The normalized vault-relative path to the plugin directory
*
* @example
* ```typescript
* const pluginDir = pathUtils.getPluginDir(this.manifest);
* // Returns: '.obsidian/plugins/typst-pdf-export'
* ```
*/
getPluginDir(pluginManifest: PluginManifest): string {
return normalizePath(pluginManifest.dir || '');
}
/**
* Join path segments with normalizePath
* Handles absolute paths correctly by using the last absolute path found
* Joins multiple path segments into a single normalized path.
*
* This method filters out empty segments, joins them using Node's path.join,
* and normalizes the result for Obsidian compatibility. It correctly handles
* absolute paths by using Node's standard path joining behavior (which uses
* the rightmost absolute path if multiple absolute paths are provided).
*
* @param segments - Variable number of path segments to join
* @returns The joined and normalized path, or empty string if no segments
*
* @example
* ```typescript
* const fullPath = pathUtils.joinPath(vaultPath, '.obsidian', 'plugins', 'my-plugin');
* // Returns: '/path/to/vault/.obsidian/plugins/my-plugin'
*
* const withEmpty = pathUtils.joinPath('folder', '', 'subfolder');
* // Returns: 'folder/subfolder' (empty segments filtered)
* ```
*/
joinPath(...segments: string[]): string {
const filtered = segments.filter(s => s);
@@ -41,7 +109,20 @@ export class PathUtils {
}
/**
* Ensure directory exists, create if necessary
* Ensures a directory exists, creating it if necessary.
*
* This method checks if the directory exists and creates it if it doesn't.
* The path is automatically normalized before operations. If creation fails,
* a notice is shown to the user and the error is re-thrown.
*
* @param path - The path to the directory (vault-relative or absolute)
* @throws {Error} If directory creation fails
*
* @example
* ```typescript
* await pathUtils.ensureDir('.obsidian/plugins/my-plugin/temp');
* // Creates directory if it doesn't exist
* ```
*/
async ensureDir(path: string): Promise<void> {
const normalizedPath = normalizePath(path);
@@ -57,7 +138,23 @@ export class PathUtils {
}
/**
* Clean up directory contents (files only, like current TempDirectoryManager)
* Cleans up directory contents by removing all files (but not subdirectories).
*
* This method removes only the files directly within the directory, leaving
* any subdirectories intact. This matches the behavior of TempDirectoryManager
* for safe cleanup operations. If the directory doesn't exist or cleanup fails,
* the method returns false and logs a warning.
*
* @param path - The path to the directory to clean (vault-relative or absolute)
* @returns True if cleanup succeeded or directory doesn't exist, false on error
*
* @example
* ```typescript
* const success = await pathUtils.cleanupDir('temp-images');
* if (success) {
* console.log('Temp directory cleaned');
* }
* ```
*/
async cleanupDir(path: string): Promise<boolean> {
const normalizedPath = normalizePath(path);
@@ -78,8 +175,33 @@ export class PathUtils {
}
/**
* Check if file or directory exists
* Handles both vault-relative paths and absolute filesystem paths
* Checks if a file or directory exists at the given path.
*
* This method intelligently handles multiple path formats:
* 1. First attempts as vault-relative path
* 2. If that fails and path is within vault, converts absolute to relative
* 3. For paths outside vault, uses Node's fs module directly
*
* Supports:
* - Vault-relative paths: 'folder/file.md'
* - Absolute Unix paths: '/home/user/vault/file.md'
* - Windows drive letters: 'C:\\Users\\vault\\file.md'
* - Windows UNC paths: '\\\\server\\share\\file.md'
*
* @param path - The path to check (vault-relative or absolute)
* @returns True if the file or directory exists, false otherwise
*
* @example
* ```typescript
* // Check vault-relative path
* const exists = await pathUtils.fileExists('templates/default.typ');
*
* // Check absolute path
* const exists = await pathUtils.fileExists('/usr/bin/pandoc');
*
* // Check Windows path
* const exists = await pathUtils.fileExists('C:\\Program Files\\Pandoc\\pandoc.exe');
* ```
*/
async fileExists(path: string): Promise<boolean> {
try {
+242 -13
View File
@@ -1,14 +1,113 @@
/**
* Security utilities for path validation and sanitization
* Security utilities for path validation and command injection prevention.
*
* This module provides critical security validation for user-provided paths and
* executable configurations to prevent common security vulnerabilities including:
* - Directory traversal attacks (../ path manipulation)
* - Command injection via shell metacharacters
* - Null byte injection attacks
* - Windows reserved name exploitation
* - Path manipulation via special characters
*
* All validation methods in this module are designed to fail safely - when in doubt,
* they reject the input rather than risk a security vulnerability. This defensive
* approach ensures the plugin cannot be exploited to access files outside the vault
* or execute arbitrary commands.
*
* Key features:
* - Output path validation for PDF export destinations
* - Executable path validation for Pandoc/Typst/ImageMagick
* - Human-readable error messages for user feedback
* - Cross-platform security checks (Windows and Unix)
* - Zero-tolerance for suspicious patterns
*
* Security principles:
* - Whitelist approach where possible (allow known-safe patterns)
* - Multiple validation layers for defense in depth
* - Clear error messages without exposing implementation details
* - No automatic sanitization (reject rather than attempt to fix)
*/
import * as path from 'path';
/**
* Security validation utilities for safe path and executable handling.
*
* This class provides static methods for validating user-provided paths and
* executable configurations before they are used in file operations or shell
* commands. All methods are designed with a security-first mindset:
* - Fail closed (reject when uncertain)
* - Multiple validation layers
* - No implicit trust of user input
* - Clear security error messages
*
* Use these methods to validate all user-configurable paths before:
* - Writing exported PDF files
* - Creating temporary directories
* - Executing external tools (Pandoc, Typst, ImageMagick)
* - Resolving output file paths
*
* @example
* ```typescript
* // Validate user-provided output folder
* const userFolder = settings.outputFolder;
* if (!SecurityUtils.validateOutputPath(userFolder)) {
* const error = SecurityUtils.getPathValidationError(userFolder);
* throw new Error(`Invalid output path: ${error}`);
* }
*
* // Safe to use the folder
* await exportToPDF(file, userFolder);
* ```
*
* @example
* ```typescript
* // Validate executable path before spawning process
* const pandocPath = settings.pandocPath;
* if (!SecurityUtils.validateExecutablePath(pandocPath)) {
* const error = SecurityUtils.getExecutablePathValidationError(pandocPath);
* new Notice(`Invalid Pandoc path: ${error}`);
* return;
* }
*
* // Safe to spawn process with this path
* spawn(pandocPath, args);
* ```
*/
export class SecurityUtils {
/**
* Validates that an output folder path is safe and doesn't contain traversal attempts
* @param outputFolder The folder path to validate
* @returns true if the path is safe, false otherwise
* Validates that an output folder path is safe for file operations.
*
* This method performs comprehensive security checks to prevent directory
* traversal attacks and path manipulation. It rejects:
* - Directory traversal attempts (..)
* - Absolute paths (must be relative to vault root)
* - Null bytes and control characters
* - Double slashes and other suspicious patterns
* - Invalid filename characters (<>:"|?*)
* - Windows reserved system names (CON, PRN, AUX, etc.)
*
* The validation is intentionally strict - when in doubt, reject the path
* rather than risk a security vulnerability. Use getPathValidationError()
* to provide specific feedback to the user about why their path was rejected.
*
* @param outputFolder - The relative folder path to validate
* @returns True if the path is safe for file operations, false otherwise
*
* @example
* ```typescript
* // Valid relative paths
* SecurityUtils.validateOutputPath('exports'); // true
* SecurityUtils.validateOutputPath('exports/pdfs'); // true
* SecurityUtils.validateOutputPath('my documents'); // true
*
* // Invalid paths (security risks)
* SecurityUtils.validateOutputPath('../../../etc'); // false - traversal
* SecurityUtils.validateOutputPath('/tmp/evil'); // false - absolute
* SecurityUtils.validateOutputPath('CON'); // false - reserved name
* SecurityUtils.validateOutputPath('test<>file'); // false - invalid chars
* SecurityUtils.validateOutputPath('path//with//double'); // false - suspicious
* ```
*/
static validateOutputPath(outputFolder: string): boolean {
if (!outputFolder || typeof outputFolder !== 'string') {
@@ -38,9 +137,57 @@ export class SecurityUtils {
}
/**
* Validates that an executable path is safe for use in shell commands
* @param executablePath The executable path to validate
* @returns true if the path is safe, false otherwise
* Validates that an executable path is safe for use in shell commands.
*
* This method prevents command injection attacks by detecting shell
* metacharacters and command substitution patterns that could be used to
* execute arbitrary commands. It rejects paths containing:
* - Shell metacharacters (;&|`$(){}[]<>)
* - Null bytes and control characters
* - Newlines and carriage returns
* - Command separators (with or without whitespace)
* - Variable substitution patterns (${var}, $var)
* - Command substitution patterns (`cmd`, $(cmd))
*
* Empty or whitespace-only paths are allowed (plugin will use system PATH).
* This enables users to simply specify executable names like 'pandoc' rather
* than full paths, relying on shell resolution.
*
* Use getExecutablePathValidationError() to provide specific feedback about
* why an executable path was rejected.
*
* @param executablePath - The executable path or name to validate
* @returns True if the path is safe for shell execution, false otherwise
*
* @example
* ```typescript
* // Valid executable paths
* SecurityUtils.validateExecutablePath(''); // true - use PATH
* SecurityUtils.validateExecutablePath('pandoc'); // true - simple name
* SecurityUtils.validateExecutablePath('/usr/bin/pandoc'); // true - full path
* SecurityUtils.validateExecutablePath('/opt/typst'); // true - full path
* SecurityUtils.validateExecutablePath('C:\\Program Files\\Pandoc\\pandoc.exe'); // true
*
* // Invalid paths (command injection risks)
* SecurityUtils.validateExecutablePath('pandoc; rm -rf /'); // false - separator
* SecurityUtils.validateExecutablePath('$(evil)'); // false - substitution
* SecurityUtils.validateExecutablePath('`malicious`'); // false - substitution
* SecurityUtils.validateExecutablePath('pandoc|cat /etc/passwd'); // false - pipe
* SecurityUtils.validateExecutablePath('${HOME}/bin/fake'); // false - variable
* ```
*
* @example
* ```typescript
* // Use with spawn to prevent injection
* const userPath = settings.pandocPath;
* if (SecurityUtils.validateExecutablePath(userPath)) {
* // Safe to use with spawn (arguments passed separately)
* const process = spawn(userPath || 'pandoc', ['--version']);
* } else {
* const error = SecurityUtils.getExecutablePathValidationError(userPath);
* throw new Error(`Security violation: ${error}`);
* }
* ```
*/
static validateExecutablePath(executablePath: string): boolean {
// Allow empty paths (will use system PATH)
@@ -66,9 +213,48 @@ export class SecurityUtils {
}
/**
* Gets a human-readable error message for invalid paths
* @param outputFolder The invalid path
* @returns Description of why the path is invalid
* Generates a human-readable error message explaining why a path is invalid.
*
* This method provides specific, actionable feedback to users when their
* output folder path fails validation. It identifies the exact security issue
* detected and explains it in user-friendly terms without exposing technical
* implementation details.
*
* The method checks for issues in priority order, returning the most critical
* security violation first. Use this alongside validateOutputPath() to provide
* clear feedback in error messages and UI validation.
*
* @param outputFolder - The path that failed validation
* @returns Descriptive error message explaining why the path is invalid
*
* @example
* ```typescript
* // Provide clear validation feedback in settings
* const userPath = folderInput.value;
* if (!SecurityUtils.validateOutputPath(userPath)) {
* const error = SecurityUtils.getPathValidationError(userPath);
* new Notice(`Invalid output folder: ${error}`);
* return;
* }
* // Continue with valid path...
* ```
*
* @example
* ```typescript
* // Display specific error for different violations
* const testPaths = [
* '../../../etc', // "Path traversal attempts (..) are not allowed"
* '/absolute/path', // "Absolute paths are not allowed..."
* 'CON', // "Reserved system names are not allowed..."
* 'invalid<>chars' // "Invalid characters found in path"
* ];
*
* testPaths.forEach(path => {
* if (!SecurityUtils.validateOutputPath(path)) {
* console.error(`${path}: ${SecurityUtils.getPathValidationError(path)}`);
* }
* });
* ```
*/
static getPathValidationError(outputFolder: string): string {
if (!outputFolder || typeof outputFolder !== 'string') {
@@ -100,9 +286,52 @@ export class SecurityUtils {
}
/**
* Gets a human-readable error message for invalid executable paths
* @param executablePath The invalid executable path
* @returns Description of why the path is invalid
* Generates a human-readable error message for invalid executable paths.
*
* This method provides specific, security-focused feedback when an executable
* path fails validation. It identifies command injection attempts and explains
* them in terms users can understand without revealing exploit techniques.
*
* The error messages are designed to be clear about the security risk while
* remaining user-friendly. Use this alongside validateExecutablePath() to
* provide actionable feedback when users configure external tool paths.
*
* @param executablePath - The executable path that failed validation
* @returns Descriptive error message explaining the security issue
*
* @example
* ```typescript
* // Validate Pandoc path in settings with clear feedback
* const pandocPath = pandocInput.value;
* if (!SecurityUtils.validateExecutablePath(pandocPath)) {
* const error = SecurityUtils.getExecutablePathValidationError(pandocPath);
* new Notice(`Invalid Pandoc path: ${error}`, 8000);
* pandocInput.addClass('error');
* return;
* }
* pandocInput.removeClass('error');
* ```
*
* @example
* ```typescript
* // Log security violations for monitoring
* function validateAndLogExecutable(name: string, path: string): boolean {
* if (!SecurityUtils.validateExecutablePath(path)) {
* const error = SecurityUtils.getExecutablePathValidationError(path);
* console.error(`Security: Rejected ${name} path: ${error}`);
* console.error(`Attempted path: ${path.substring(0, 50)}...`);
* return false;
* }
* return true;
* }
*
* // Validate all external tools
* const valid = [
* validateAndLogExecutable('Pandoc', settings.pandocPath),
* validateAndLogExecutable('Typst', settings.typstPath),
* validateAndLogExecutable('ImageMagick', settings.imagemagickPath)
* ].every(v => v);
* ```
*/
static getExecutablePathValidationError(executablePath: string): string {
if (!executablePath || typeof executablePath !== 'string') {
+340 -12
View File
@@ -1,11 +1,38 @@
// ABOUTME: Manages temporary directories for export operations
// ABOUTME: Uses normalizePath for cross-platform path operations
/**
* Temporary directory management for Obsidian Typst PDF Export plugin.
*
* This module provides centralized management of temporary directories used during
* the PDF export process. It handles creation, cleanup, and validation of temporary
* storage locations for intermediate files such as:
* - Converted images from embedded PDFs
* - Intermediate Pandoc processing files
* - Temporary Typst compilation artifacts
*
* Key features:
* - Cross-platform path handling using Obsidian's normalizePath
* - Automatic directory creation on first use
* - Safe cleanup that preserves directory structure
* - Plugin-scoped temporary directories within .obsidian folder
* - Validation utilities for path security
*
* The manager creates temporary directories at:
* `<vault>/.obsidian/plugins/typst-pdf-export/temp-images/`
* `<vault>/.obsidian/plugins/typst-pdf-export/temp-pandoc/`
*/
import { PLUGIN_DIRS } from './constants';
import { normalizePath } from 'obsidian';
import type { App } from 'obsidian';
import * as path from 'path';
/**
* Configuration options for TempDirectoryManager initialization.
*
* @property vaultPath - Absolute path to the vault root directory
* @property configDir - Configuration directory path (typically '.obsidian')
* @property pluginName - Optional custom plugin directory name (defaults to 'typst-pdf-export')
* @property app - Obsidian App instance for vault.adapter file operations
*/
export interface TempDirectoryOptions {
/** Base path for the vault */
vaultPath: string;
@@ -17,12 +44,101 @@ export interface TempDirectoryOptions {
app: App;
}
/**
* Manager for plugin temporary directories used during PDF export operations.
*
* This class provides a centralized interface for managing temporary file storage
* during the Markdown → Typst → PDF conversion pipeline. It handles the full
* lifecycle of temporary directories:
* - Automatic directory creation on first use
* - Type-specific directory paths (images vs. pandoc processing)
* - Safe cleanup that removes files but preserves directory structure
* - Cross-platform path handling with proper normalization
* - Security validation to prevent directory traversal attacks
*
* The manager uses Obsidian's vault.adapter API for all file operations, ensuring
* compatibility with desktop-only features and proper permission handling.
*
* Temporary Directory Structure:
* ```
* <vault>/.obsidian/plugins/typst-pdf-export/
* ├── temp-images/ # Converted images from embedded PDFs
* └── temp-pandoc/ # Intermediate Pandoc/Typst processing files
* ```
*
* Lifecycle:
* 1. Initialize manager with vault path and app instance
* 2. Call ensureTempDir() to create directories as needed
* 3. Use getTempDir() to resolve paths for file operations
* 4. Call cleanupTempDir() to remove temporary files (preserves directories)
* 5. Use isPluginTempDir() to validate paths before operations
*
* @example
* ```typescript
* // Initialize for a specific vault
* const manager = new TempDirectoryManager({
* vaultPath: '/Users/name/vault',
* configDir: '.obsidian',
* app: this.app
* });
*
* // Ensure temp directories exist before export
* const imagesDir = await manager.ensureTempDir('images');
* const pandocDir = await manager.ensureTempDir('pandoc');
*
* // Use directories for file operations
* await this.app.vault.adapter.write(
* `${imagesDir}/converted-pdf-page-1.png`,
* imageData
* );
*
* // Clean up after export
* await manager.cleanupAllTempDirs();
* ```
*
* @example
* ```typescript
* // Factory method for quick initialization
* const manager = TempDirectoryManager.create(
* vaultPath,
* '.obsidian',
* 'typst-pdf-export',
* app
* );
*
* // Validate paths before operations
* const userPath = '/some/user/provided/path';
* if (manager.isPluginTempDir(userPath)) {
* // Safe to operate on this path
* await manager.cleanupTempDir('images');
* }
* ```
*/
export class TempDirectoryManager {
private readonly vaultPath: string;
private readonly configDir: string;
private readonly pluginName: string;
private readonly app: App;
/**
* Creates a new TempDirectoryManager instance.
*
* Initializes the manager with vault configuration and Obsidian app instance.
* The manager will create temporary directories within the plugin folder using
* the provided paths.
*
* @param options - Configuration options for the temp directory manager
*
* @example
* ```typescript
* const manager = new TempDirectoryManager({
* vaultPath: this.app.vault.adapter.getBasePath(),
* configDir: this.app.vault.configDir,
* pluginName: 'typst-pdf-export',
* app: this.app
* });
* ```
*/
constructor(options: TempDirectoryOptions) {
this.vaultPath = options.vaultPath;
this.configDir = options.configDir;
@@ -31,8 +147,22 @@ export class TempDirectoryManager {
}
/**
* Get the plugin directory path
* Handles absolute paths correctly on Windows
* Resolves the absolute path to the plugin directory.
*
* Constructs the full path to the plugin's directory within the vault's
* .obsidian/plugins folder. Uses Node.js path.join for proper cross-platform
* path handling (Windows drive letters, Unix-style paths) and Obsidian's
* normalizePath to ensure consistent forward slashes.
*
* @returns Normalized absolute path to plugin directory
* @private
*
* @example
* ```typescript
* // On Unix: '/Users/name/vault/.obsidian/plugins/typst-pdf-export'
* // On Windows: 'C:/Users/name/vault/.obsidian/plugins/typst-pdf-export'
* const pluginDir = this.getPluginDir();
* ```
*/
private getPluginDir(): string {
// path.join automatically handles absolute paths correctly
@@ -41,8 +171,34 @@ export class TempDirectoryManager {
}
/**
* Get the path for a specific temp directory
* Handles absolute paths correctly on Windows
* Resolves the path for a specific temporary directory type.
*
* Returns the absolute path to either the images or pandoc temporary directory
* without creating it. Use ensureTempDir() to also create the directory if it
* doesn't exist.
*
* Directory types:
* - 'images': For converted images from embedded PDF files
* - 'pandoc': For intermediate Pandoc/Typst processing files
*
* Paths use Obsidian's normalizePath to ensure consistent forward slashes
* across all platforms.
*
* @param type - Type of temporary directory ('images' or 'pandoc')
* @returns Normalized absolute path to the temporary directory
*
* @example
* ```typescript
* const imagesPath = manager.getTempDir('images');
* // Returns: '<vault>/.obsidian/plugins/typst-pdf-export/temp-images'
*
* const pandocPath = manager.getTempDir('pandoc');
* // Returns: '<vault>/.obsidian/plugins/typst-pdf-export/temp-pandoc'
*
* // Use with vault adapter for file operations
* const outputPath = `${imagesPath}/converted-page-1.png`;
* await this.app.vault.adapter.write(outputPath, imageData);
* ```
*/
public getTempDir(type: 'images' | 'pandoc'): string {
const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC;
@@ -55,7 +211,44 @@ export class TempDirectoryManager {
}
/**
* Ensure a temp directory exists, creating it if necessary
* Ensures a temporary directory exists, creating it if necessary.
*
* This method checks if the specified temporary directory exists and creates
* it if missing. It uses Obsidian's vault.adapter API for directory creation,
* ensuring proper permissions and cross-platform compatibility.
*
* This is the recommended method to use before writing temporary files, as it
* handles both path resolution and directory creation in a single call.
*
* @param type - Type of temporary directory ('images' or 'pandoc')
* @returns Promise resolving to the normalized absolute path of the directory
*
* @example
* ```typescript
* // Ensure images directory exists before conversion
* const imagesDir = await manager.ensureTempDir('images');
* console.log('Images directory ready:', imagesDir);
* // Output: Images directory ready: /vault/.obsidian/plugins/typst-pdf-export/temp-images
*
* // Write converted image file
* await this.app.vault.adapter.write(
* `${imagesDir}/pdf-page-1.png`,
* imageBuffer
* );
* ```
*
* @example
* ```typescript
* // Ensure both directories exist before export
* const [imagesDir, pandocDir] = await Promise.all([
* manager.ensureTempDir('images'),
* manager.ensureTempDir('pandoc')
* ]);
*
* // Use directories for export pipeline
* await convertPdfToImages(pdfPath, imagesDir);
* await runPandocConversion(inputPath, pandocDir);
* ```
*/
public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
const tempDir = this.getTempDir(type);
@@ -69,7 +262,42 @@ export class TempDirectoryManager {
}
/**
* Clean up a specific temp directory
* Cleans up temporary files from a specific directory.
*
* This method removes all files from the specified temporary directory while
* preserving the directory structure itself. It only removes files, not
* subdirectories, ensuring that the temporary directory remains ready for
* future use.
*
* Cleanup failures are logged to the console but don't throw errors, allowing
* the export process to continue even if cleanup encounters issues. This is
* important for user experience - a failed cleanup shouldn't prevent export
* completion.
*
* @param type - Type of temporary directory to clean ('images' or 'pandoc')
* @returns Promise resolving to true if cleanup succeeded, false if it failed
*
* @example
* ```typescript
* // Clean up after successful export
* const success = await manager.cleanupTempDir('images');
* if (success) {
* console.log('Temporary images cleaned up');
* } else {
* console.warn('Cleanup failed, but export completed');
* }
* ```
*
* @example
* ```typescript
* // Clean up in finally block to ensure cleanup even on errors
* try {
* await exportToPDF(file);
* } finally {
* await manager.cleanupTempDir('pandoc');
* await manager.cleanupTempDir('images');
* }
* ```
*/
public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
const tempDir = this.getTempDir(type);
@@ -91,7 +319,34 @@ export class TempDirectoryManager {
}
/**
* Clean up all temp directories
* Cleans up all temporary directories in a single operation.
*
* This convenience method calls cleanupTempDir() for both the images and
* pandoc directories, running the cleanups in parallel for efficiency. It
* returns the success status for each directory independently, allowing
* partial cleanup if one directory fails.
*
* Use this method at the end of export operations to remove all temporary
* files created during the conversion process.
*
* @returns Promise resolving to object with cleanup success status for each directory type
*
* @example
* ```typescript
* // Clean up all temp directories after export
* const result = await manager.cleanupAllTempDirs();
* console.log('Images cleanup:', result.images ? 'Success' : 'Failed');
* console.log('Pandoc cleanup:', result.pandoc ? 'Success' : 'Failed');
* ```
*
* @example
* ```typescript
* // Use in plugin unload to ensure cleanup on disable
* async onunload() {
* await this.tempManager.cleanupAllTempDirs();
* console.log('Temporary files cleaned up');
* }
* ```
*/
public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> {
return {
@@ -101,15 +356,88 @@ export class TempDirectoryManager {
}
/**
* Static helper to create manager from vault path and configDir
* Factory method for creating a TempDirectoryManager instance.
*
* This static convenience method provides a simpler way to instantiate the
* manager when you have individual parameters rather than an options object.
* It's particularly useful when parameters are obtained separately from
* different sources.
*
* @param vaultPath - Absolute path to the vault root directory
* @param configDir - Configuration directory path (typically '.obsidian')
* @param pluginName - Optional plugin directory name (defaults to 'typst-pdf-export')
* @param app - Obsidian App instance for vault.adapter operations
* @returns New TempDirectoryManager instance
*
* @example
* ```typescript
* // Create manager from separate parameters
* const pathUtils = new PathUtils(this.app);
* const vaultPath = pathUtils.getVaultPath();
* const configDir = this.app.vault.configDir;
*
* const manager = TempDirectoryManager.create(
* vaultPath,
* configDir,
* 'typst-pdf-export',
* this.app
* );
* ```
*
* @example
* ```typescript
* // Quick initialization with default plugin name
* const manager = TempDirectoryManager.create(
* this.app.vault.adapter.getBasePath(),
* this.app.vault.configDir,
* undefined, // Use default plugin name
* this.app
* );
* ```
*/
public static create(vaultPath: string, configDir: string, pluginName: string | undefined, app: App): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, configDir, pluginName, app });
}
/**
* Check if a path is within the plugin's temp directories
* Handles absolute paths correctly on Windows
* Validates if a path is within the plugin's temporary directories.
*
* This security utility checks whether a given path is contained within either
* the temp-images or temp-pandoc directories. Use this method to validate paths
* before performing operations to prevent directory traversal attacks or
* accidental operations on user files.
*
* The method performs normalized path comparisons using Obsidian's normalizePath
* to ensure consistent behavior across Windows and Unix-like systems.
*
* @param dirPath - Path to validate (can be absolute or relative)
* @returns True if the path is within plugin temp directories, false otherwise
*
* @example
* ```typescript
* // Validate user-provided path before cleanup
* const userPath = '/vault/.obsidian/plugins/typst-pdf-export/temp-images/file.png';
* if (manager.isPluginTempDir(userPath)) {
* await this.app.vault.adapter.remove(userPath);
* console.log('Safe to remove - within temp directory');
* } else {
* console.error('Unsafe path - outside temp directories');
* }
* ```
*
* @example
* ```typescript
* // Use as guard before bulk operations
* async safeCleanup(filePaths: string[]) {
* for (const filePath of filePaths) {
* if (manager.isPluginTempDir(filePath)) {
* await this.app.vault.adapter.remove(filePath);
* } else {
* console.warn('Skipping non-temp file:', filePath);
* }
* }
* }
* ```
*/
public isPluginTempDir(dirPath: string): boolean {
const pluginDir = this.getPluginDir();
+182 -10
View File
@@ -1,9 +1,53 @@
/**
* Constants used throughout the Obsidian Typst PDF Export plugin
* Global constants for Obsidian Typst PDF Export plugin.
*
* This module defines all constant values used throughout the plugin, including:
* - Fallback fonts for cross-platform compatibility
* - Plugin directory structure and file names
* - Export operation timeouts and durations
* - Dependency checking paths and executables
*
* All constants are defined using `as const` for maximum type safety, ensuring
* they cannot be modified at runtime and TypeScript can infer literal types.
* This prevents accidental mutations and catches typos at compile time.
*
* These constants are imported and used across:
* - Font management and caching
* - Temporary directory management
* - Export pipeline timeouts
* - Dependency resolution and validation
* - User notifications and feedback
*/
/**
* Fallback fonts used when Typst font detection fails
* Fallback fonts used when Typst cannot detect system fonts.
*
* This array provides a curated list of widely-available fonts that work across
* Windows, macOS, and Linux systems. When Typst's automatic font detection fails
* or specific fonts aren't found, the plugin will offer these fonts to users as
* safe alternatives.
*
* The list is organized by category:
* - Serif: Times New Roman, Georgia
* - Sans-serif: Arial, Helvetica, SF Pro Text
* - Monospace: Courier New, Monaco, SF Mono, Source Code Pro
* - Special: Concourse OT, UbuntuMono Nerd Font Mono
*
* These fonts are chosen for their:
* - Wide platform availability
* - Good readability in PDFs
* - Professional appearance
* - Comprehensive character coverage
*
* @example
* ```typescript
* // Use fallback fonts when system font detection fails
* let availableFonts = await detectSystemFonts();
* if (availableFonts.length === 0) {
* availableFonts = [...FALLBACK_FONTS];
* console.warn('Using fallback fonts - system font detection failed');
* }
* ```
*/
export const FALLBACK_FONTS = [
'Times New Roman',
@@ -20,7 +64,27 @@ export const FALLBACK_FONTS = [
] as const;
/**
* Plugin-specific directory names
* Plugin-specific directory and file names.
*
* Defines the structure of plugin-managed directories within the vault's
* .obsidian/plugins/typst-pdf-export folder. These directories are used for:
* - Temporary file storage during export operations
* - Font cache persistence for faster initialization
*
* Directory structure:
* ```
* .obsidian/plugins/typst-pdf-export/
* ├── temp-images/ # Converted images from embedded PDFs
* ├── temp-pandoc/ # Intermediate Pandoc/Typst processing files
* └── fonts-cache.json # Cached system font list
* ```
*
* All paths are managed by TempDirectoryManager and automatically cleaned up
* to prevent disk space accumulation.
*
* @property TEMP_IMAGES - Directory for converted PDF images
* @property TEMP_PANDOC - Directory for Pandoc intermediate files
* @property FONTS_CACHE - JSON file storing cached font information
*/
export const PLUGIN_DIRS = {
TEMP_IMAGES: 'temp-images',
@@ -29,7 +93,31 @@ export const PLUGIN_DIRS = {
} as const;
/**
* Export-related constants
* Export operation timeouts and notification durations.
*
* Configures timing parameters for export operations and user feedback:
* - Process timeouts prevent hanging exports from blocking the UI
* - Notice durations ensure users have time to read important messages
*
* @property DEFAULT_TIMEOUT - Maximum time (ms) for export operations (2 minutes)
* @property NOTICE_DURATION - Standard durations for Obsidian notices
* @property NOTICE_DURATION.SHORT - Brief notices for status updates (5 seconds)
* @property NOTICE_DURATION.LONG - Extended notices for detailed info (12 seconds)
*
* @example
* ```typescript
* // Use timeout for export process
* const result = await Promise.race([
* exportToPDF(file),
* new Promise((_, reject) =>
* setTimeout(() => reject(new Error('Timeout')),
* EXPORT_CONSTANTS.DEFAULT_TIMEOUT)
* )
* ]);
*
* // Show success notice with short duration
* new Notice('PDF exported successfully', EXPORT_CONSTANTS.NOTICE_DURATION.SHORT);
* ```
*/
export const EXPORT_CONSTANTS = {
DEFAULT_TIMEOUT: 120000, // 2 minutes
@@ -40,24 +128,97 @@ export const EXPORT_CONSTANTS = {
} as const;
/**
* Dependency checking constants and utilities
* Dependency checking configuration and common paths.
*
* Defines default executable names and search paths for external tools required
* by the plugin (Pandoc, Typst, and ImageMagick). The plugin searches these
* paths in addition to the system PATH to handle various installation methods:
* - Package managers (brew, apt, snap, cargo)
* - User-local installations (~/.local/bin)
* - Language-specific package managers (cargo, npm, go)
* - System standard locations (/usr/bin, /usr/local/bin)
*
* These paths are always checked regardless of user settings, ensuring the plugin
* can find executables even when they're not in the user's shell PATH (common
* with GUI applications on macOS).
*
* @property DEFAULT_EXECUTABLES - Default command names for each dependency
* @property DEFAULT_EXECUTABLES.pandoc - Pandoc markdown converter (v2.0+)
* @property DEFAULT_EXECUTABLES.typst - Typst PDF compiler (v0.11+)
* @property DEFAULT_EXECUTABLES.imagemagick - ImageMagick convert utility (v7+)
* @property COMMON_PATHS - Standard installation locations to search
* @property COMMON_PATHS.HOME_RELATIVE - Paths relative to user home directory
* @property COMMON_PATHS.ABSOLUTE - System-wide absolute paths
*
* @example
* ```typescript
* // Build augmented PATH for dependency checking
* const homeDir = process.env.HOME || process.env.USERPROFILE;
* const homePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE
* .map(p => homeDir + p);
* const allPaths = [
* ...process.env.PATH.split(':'),
* ...homePaths,
* ...DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE
* ];
*
* // Search for pandoc in augmented PATH
* const pandocPath = findInPaths(
* DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc,
* allPaths
* );
* ```
*
* @example
* ```typescript
* // Resolve executable with fallback to default name
* const executablePath = settings.pandocPath ||
* DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc;
*
* // Check if executable exists in common paths
* const resolved = await resolveExecutable(
* executablePath,
* DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.concat(
* DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE
* )
* );
* ```
*/
export const DEPENDENCY_CONSTANTS = {
/**
* Default executable names for dependencies
* Default executable names for external dependencies.
*
* These are the command names used when users haven't configured custom paths.
* The plugin will search for these in the augmented PATH.
*
* @property pandoc - Pandoc executable (markdown → typst converter)
* @property typst - Typst executable (typst → PDF compiler)
* @property imagemagick - ImageMagick executable (PDF → image converter)
*/
DEFAULT_EXECUTABLES: {
pandoc: 'pandoc',
typst: 'typst',
imagemagick: 'magick'
},
/**
* Common paths to augment PATH with - these are always checked regardless of user settings
* Common installation paths to search for executables.
*
* These paths are checked in addition to the system PATH to handle tools
* installed via various methods. The plugin automatically augments PATH
* with these locations during dependency checking.
*/
COMMON_PATHS: {
/**
* Paths relative to home directory (will have HOME prepended)
* Paths relative to the user's home directory.
*
* These paths will have HOME or USERPROFILE prepended before searching:
* - .local/bin: Local user installations (Linux standard)
* - .cargo/bin: Rust/Cargo package installations
* - go/bin: Go package installations
* - .npm-global/bin: Global npm package installations
*
* @example ['~/.local/bin', '~/.cargo/bin', '~/go/bin', '~/.npm-global/bin']
*/
HOME_RELATIVE: [
'/.local/bin',
@@ -66,7 +227,18 @@ export const DEPENDENCY_CONSTANTS = {
'/.npm-global/bin'
],
/**
* System-wide absolute paths (used as-is)
* System-wide absolute paths used as-is.
*
* Standard Unix/Linux system directories where executables are commonly
* installed by package managers:
* - /usr/local/bin: Homebrew (macOS), local installs
* - /opt/homebrew/bin: Homebrew on Apple Silicon
* - /usr/bin: System package manager installs
* - /bin: Essential system commands
* - /opt/local/bin: MacPorts installations
* - /snap/bin: Snap package installations (Linux)
*
* @example ['/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin', '/opt/local/bin', '/snap/bin']
*/
ABSOLUTE: [
'/usr/local/bin',
+191 -14
View File
@@ -1,34 +1,162 @@
/**
* Core settings and configuration for Obsidian Typst PDF Export plugin
* Settings and configuration schema for Obsidian Typst PDF Export plugin.
*
* This module defines the complete configuration structure for the plugin, including:
* - External tool paths (Pandoc, Typst, ImageMagick)
* - Export defaults and presets
* - Typography and page layout settings
* - Behavior flags and preferences
* - Default values for fresh installations
*
* The settings are persisted to the vault's data.json file and can be modified
* through the plugin's settings tab. All settings have safe defaults that work
* out-of-the-box when external tools are available in PATH.
*
* Settings Organization:
* - Top-level: Core paths and output configuration
* - executablePaths: External tool configuration
* - exportDefaults: Default values for new exports
* - typography: Font configuration
* - pageSetup: Page layout and margins
* - behavior: Plugin behavior flags
*
* Type Safety:
* All settings use TypeScript for compile-time validation, preventing invalid
* configuration values and catching errors before runtime.
*/
/**
* Export format options for PDF generation.
*
* Determines the pagination and layout style of the exported PDF:
* - Standard: Traditional multi-page format with page breaks
* - Single-page: Continuous single-page format without pagination
*
* The format affects Typst compilation parameters and influences layout decisions
* like automatic width adjustment for landscape orientation.
*/
export enum ExportFormat {
/** Standard multi-page PDF format */
/** Standard multi-page PDF format with automatic pagination */
Standard = 'standard',
/** Single-page continuous PDF format */
/** Single-page continuous PDF format without page breaks */
SinglePage = 'single-page'
}
/**
* Complete plugin settings interface.
*
* Defines all configurable options for the plugin, organized into logical groups.
* This interface serves as both the TypeScript type definition and the schema
* for the settings tab UI.
*
* Settings Lifecycle:
* 1. Plugin initializes with DEFAULT_SETTINGS
* 2. Persisted settings loaded from data.json (if exists)
* 3. User modifies via settings tab
* 4. Changes saved immediately to data.json
* 5. Export operations use current settings
*
* @example
* ```typescript
* // Load settings with defaults
* const settings: obsidianTypstPDFExportSettings = {
* ...DEFAULT_SETTINGS,
* ...await this.loadData()
* };
*
* // Use settings in export
* const converter = new PandocTypstConverter(
* this.plugin,
* { template: settings.exportDefaults.template },
* { ppi: 144 }
* );
* ```
*/
export interface obsidianTypstPDFExportSettings {
/** Path to the Pandoc executable */
/**
* Path to the Pandoc executable.
*
* Can be either:
* - Empty string: Use system PATH resolution
* - Executable name: e.g., 'pandoc' (searches augmented PATH)
* - Absolute path: e.g., '/usr/local/bin/pandoc'
*
* Pandoc 2.0+ required for Typst output support.
*/
pandocPath: string;
/** Path to the Typst executable */
/**
* Path to the Typst executable.
*
* Can be either:
* - Empty string: Use system PATH resolution
* - Executable name: e.g., 'typst' (searches augmented PATH)
* - Absolute path: e.g., '/opt/typst/bin/typst'
*
* Typst 0.11+ recommended for best compatibility.
*/
typstPath: string;
/** Default output folder for exported PDFs */
/**
* Default output folder for exported PDFs.
*
* Relative path from vault root. Will be created if it doesn't exist.
* Security: Must pass SecurityUtils.validateOutputPath() validation.
*
* @example 'exports' - PDF files saved to <vault>/exports/
* @example 'pdfs/from-notes' - PDF files saved to <vault>/pdfs/from-notes/
*/
outputFolder: string;
/** Executable paths configuration */
/**
* Executable paths configuration for optional dependencies.
*
* Controls where the plugin searches for external tools and how
* it augments the PATH environment variable.
*/
executablePaths: {
/** Path to ImageMagick command (optional, uses PATH if not specified) */
/**
* Path to ImageMagick command (optional).
*
* ImageMagick is optional but recommended for embedded PDF support.
* If not configured, embedded PDFs will be skipped during export.
*
* Can be:
* - Empty string: Use system PATH (default)
* - Executable name: e.g., 'magick'
* - Absolute path: e.g., '/usr/bin/magick'
*/
imagemagickPath: string;
/** Additional paths to append to PATH environment variable */
/**
* Additional directories to search for executables.
*
* These paths are added to the PATH environment variable when
* searching for external tools. Useful for non-standard installations
* or when tools aren't in the user's shell PATH.
*
* @example ['/opt/homebrew/bin', '/usr/local/bin']
*/
additionalPaths: string[];
};
/** Custom environment variables for subprocess execution */
/**
* Custom environment variables for subprocess execution.
*
* Additional environment variables passed to Pandoc and Typst processes.
* Useful for configuring tool behavior or providing authentication.
*
* @example { 'TYPST_FONT_PATHS': '/custom/fonts:/system/fonts' }
* @example { 'PANDOC_USER_DATA_DIR': '/custom/pandoc/data' }
*/
customEnvironmentVariables: { [key: string]: string };
/** Export defaults */
/**
* Default values for new export operations.
*
* These settings are used when opening the export modal. Users can override
* them on a per-export basis through the modal interface.
*/
exportDefaults: {
/** Default template to use for exports */
template: string;
@@ -101,6 +229,55 @@ export interface obsidianTypstPDFExportSettings {
};
}
/**
* Default settings for fresh plugin installations.
*
* These values are used when:
* - Plugin is first installed (no data.json exists)
* - Settings are reset to defaults
* - Individual settings are missing from persisted data
*
* The defaults are designed to:
* - Work out-of-the-box when external tools are in PATH
* - Produce professional-looking PDFs with minimal configuration
* - Use widely-available fonts as fallbacks
* - Enable helpful features (auto-open, folder structure preservation)
*
* Settings Strategy:
* - Empty paths for executables (rely on PATH resolution)
* - Common system paths in additionalPaths for macOS/Linux
* - Conservative concurrency (3) for stability
* - Professional typography (Concourse OT, SF Pro)
* - Standard A4 paper with reasonable margins
*
* @example
* ```typescript
* // Initialize plugin with defaults
* async onload() {
* await this.loadSettings(); // Merges with DEFAULT_SETTINGS
* this.registerSettingsTab();
* }
*
* async loadSettings() {
* this.settings = Object.assign(
* {},
* DEFAULT_SETTINGS,
* await this.loadData()
* );
* }
* ```
*
* @example
* ```typescript
* // Reset individual settings to defaults
* resetTypography() {
* this.settings.typography = {
* ...DEFAULT_SETTINGS.typography
* };
* await this.saveSettings();
* }
* ```
*/
export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
pandocPath: '',
typstPath: '',