53 Commits
Author SHA1 Message Date
Jarvis b322e6801c chore: release 1.4.0
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-09 18:30:36 +01:00
AlexKucera 9957e4fb58 Merge pull request #9 from AlexKucera/version_checker
Enforces minimum version checks for dependencies
2025-11-09 18:28:16 +01:00
AlexKucera d078215361 Makes version regex case-insensitive
Updates the regex patterns in the dependency checks
to be case-insensitive, improving flexibility and reliability
when parsing version information from executables.

Aligned with improvements on the version_checker branch.
2025-11-09 18:09:20 +01:00
AlexKucera b5ca5d1e47 Enforces minimum version checks for dependencies
Updates the README with specific minimum version requirements
for dependencies. Implements logic to check installed
dependencies against these minimum versions, issuing
warnings for outdated versions. Introduces utilities to
compare version strings for accurate validation.

This ensures compatibility and stability by guiding users
to update necessary tools for optimal performance.

Relates to version control and dependency management.
2025-11-09 18:02:46 +01:00
Jarvis a69cf31951 chore: release 1.3.1
## Changes

### Security
- Enhanced shell metacharacter validation to reject {} and [] characters in executable paths
- Improved path validation error messages for better clarity

### Tests
- Fixed SecurityUtils test assertions to match improved error messages
- Updated TempDirectoryManager tests to use fs module mocks (partial - 7 tests need further mock configuration)

### Documentation
- Updated CHANGELOG.md with comprehensive v1.3.1 release notes
- Documented all fixes, security improvements, and changes since 1.3.0

## Test Status
- 96/103 tests passing (93%)
- All SecurityUtils tests passing
- 7 TempDirectoryManager tests require mock updates (infrastructure issue, not code bug)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-09 15:26:40 +01:00
AlexKucera b0f8755a56 Enhances security checks and mocks fs module in tests
Updates security check patterns to include brackets for improved command injection prevention. Enhances test reliability by mocking Node's fs module to replace custom mock functions, aligning test behavior closer to actual usage scenarios and ensuring consistent outcomes.

No specific issue reference.
2025-11-09 15:26:33 +01:00
AlexKucera d39ddd189e Refines inline comments in plugin code
Consolidates existing comments by removing redundancy
and improves clarity for ESLint directives, enhancing
code readability and maintenance.
2025-11-09 13:59:06 +01:00
AlexKucera b70ad772f3 Merge pull request #8 from AlexKucera/obsidian-bot-review
Update ESLint rules and resolve bot review feedback
2025-11-09 12:06:31 +01:00
AlexKucera efbff4e172 Fixes indentation and adds debug logging
Corrects inconsistent indentation in FrontmatterProcessor methods
to improve code readability. Adds debug logging for unexpected
types in frontmatter display formatting to aid troubleshooting.

Improves robustness of font settings handling by clarifying
fallback behavior on load failure in TypographySection.

Relates to obsidian-bot-review
2025-11-09 11:04:17 +01:00
AlexKucera d6d31afb16 Adds error handling for font settings initialization
Implements error handling for font settings creation to ensure
fallback to default fonts if loading fails. Reorders font size
settings setup to follow font dropdowns for logical flow.

Enhances robustness and improves user settings experience.
2025-11-09 10:53:46 +01:00
AlexKucera b0df21d9c2 Sanitizes frontmatter to prevent data leakage
Introduces sanitization of frontmatter to remove citation fields,
enhancing data privacy and integrity. Adjusts logic to store
sanitized frontmatter in metadata and reconstruct content while
preserving frontmatter when required. Ensures title in metadata
reflects noteTitle when provided.

Enhances frontmatter processing and metadata handling.
2025-11-09 10:51:39 +01:00
AlexKucera ae5df90eec Rejects absolute paths in vault exports
Updates path normalization to disallow absolute paths, ensuring
exports remain within the vault. Enhances security by rejecting
path traversal attempts.

Aligns with obisidian-bot-review branch requirements.
2025-11-08 19:49:16 +01:00
AlexKucera 5219ef76b0 Removes unused font dropdown logic
Eliminates redundant methods for adding fallback fonts
and removes an unnecessary import, simplifying the
TypographySection code structure. This streamlines
the user interface logic by cleaning up unused
dropdown components.

Relates to task on branch obsidian-bot-review.
2025-11-08 19:47:58 +01:00
AlexKucera c1c02ee553 Apply eslint overrides for capitalization in UI
Disables sentence-case rule for UI elements where proper nouns
are used, ensuring intended capitalization is preserved for
acronyms and font names. Adds comments to justify each override
and re-enables the rule after relevant sections.
2025-11-08 19:15:02 +01:00
AlexKucera 7314776057 Improves output folder path normalization
Enhances path handling by skipping normalization of absolute paths to preserve leading slashes. This prevents potential validation errors when checking output folder paths.

This change increases accuracy and reliability of the path validation logic.
2025-11-08 19:08:41 +01:00
AlexKucera 6c28b82a16 Improves error handling for export submissions
Enhances export submission logic by adding error handling to
manage failures, logging errors for debugging, and providing
user feedback. Re-enables buttons post-failure for retry or
cancellation. Updates description to clarify output folder path
can be absolute or relative.

Relates to user feedback on error transparency.
2025-11-08 19:07:55 +01:00
AlexKucera a71b20e9ba Preserves absolute paths in SecurityUtils
Updates path normalization to maintain absolute paths, aligning
with SettingsTab storage logic. Enhances security by ensuring
consistent path handling and preventing path traversal.

Relates to issue: obsidian-bot-review branch
2025-11-08 19:05:46 +01:00
AlexKucera d56cb98d51 Refactors path conversion to simplify logic
Replaces manual conversion of absolute paths to vault-relative paths with a utility method to improve code readability and maintainability across various modules. Removes redundant code and streamlines path handling operations.

This refactoring helps ensure consistent path management and reduces potential errors related to path conversion.

Relates to obsidian-bot-review
2025-11-08 19:01:42 +01:00
AlexKucera ec36b6334f Refactors path handling in EmbedProcessor
Introduces toVaultRelativePath method to centralize path conversions,
reducing code duplication and improving maintainability. Extracts
image download completion logic into handleDownloadComplete for clarity.

Relates to obsidian-bot-review
2025-11-08 18:52:27 +01:00
AlexKucera 6923644261 Refactors array formatting logic
Simplifies array item formatting by eliminating redundant
string manipulations. Enhances readability and maintains
consistent output for arrays with multiple items.

Relates to obsidian-bot-review
2025-11-08 18:48:31 +01:00
AlexKucera 96859c98e5 Renames dependency check method for clarity
Updates method name from 'checkDependenciesAsync' to
'checkDependenciesOnStartup' to better reflect its purpose of
verifying dependencies during plugin startup.

Enhances code readability and maintainability.
2025-11-08 18:46:39 +01:00
AlexKucera 6098f99c68 Refactors exec invocation in PdfCliExecutor
Moves the promisify exec function outside the render method
for clarity and potential reuse, improving code structure.
2025-11-08 18:45:04 +01:00
AlexKucera 1ac2807320 Enhances error handling with user notifications
Adds user notifications for export and dependency status
errors to improve feedback when operations fail. Utilizes
Obsidian's Notice to display error messages to users.

Relates to obsidian-bot-review branch improvements.
2025-11-08 18:39:50 +01:00
AlexKucera 003d6d105b Replaces 'info' with 'debug' for log levels
Changes log level 'info' to 'debug' in error handling
to improve granularity in log outputs. Enhances monitoring
capabilities by categorizing non-essential logs separately.
2025-11-08 18:38:24 +01:00
AlexKucera 5034e111eb Improves logging for frontmatter processing
Enhances debugging output by including content length in log
messages, assisting in monitoring and troubleshooting frontmatter
parsing issues efficiently.

Reduces redundant debug information, focusing on concise logging
to maintain readability and effectiveness in error analysis.
2025-11-08 18:37:14 +01:00
AlexKucera dc59776379 Adds config directory existence check for error handling
Introduces a validation step to ensure the vault configuration directory is accessible. Throws a descriptive error if the directory is unavailable, improving error handling and initialization clarity for the plugin.

Enhances stability by ensuring TempDirectoryManager functions only when prerequisites are satisfied.
2025-11-08 18:35:14 +01:00
AlexKucera 2e8ac6a848 Enhances cleanup with async lifecycle handling
Updates plugin cleanup to utilize async handlers during onunload,
ensuring proper resource management and cleanup of temporary files.
Removes redundant process termination listeners and integrates lifecycle
methods for better maintainability and efficiency.

Improves robustness of plugin cleanup on unload.
2025-11-08 18:32:48 +01:00
AlexKucera f0daebc8fd Updates Node.js requirement to version 18.20+
Specifies Node.js version 18.20+ in package engines and README
to ensure compatibility and leverage latest features available
from this Node.js version.
2025-11-08 18:28:19 +01:00
Jarvis 87f3894bf1 Fixes path doubling issues in directory creation and file operations
Resolves critical bugs where directories and files were being created with
doubled paths (e.g., /vault/vault/path) due to incorrect handling of absolute
vs vault-relative paths when using Obsidian's vault adapter.

## Root Cause
The vault.adapter methods (mkdir, write, readBinary, etc.) expect vault-relative
paths, but many parts of the codebase were passing absolute filesystem paths.
This caused the adapter to prepend the vault path again, resulting in doubled
paths like: /Users/user/vault/Users/user/vault/exports

## Changes

### Core Path Handling
- **TempDirectoryManager**: Switched to Node's fs module for temp directory
  operations since external tools (pdf2img, ImageMagick, Pandoc) require
  absolute filesystem paths and cannot use vault adapter
- **PathUtils.ensureDir()**: Enhanced error messages to provide context about
  missing parent directories and permission issues

### Path Conversion Pattern
Implemented consistent pattern throughout codebase: convert absolute paths to
vault-relative before vault.adapter operations by:
1. Checking if path starts with vault base path
2. Stripping vault base path
3. Removing leading slash/backslash
4. Passing vault-relative path to vault.adapter

### Fixed Locations
- **ImageOptimizer**: Convert paths before vault.adapter operations (3 locations)
- **EmbedProcessor**:
  - downloadRemoteImage(): path conversion for writeBinary
  - copyImageToVaultTemp(): path conversion for vault.adapter operations
  - processImageEmbeds(): WebP conversion temp directory
- **PandocTypstConverter**: Use fs module for temp markdown file operations
- **PathResolver**: Convert output folder paths before ensureDir
- **PdfToImageConverter**: Convert output directory path before ensureDir
- **EmbeddedTemplateManager**: Convert template directory paths (2 locations)

### Additional Improvements
- **PathResolver**: Added validation for empty/missing output folder with
  clear error message guiding users to plugin settings
- **ESLint**: Changed sentence-case rule from error to warning to reduce
  linter noise during development

## Impact
- Fixes directories being created in wrong locations with doubled paths
- Ensures temp directories are accessible by external CLI tools
- Improves error messages for directory creation failures
- Maintains compatibility with both Obsidian's vault adapter and Node's fs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-05 19:17:37 +01:00
AlexKucera 7d805eda45 Standardizes terminology and error handling
Corrects capitalization inconsistencies in UI and documentation,
improving clarity and professionalism. Enhances error handling
in the image download function by properly rejecting promises
on errors, thus increasing reliability and maintainability.

Relates to obsidian-bot-review branch tasks.
2025-11-05 17:25:01 +01:00
AlexKucera 2c4076f3c9 Applies Obsidian linter and fixes code issues
Applies linting rules to the codebase and resolves identified issues.

Addresses:
- Renamed headings in settings tabs to improve UI consistency and style.
- Resolved require() style imports
- Added void operator to ensure correct promise handling.
- Replaced deprecated Obsidian API calls.
- Enforces sentence case to enhance UI text consistency.
2025-11-05 13:46:06 +01:00
AlexKucera 3c3f86ae4f Adds YAML parsing support
Adds js-yaml as a dependency to support parsing YAML files.

This will allow the application to process YAML formatted data,
enhancing its data handling capabilities.
2025-11-05 09:37:54 +01:00
AlexKucera 39d66607af Merge pull request #7 from AlexKucera/windows_path_fix
Fixes path, image, and bibliography issues
2025-11-05 09:28:22 +01:00
AlexKucera 68238e3db2 Refines temp directory path validation
Ensures accurate determination of whether a directory is a temporary directory by explicitly matching the full path or a subdirectory.

This change prevents potential issues related to incorrect path comparisons, especially on Windows where path variations can occur.
2025-11-05 08:51:04 +01:00
AlexKucera c7b9a8b5b8 Fixes executable path resolution on Windows
Updates the executable path resolution logic to correctly identify executables on Windows systems by using the 'where' command instead of 'which', which is not available on Windows.

This change ensures that the application can locate and execute dependencies properly, regardless of the operating system. It also uses `path.isAbsolute` to accurately determine if a user-provided path is absolute, improving the reliability of path resolution.
2025-11-05 08:50:15 +01:00
AlexKucera 207e115699 Restricts shell metacharacters in paths
Addresses a potential command injection vulnerability by tightening the validation of executable paths.

Removes brackets and curly braces from the list of disallowed shell metacharacters in paths on Windows to prevent issues when paths contain these characters. Only the metacharacters that can't appear in safe paths are disallowed.
2025-11-05 08:47:35 +01:00
AlexKucera 35a5249607 Improves remote image download protocol handling
Ensures correct protocol (HTTP/HTTPS) is used when downloading
remote images by using the parsed URL object for the request.

This fixes potential issues where the protocol might be incorrectly
determined, especially when dealing with case-insensitive URL schemes.
2025-11-05 08:33:48 +01:00
AlexKucera a9f436f972 Simplifies path normalization for Windows compatibility
Avoids double normalization of paths, which can lead to issues with Windows path handling, specifically with drive letters and forward slashes.
2025-11-05 08:32:58 +01:00
AlexKucera c788422cdf Strengthens path validation against reserved names
Enhances path validation to prevent issues caused by reserved Windows names.

The previous implementation only checked for reserved names
when the entire path matched a reserved name. This update extends
the check to ensure that no segment of the path, including the
base name without extension, matches a reserved name.

This prevents the use of reserved names, even with extensions or
within directory structures, mitigating potential security risks.
2025-11-05 08:31:44 +01:00
AlexKucera a37e8e1e40 Fixes PATH handling for Windows compatibility
Ensures that the PATH environment variable is correctly augmented with
additional paths, especially on Windows systems. It uses platform-specific
path delimiters (';' on Windows, ':' on Unix) and filters out empty segments
to prevent PATH corruption.
2025-11-05 08:29:47 +01:00
AlexKucera 1aeebed4bf Ensures proper cleanup of converter resources
Addresses potential resource leaks by ensuring that temporary
files and event listeners are properly cleaned up when the
converter is disposed. This prevents issues with multiple
conversions, especially on platforms like Windows where file
locking can occur.

The `uncaughtException` handler is removed to avoid
swallowing errors, and a flag is added to prevent double
cleanup.
2025-11-05 08:28:35 +01:00
AlexKucera 4eb52d11c0 Handles relative redirects for remote images
Ensures that relative redirect URLs are resolved against the original image URL.
This prevents issues when downloading remote images from servers that return
relative redirect paths.
2025-11-05 08:06:48 +01:00
AlexKucera 711eab4593 Handles images without extensions correctly
Ensures images without file extensions are properly handled by appending ".png" to the filename, preventing potential issues with image processing or display.

Preserves existing extensions for other image types (e.g., svg, ico, avif) without forcing a ".png" extension.
2025-11-05 08:05:40 +01:00
AlexKucera 281c02210a Add Docstrings 2025-11-05 08:03:52 +01:00
AlexKucera 7ac9e1f489 Adds unit tests for core functionalities
Adds comprehensive unit tests to improve code coverage for core functionalities: constants, paper size mapping, modal settings, security utilities, temporary directory management, and variable mapping.

This ensures that basic functionalities work as expected and enhances the reliability of the plugin.

Additionally, this commit includes a mock Obsidian API to facilitate testing in a non-Obsidian environment.
2025-11-05 08:03:24 +01:00
AlexKucera 4a0376ec2b Simplifies path handling for temp directories
Removes unnecessary conditional logic when constructing paths for temporary directories.

The logic previously checked if the plugin directory was absolute before joining it with the directory name. This check is redundant as `path.join` correctly handles both absolute and relative paths.
2025-11-04 11:16:25 +01:00
AlexKucera 1ca3669e2f Ensures correct image download order
Ensures that standard markdown images with remote URLs are processed for download after embeds and before wikilinks.

This ensures that remote URLs in the standard markdown format `![](url)` are correctly queued for download.
2025-11-04 11:15:53 +01:00
AlexKucera 6e446048d2 Refactors local path resolution
Consolidates local path resolution logic into a dedicated
`resolveLocalPath` method for improved code reuse and readability.

Improves image downloading by using the vault adapter to write
binary data, preventing potential data corruption.

This change addresses issues with image embed resolution,
especially for attachments in non-standard locations, and fixes
file overwriting during image downloads.
2025-11-04 11:14:53 +01:00
AlexKucera 2e1d2673b1 Simplifies path joining logic
Simplifies the path joining logic by leveraging the built-in `path.join` method directly.
This change removes the manual iteration and absolute path handling, resulting in more concise and readable code.

Ensures correct path handling on Windows.
2025-11-04 11:10:53 +01:00
AlexKucera 501f380644 Simplifies path handling for Windows
Refactors the code to leverage `path.join` for cross-platform path manipulation, especially improving handling of absolute paths on Windows.

Removes redundant normalizations and simplifies the logic for determining temporary directories. This change ensures consistent behavior across different operating systems and reduces code complexity.
2025-11-04 11:09:47 +01:00
AlexKucera 9ca299cafd Fixes bibliography errors
Disables Pandoc's automatic citeproc filter to prevent errors
when processing documents without a bibliography file. This
resolves issues where Pandoc incorrectly detects citation-like
patterns in markdown and attempts to generate bibliographies,
leading to "document does not contain a bibliography" errors.
2025-11-04 10:57:24 +01:00
AlexKucera 8329c9dd48 Fixes path handling and adds remote image support
Addresses issues with path construction on Windows by using `path.isAbsolute()` to correctly handle absolute paths.  Improves cross-platform compatibility in temp directory management and binary location.

Adds support for downloading and embedding remote images (http/https URLs) in markdown, enhancing content integration. Provides fallback mechanism with placeholder text upon download failure.
2025-11-04 10:55:24 +01:00
AlexKucera 536351cbbf Updates repository URLs in README
Updates the repository URLs in the README file to reflect the correct owner.
This ensures users are directed to the correct location for the project and its releases, especially for installation instructions.
2025-09-26 07:47:35 +02:00
60 changed files with 12071 additions and 1414 deletions

No files matched your search

+2
View File
@@ -70,3 +70,5 @@ CLAUDE.md
repomix-output.xml repomix-output.xml
guidance.md guidance.md
coverage/
+48 -4
View File
@@ -5,9 +5,34 @@ All notable changes to the Obsidian Typst PDF Export plugin will be documented i
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.3.1] - 2025-01-25 ## [Unreleased]
## [1.4.0] - 2025-01-09
### Added ### Added
- Minimum version requirements for external dependencies (Pandoc 3.7.0+, Typst 0.13.0+, ImageMagick 7.1.2+)
- Version comparison utilities (`compareVersions`, `isVersionAtLeast`) for semantic version validation
- Outdated dependency warnings in dependency checker with detailed version information
- Enhanced dependency status display showing current version vs. minimum required version
- Comprehensive version checking documentation in README
### Changed
- Updated README to document minimum version requirements in Quick Start and Requirements sections
- Enhanced dependency checker to validate installed versions against minimum requirements
- Improved user-facing dependency status messages with version-specific guidance
### Fixed
- Case-sensitive regex pattern for Typst version detection (now case-insensitive with `/i` flag)
- Version extraction now correctly handles "Typst 0.13.0" (capital T) format
## [1.3.1] - 2025-11-09
### Added
- Unit tests for core functionalities with comprehensive test coverage
- YAML parsing support (js-yaml) for enhanced frontmatter and configuration handling
- Extensive docstrings throughout codebase for improved maintainability
- Config directory existence check for enhanced error handling
- **Remote Image Download**: Automatic download and embedding of remote images (http:// and https:// URLs) during export. Works with both wikilink-style embeds `![[https://...]]` and standard markdown images `![alt](https://...)`. Falls back to placeholder text if download fails (10-second timeout)
- **Windows Compatibility**: Comprehensive Windows executable detection with platform-specific extensions (.cmd, .bat, .ps1, .exe) - **Windows Compatibility**: Comprehensive Windows executable detection with platform-specific extensions (.cmd, .bat, .ps1, .exe)
- **Dynamic Image Format Support**: FileDiscovery now supports multiple image formats (.png, .jpg, .jpeg, .webp, .gif, .bmp, .tiff) - **Dynamic Image Format Support**: FileDiscovery now supports multiple image formats (.png, .jpg, .jpeg, .webp, .gif, .bmp, .tiff)
- **Enhanced Pattern Matching**: Five-strategy file discovery system for robust PDF-to-image conversion output detection - **Enhanced Pattern Matching**: Five-strategy file discovery system for robust PDF-to-image conversion output detection
@@ -15,6 +40,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Improved Plugin Isolation**: TempDirectoryManager now uses proper plugin namespacing to prevent conflicts - **Improved Plugin Isolation**: TempDirectoryManager now uses proper plugin namespacing to prevent conflicts
### Fixed ### Fixed
- Path doubling issues in directory creation and file operations
- Executable path resolution on Windows for better cross-platform compatibility
- Bibliography errors by properly handling YAML parsing conflicts
- Image download order to ensure correct processing sequence
- Images without extensions now handled correctly
- **Windows Absolute Path Handling**: Fixed ENOENT errors on Windows caused by improper path joining when combining vault paths with plugin directories. PathUtils.joinPath() now properly detects and handles absolute paths using path.isAbsolute() to prevent invalid path construction like `C:\MyVault\C:\MyVault\...`
- **Remote URL Image Handling**: Fixed ENOENT errors when markdown contains remote image URLs. Remote images are now automatically downloaded and embedded, with graceful fallback to placeholder text if download fails
- **Cross-Platform Binary Discovery**: BinaryLocator now includes comprehensive fallback paths for different installation methods - **Cross-Platform Binary Discovery**: BinaryLocator now includes comprehensive fallback paths for different installation methods
- **Vault-Relative Path Consistency**: Fixed all vault.adapter operations to use proper vault-relative paths instead of absolute paths - **Vault-Relative Path Consistency**: Fixed all vault.adapter operations to use proper vault-relative paths instead of absolute paths
- **Resource Path Resolution**: Removed extra quotes from Pandoc arguments that could break spawn commands on Windows - **Resource Path Resolution**: Removed extra quotes from Pandoc arguments that could break spawn commands on Windows
@@ -22,16 +54,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Template Path Resolution**: Fixed resource path handling in PandocCommandBuilder for better cross-platform compatibility - **Template Path Resolution**: Fixed resource path handling in PandocCommandBuilder for better cross-platform compatibility
### Changed ### Changed
- Node.js requirement updated to version 18.20+ for latest LTS support
- Logging improvements: replaced 'info' with 'debug' for better log level hierarchy
- Path normalization simplified for Windows compatibility
- Refactored path handling throughout codebase for consistency and reliability
- Applied Obsidian linter rules and fixed code quality issues
- Standardized terminology and error handling across modules
- Automated cleanup with async lifecycle handling for better resource management
- **Enhanced Error Recovery**: Improved fallback mechanisms and graceful degradation throughout font and file discovery systems - **Enhanced Error Recovery**: Improved fallback mechanisms and graceful degradation throughout font and file discovery systems
- **Platform Detection**: Added platform awareness to caching systems for better cross-platform consistency - **Platform Detection**: Added platform awareness to caching systems for better cross-platform consistency
- **Code Quality**: Improved type safety, error handling, and validation across all affected modules - **Code Quality**: Improved type safety, error handling, and validation across all affected modules
- **Performance**: Optimized file discovery with progressive pattern matching strategies - **Performance**: Optimized file discovery with progressive pattern matching strategies
### Security ### Security
- Sanitizes frontmatter to prevent data leakage in exports
- Rejects absolute paths in vault exports for improved security
- Restricts shell metacharacters in paths to prevent injection attacks
- Strengthens path validation against reserved names and reserved filesystem names
- Enhanced cleanup ensures proper resource disposal
- **Path Validation**: Enhanced path sanitization and validation for all file system operations - **Path Validation**: Enhanced path sanitization and validation for all file system operations
- **Process Spawning**: Improved security in font discovery and binary execution with proper argument handling - **Process Spawning**: Improved security in font discovery and binary execution with proper argument handling
## [1.3.0] - 2024-12-25 ## [1.3.0] - 2025-09-25
### Added ### Added
- PathUtils helper class for centralized path operations and safe Obsidian API usage - PathUtils helper class for centralized path operations and safe Obsidian API usage
@@ -52,7 +96,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Enhanced error handling and path validation across all modules - Enhanced error handling and path validation across all modules
- Updated all 16 core files with consistent, safe path handling practices - Updated all 16 core files with consistent, safe path handling practices
## [1.2.1] - 2025-01-10 ## [1.2.1] - 2025-09-10
### Fixed ### Fixed
- **Horizontal Rule Processing**: Resolved YAML parsing conflicts when documents contain horizontal rules (`---`) - **Horizontal Rule Processing**: Resolved YAML parsing conflicts when documents contain horizontal rules (`---`)
@@ -69,7 +113,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Improved type safety throughout the codebase - Improved type safety throughout the codebase
- Enhanced code maintainability with proper type assertions - Enhanced code maintainability with proper type assertions
## [1.2.0] - 2025-01-10 ## [1.2.0] - 2025-09-10
### Changed ### Changed
- **Major Refactoring**: Complete modularization of codebase for improved maintainability - **Major Refactoring**: Complete modularization of codebase for improved maintainability
+15 -12
View File
@@ -73,7 +73,7 @@ Typst offers several advantages over standard PDF export:
**⚠️ Important**: This plugin requires template files to function. Always use the complete ZIP package. **⚠️ Important**: This plugin requires template files to function. Always use the complete ZIP package.
1. Go to [GitHub Releases](https://github.com/akucera/obsidian-typst-pdf-export/releases) 1. Go to [GitHub Releases](https://github.com/AlexKucera/obsidian-typst-pdf-export/releases)
2. Download the **complete ZIP package** (`typst-pdf-export.zip`) - **NOT just main.js** 2. Download the **complete ZIP package** (`typst-pdf-export.zip`) - **NOT just main.js**
3. Extract the entire contents to `{VaultFolder}/.obsidian/plugins/typst-pdf-export/` 3. Extract the entire contents to `{VaultFolder}/.obsidian/plugins/typst-pdf-export/`
4. Ensure the `templates/` directory is included with all `.typ` files: 4. Ensure the `templates/` directory is included with all `.typ` files:
@@ -95,7 +95,7 @@ Typst offers several advantages over standard PDF export:
### Method 3: BRAT (Beta Reviewer's Auto-update Tool) ### Method 3: BRAT (Beta Reviewer's Auto-update Tool)
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat) 1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
2. Add this repository: `akucera/obsidian-typst-pdf-export` 2. Add this repository: `https://github.com/AlexKucera/obsidian-typst-pdf-export`
3. Enable the plugin after installation 3. Enable the plugin after installation
### Method 4: Developer Installation ### Method 4: Developer Installation
@@ -105,7 +105,7 @@ For development or the latest changes:
1. Clone the repository to your vault's plugins folder: 1. Clone the repository to your vault's plugins folder:
```bash ```bash
cd {VaultFolder}/.obsidian/plugins/ cd {VaultFolder}/.obsidian/plugins/
git clone https://github.com/akucera/obsidian-typst-pdf-export.git typst-pdf-export git clone https://github.com/AlexKucera/obsidian-typst-pdf-export.git typst-pdf-export
cd typst-pdf-export cd typst-pdf-export
``` ```
2. Install dependencies and build: 2. Install dependencies and build:
@@ -131,9 +131,9 @@ For development or the latest changes:
### 1. Install Dependencies ### 1. Install Dependencies
**Required:** **Required:**
- [Pandoc](https://pandoc.org/installing.html) - Markdown to Typst conversion - [Pandoc](https://pandoc.org/installing.html) 3.7.0+ - Markdown to Typst conversion
- [Typst](https://typst.app/docs/reference/foundations/) - PDF generation - [Typst](https://typst.app/docs/reference/foundations/) 0.13.0+ - PDF generation
- [ImageMagick](https://imagemagick.org/script/download.php) - Enhanced image processing - [ImageMagick](https://imagemagick.org/script/download.php) 7.1.2+ - Enhanced image processing
### 2. Export Your First Note ### 2. Export Your First Note
@@ -169,15 +169,17 @@ Go to the plugin settings and click **Check Dependencies** to ensure all require
- **Obsidian**: Version 1.9.12 or higher - **Obsidian**: Version 1.9.12 or higher
- **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it. - **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it.
- **Node.js**: Version 16+ (for development) - **Node.js**: Version 18.20+ (for development)
### External Dependencies ### External Dependencies
| Tool | Purpose | Installation | | Tool | Minimum Version | Purpose | Installation |
|------|---------|-------------| |------|----------------|---------|-------------|
| **Pandoc** | Markdown → Typst conversion | [Download here](https://pandoc.org/installing.html) or `brew install pandoc` | | **Pandoc** | 3.7.0 | Markdown → Typst conversion | [Download here](https://pandoc.org/installing.html) or `brew install pandoc` |
| **Typst** | PDF generation | [Download here](https://typst.app/docs/reference/foundations/) or `brew install typst` | | **Typst** | 0.13.0 | PDF generation | [Download here](https://typst.app/docs/reference/foundations/) or `brew install typst` |
| **ImageMagick** | Enhanced image processing (optional) | [Download here](https://imagemagick.org/script/download.php) or `brew install imagemagick` | | **ImageMagick** | 7.1.2 | Enhanced image processing (optional) | [Download here](https://imagemagick.org/script/download.php) or `brew install imagemagick` |
**Note**: The plugin will display warnings if your installed versions are below the minimum requirements. While older versions may work, they are not officially supported and may cause compatibility issues.
### Dependency Verification ### Dependency Verification
@@ -259,6 +261,7 @@ JB
|---------|----------| |---------|----------|
| **"Pandoc not found"** | Install Pandoc and ensure it's in your system PATH | | **"Pandoc not found"** | Install Pandoc and ensure it's in your system PATH |
| **"Typst not found"** | Install Typst CLI and verify PATH configuration | | **"Typst not found"** | Install Typst CLI and verify PATH configuration |
| **Outdated version warning** | Update dependencies to meet minimum versions (Pandoc 3.7.0+, Typst 0.13.0+, ImageMagick 7.1.2+) |
| **Export hangs** | Check if files are locked by other applications | | **Export hangs** | Check if files are locked by other applications |
| **Images not showing** | Verify image paths and file permissions | | **Images not showing** | Verify image paths and file permissions |
| **Template errors** | Check template syntax and file integrity | | **Template errors** | Check template syntax and file integrity |
+82 -39
View File
@@ -1,57 +1,100 @@
// @ts-check // @ts-check
import eslint from '@eslint/js'; import js from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint'; import tseslint from 'typescript-eslint';
import obsidianmd from 'eslint-plugin-obsidianmd';
import importPlugin from 'eslint-plugin-import';
import globals from 'globals';
export default tseslint.config( export default tseslint.config(
// Apply ESLint recommended rules // Base JavaScript recommended rules
eslint.configs.recommended, js.configs.recommended,
// Apply TypeScript-ESLint recommended rules
...tseslint.configs.recommended, // TypeScript recommended type-checked rules
...tseslint.configs.recommendedTypeChecked,
// Obsidian-specific configuration
{ {
// Configure language options plugins: {
obsidianmd: obsidianmd,
import: importPlugin,
},
languageOptions: { languageOptions: {
globals: { globals: {
...globals.node, ...globals.node,
...globals.es2022, ...globals.browser,
NodeJS: 'readonly', // TypeScript global namespace
}, },
parserOptions: { parserOptions: {
sourceType: 'module', projectService: true,
ecmaVersion: 2022, tsconfigRootDir: import.meta.dirname,
}, },
}, },
// Configure files to lint // Apply Obsidian plugin recommended rules (manually specified)
files: ['**/*.ts', '**/*.js', 'main.ts'],
// Configure rules - incorporating Obsidian sample plugin settings
rules: { rules: {
// Disable base ESLint no-unused-vars in favor of TypeScript version // Obsidian command rules
'obsidianmd/commands/no-command-in-command-id': 'error',
'obsidianmd/commands/no-command-in-command-name': 'error',
'obsidianmd/commands/no-default-hotkeys': 'error',
'obsidianmd/commands/no-plugin-id-in-command-id': 'error',
'obsidianmd/commands/no-plugin-name-in-command-name': 'error',
// Settings tab rules
'obsidianmd/settings-tab/no-manual-html-headings': 'error',
'obsidianmd/settings-tab/no-problematic-settings-headings': 'error',
// Other Obsidian rules
'obsidianmd/vault/iterate': 'error',
'obsidianmd/detach-leaves': 'error',
'obsidianmd/hardcoded-config-path': 'error',
'obsidianmd/no-forbidden-elements': 'error',
'obsidianmd/no-plugin-as-component': 'error',
'obsidianmd/no-sample-code': 'error',
'obsidianmd/no-tfile-tfolder-cast': 'error',
'obsidianmd/no-view-references-in-plugin': 'error',
'obsidianmd/no-static-styles-assignment': 'error',
'obsidianmd/object-assign': 'error',
'obsidianmd/platform': 'error',
'obsidianmd/prefer-file-manager-trash-file': 'warn',
'obsidianmd/prefer-abstract-input-suggest': 'error',
'obsidianmd/regex-lookbehind': 'error',
'obsidianmd/sample-names': 'error',
'obsidianmd/validate-manifest': 'error',
'obsidianmd/validate-license': 'error',
'obsidianmd/ui/sentence-case': ['warn', { enforceCamelCaseLower: true }],
// General ESLint rules from Obsidian recommended
'no-unused-vars': 'off', 'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
// Allow @ts-ignore comments (useful for Obsidian API quirks)
'@typescript-eslint/ban-ts-comment': 'off',
// Allow prototype builtins usage
'no-prototype-builtins': 'off', 'no-prototype-builtins': 'off',
'no-self-compare': 'warn',
// Allow empty functions (common in plugin architecture) 'no-eval': 'error',
'@typescript-eslint/no-empty-function': 'off', 'no-implied-eval': 'error',
'prefer-const': 'off',
// Allow require() imports (Node.js environment with mixed modules) 'no-implicit-globals': 'error',
'@typescript-eslint/no-require-imports': 'off', 'no-console': ['error', { allow: ['warn', 'error', 'debug'] }],
'@typescript-eslint/no-var-requires': 'off', 'no-alert': 'error',
'no-undef': 'error',
// Obsidian plugins often use 'any' type for API flexibility
'@typescript-eslint/no-explicit-any': 'warn', // TypeScript rules from Obsidian recommended
'@typescript-eslint/ban-ts-comment': 'off',
// Allow lexical declarations in case blocks '@typescript-eslint/no-deprecated': 'error',
'no-case-declarations': 'off', '@typescript-eslint/require-await': 'off',
'@typescript-eslint/no-explicit-any': ['error', { fixToUnknown: true }],
// Prefer const is good but not critical for existing code
'prefer-const': 'warn', // Downgrade strict type checking rules to warnings
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-unsafe-call': 'warn',
'@typescript-eslint/no-unsafe-return': 'warn',
// Unused vars with underscore prefix
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
// Import rules
'import/no-extraneous-dependencies': 'error',
}, },
}, },
{ {
@@ -65,4 +108,4 @@ export default tseslint.config(
'coverage/**', 'coverage/**',
], ],
} }
); );
+9 -8
View File
@@ -11,6 +11,7 @@ import {
Notice, Notice,
MarkdownView MarkdownView
} from 'obsidian'; } from 'obsidian';
import { shell } from 'electron';
import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS } from './src/core/settings'; import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS } from './src/core/settings';
import { DependencyChecker } from './src/core/DependencyChecker'; import { DependencyChecker } from './src/core/DependencyChecker';
@@ -177,8 +178,8 @@ export class obsidianTypstPDFExport extends Plugin {
); );
} }
async checkDependenciesAsync(): Promise<void> { checkDependenciesOnStartup(): void {
return DependencyChecker.checkDependenciesAsync( DependencyChecker.checkDependenciesOnStartup(
this.settings.pandocPath, this.settings.pandocPath,
this.settings.typstPath, this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath, this.settings.executablePaths?.imagemagickPath,
@@ -212,8 +213,7 @@ export class obsidianTypstPDFExport extends Plugin {
* Open a PDF file in the default viewer * Open a PDF file in the default viewer
*/ */
openPDF(pdfPath: string): void { openPDF(pdfPath: string): void {
const { shell } = require('electron'); void shell.openPath(pdfPath);
shell.openPath(pdfPath);
} }
async loadSettings() { async loadSettings() {
@@ -236,11 +236,12 @@ export class obsidianTypstPDFExport extends Plugin {
throw error; // Re-throw to let callers handle appropriately throw error; // Re-throw to let callers handle appropriately
} }
} }
onunload() { // eslint-disable-next-line @typescript-eslint/no-misused-promises -- Obsidian supports async onunload and will await it properly, even though the Plugin type definition shows void return. This ensures cleanup completes.
async onunload(): Promise<void> {
// Use lifecycle manager for cleanup // Use lifecycle manager for cleanup
this.lifecycle.cleanup(); await this.lifecycle.cleanup();
} }
} }
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"id": "typst-pdf-export", "id": "typst-pdf-export",
"name": "Typst PDF Export", "name": "Typst PDF Export",
"version": "1.3.0", "version": "1.4.0",
"minAppVersion": "1.9.12", "minAppVersion": "1.9.12",
"description": "Exports a note or collection of notes to a pretty Typst PDF.", "description": "Exports a note or collection of notes to a pretty Typst PDF.",
"author": "Alexander Kucera", "author": "Alexander Kucera",
+194
View File
@@ -0,0 +1,194 @@
### Required
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L81-L81)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/mmandRegistry.ts#L37-L37)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L23-L23)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L38-L38)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L56-L56)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L325-L325)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L31-L31)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L50-L50)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L57-L57)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L65-L65)
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L67-L67)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L80-L80)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L82-L82)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L94-L94)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L95-L95)
[16](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L97-L97)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L134-L134)
[18](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L138-L138)
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L160-L160)
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L179-L179)
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L182-L182)
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L232-L232)
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L138-L138)
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L222-L222)
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/BehaviorSection.ts#L14-L14)
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/neralSection.ts#L21-L21)
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L75-L75)
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L78-L78)
[30](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/youtSection.ts#L16-L16)
[31](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L16-L16)
[32](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L72-L72)
[33](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L166-L166)
[34](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L167-L167)
[35](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L174-L174)
[36](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L194-L194)
[37](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L195-L195)
[38](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L199-L199)
[39](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L200-L200)
[40](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L201-L201)
Use sentence case for UI text.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L215-L215)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/naryLocator.ts#L154-L154)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L38-L38)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L115-L115)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L183-L183)
[6](https://github.com/exKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L61-L61)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L111-L111)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L236-L236)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L252-L252)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L264-L264)
[11](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L114-L114)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L115-L115)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L35-L35)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L46-L46)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
[16](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
[18](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/eprocessors/FrontmatterProcessor.ts#L208-L208)
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L51-L51)
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ecutableChecker.ts#L128-L128)
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L158-L158)
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L215-L215)
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/PathUtils.ts#L115-L115)
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EmbedProcessor.ts#L164-L164)
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/bedProcessor.ts#L165-L165)
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/FontManager.ts#L19-L19)
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PathResolver.ts#L29-L29)
A `require()` style import is forbidden.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/MarkdownPreprocessor.ts#L117-L117)
Async method 'process' has no 'await' expression.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L138-L138)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/plugin/CommandRegistry.ts#L21-L21)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L30-L30)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L39-L39)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L26-L26)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L41-L41)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/entHandlers.ts#L59-L59)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L68-L68)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L95-L95)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L104-L104)
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L56-L56)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/uginLifecycle.ts#L59-L59)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L72-L80)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L88-L101)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L86-L86)
[16](https://github.com/AlexKucerabsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L122-L122)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L19-L19)
Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L180-L180)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/converters/PandocTypstConverter.ts#L187-L187)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/BinaryLocator.ts#L33-L33)
Obsidian's configuration folder is not necessarily `.obsidian`, can be configured by the user. Use `Vault#configDir` to get the current value
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L35-L35)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
[6](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L208-L208)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
'js-yaml' should be listed in the project's dependencies. n 'npm i -S js-yaml' to add it
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L49-L49)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L50-L50)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L155-L155)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L156-L156)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExportErrorHandler.ts#L64-L64)
Unexpected console statement. Only these console methods are allowed: warn, error, debug.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L275-L275)
'value' will use Object's default stringification format ('[object Object]') when ringified.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/DependencyChecker.ts#L122-L122)
Static async method 'checkDependenciesAsync' has no 'await' expression.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ModalSettingsHelper.ts#L72-L72)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/dal/sections/PageSetupSection.ts#L60-L60)
The two values in this comparison do not have a shared enum type.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/SecurityUtils.ts#L56-L56)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/curityUtils.ts#L117-L117)
Unexpected undescribed directive comment. Include descriptions to explain why the comment is necessary.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L51-L51)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/portOrchestrator.ts#L322-L322)
A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object. Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an intended `this` value. If a function does not access `this`, it can be annotated with `this: void`.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L89-L91)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ugin/ExportOrchestrator.ts#L124-L126)
Promise returned in function argument where a void return was expected.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L160-L160)
`noticeEl` is deprecated. Use `messageEl` instead
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L31-L31)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L50-L50)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L134-L134)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L232-L232)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L366-L366)
For a consistent UI use `new Setting(containerEl).setName(...).setHeading()` instead of creating HTML heading elements directly.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/templates/TemplateManager.ts#L132-L132)
Unexpected lexical declaration in case block.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L50-L50)
Promise-returning function provided to property where a void return was expected.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L152-L152)
Unexpected `await` of a non-Promise (non-"Thenable") value.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L260-L260)
Creating and attaching "style" elements is not allowed. For loading CSS, use a "styles.css" file instead, which sidian loads for you.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/state/ModalState.ts#L192-L192)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/uiodal/state/ModalState.ts#L203-L203)
Unexpected use of 'localStorage'. Prefer `App#saveLocalStorage` / `App#loadLocalStorage` functions to write / read localStorage data that's unique to a vault.
### Optional
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L92-L92)
'_result' is assigned a value but never used.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L124-L124)
'_progressPercent' is assigned a value but never used.
+5405 -460
View File
File diff suppressed because it is too large. Load diff
+22 -5
View File
@@ -1,6 +1,6 @@
{ {
"name": "obsidian-typst-pdf-export", "name": "obsidian-typst-pdf-export",
"version": "1.3.0", "version": "1.4.0",
"description": "Exports a note or collection of notes to a pretty Typst PDF.", "description": "Exports a note or collection of notes to a pretty Typst PDF.",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
@@ -8,6 +8,10 @@
"lint": "eslint src/ main.ts", "lint": "eslint src/ main.ts",
"dev": "npm run typecheck && node esbuild.config.mjs", "dev": "npm run typecheck && node esbuild.config.mjs",
"build": "npm run typecheck && npm run lint && node esbuild.config.mjs production", "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", "package": "node scripts/package-plugin.js",
"version": "node version-bump.mjs && git add manifest.json versions.json" "version": "node version-bump.mjs && git add manifest.json versions.json"
}, },
@@ -20,23 +24,36 @@
], ],
"author": "Alexander Kucera", "author": "Alexander Kucera",
"license": "MIT", "license": "MIT",
"engines": {
"node": ">=18.20.0"
},
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3.3.1", "@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.34.0", "@eslint/js": "^9.34.0",
"@types/node": "^16.11.6", "@types/js-yaml": "^4.0.9",
"@typescript-eslint/eslint-plugin": "5.29.0", "@types/node": "^20.19.24",
"@typescript-eslint/parser": "5.29.0", "@typescript-eslint/eslint-plugin": "^8.46.3",
"@typescript-eslint/parser": "^8.46.3",
"@typescript-eslint/utils": "^8.46.3",
"@vitest/coverage-v8": "^4.0.6",
"@vitest/ui": "^4.0.6",
"archiver": "^7.0.1", "archiver": "^7.0.1",
"builtin-modules": "3.3.0", "builtin-modules": "3.3.0",
"electron": "^33.3.0",
"esbuild": "0.17.3", "esbuild": "0.17.3",
"eslint": "^9.39.1",
"eslint-plugin-obsidianmd": "^0.1.8",
"globals": "^16.3.0", "globals": "^16.3.0",
"happy-dom": "^20.0.10",
"obsidian": "latest", "obsidian": "latest",
"tslib": "2.4.0", "tslib": "2.4.0",
"typescript": "^5.9.2", "typescript": "^5.9.2",
"typescript-eslint": "^8.43.0" "typescript-eslint": "^8.43.0",
"vitest": "^4.0.6"
}, },
"dependencies": { "dependencies": {
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"js-yaml": "^4.1.0",
"pdf-to-img": "^4.5.0" "pdf-to-img": "^4.5.0"
} }
} }
+503 -10
View File
@@ -1,6 +1,35 @@
/** /**
* MarkdownPreprocessor - Converts Obsidian-specific markdown syntax to standard markdown * Markdown preprocessing pipeline for Obsidian-to-Pandoc conversion.
* compatible with Pandoc for Typst PDF export *
* 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'; import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor';
@@ -9,7 +38,15 @@ import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProce
import { CalloutProcessor } from './preprocessors/CalloutProcessor'; import { CalloutProcessor } from './preprocessors/CalloutProcessor';
import { MetadataExtractor } from './preprocessors/MetadataExtractor'; import { MetadataExtractor } from './preprocessors/MetadataExtractor';
import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor'; 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 { export interface PreprocessorOptions {
/** Preserve existing frontmatter */ /** Preserve existing frontmatter */
preserveFrontmatter: boolean; preserveFrontmatter: boolean;
@@ -19,7 +56,24 @@ export interface PreprocessorOptions {
printFrontmatter?: boolean; 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 { export interface PreprocessingResult {
/** Processed markdown content */ /** Processed markdown content */
content: string; content: string;
@@ -60,6 +114,36 @@ export interface PreprocessingResult {
warnings: string[]; 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 { export interface MarkdownPreprocessorConfig {
/** Vault path for file resolution */ /** Vault path for file resolution */
vaultPath: string; vaultPath: string;
@@ -71,6 +155,72 @@ export interface MarkdownPreprocessorConfig {
noteTitle?: string; 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 = 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 = preprocessor.process(markdown);
* ```
*/
export class MarkdownPreprocessor { export class MarkdownPreprocessor {
private vaultPath: string; private vaultPath: string;
private options: PreprocessorOptions; private options: PreprocessorOptions;
@@ -112,9 +262,73 @@ 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.
*
* 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 = 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 = 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> { public process(content: string): PreprocessingResult {
const result: PreprocessingResult = { const result: PreprocessingResult = {
content: content, content: content,
metadata: { metadata: {
@@ -141,7 +355,12 @@ export class MarkdownPreprocessor {
// Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added) // Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
result.content = this.embedProcessor.processEmbeds(result.content, result); result.content = this.embedProcessor.processEmbeds(result.content, result);
// Step 5.5: Handle standard markdown images with remote URLs
// Process after embeds (which handle ![[]] syntax) but before wikilinks
// to ensure remote URLs in standard markdown ![](url) format are queued for download
result.content = this.processStandardMarkdownImages(result.content, result);
// Step 6: Convert wikilinks (after embeds are processed) // Step 6: Convert wikilinks (after embeds are processed)
result.content = this.wikilinkProcessor.processWikilinks(result.content, result); result.content = this.wikilinkProcessor.processWikilinks(result.content, result);
@@ -159,9 +378,163 @@ export class MarkdownPreprocessor {
return result; return result;
} }
/** /**
* Update configuration * 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)
const markdownImagePattern = /!\[([^\]]*)\]\(([^)]+)\)/g;
return content.replace(markdownImagePattern, (match, alt, url) => {
// Check if this is a remote URL (http:// or https://)
const isRemoteUrl = /^https?:\/\//i.test(url.trim());
if (isRemoteUrl) {
const cleanUrl = url.trim();
// Extract filename from URL for tracking
let fileName = 'remote-image.png';
try {
const urlObj = new URL(cleanUrl);
fileName = path.basename(urlObj.pathname) || fileName;
} catch {
// Use default if URL parsing fails
}
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
// Create a marker that the export process can detect and replace
const marker = `IMAGE_EMBED_MARKER:${cleanUrl}:${baseName}:${alt || ''}`;
// Add to processing queue for later download and embedding
if (!result.metadata.imageEmbeds) {
result.metadata.imageEmbeds = [];
}
result.metadata.imageEmbeds.push({
originalPath: cleanUrl,
sanitizedPath: cleanUrl, // For remote URLs, sanitized = original
fileName: fileName,
baseName: baseName,
sizeOrAlt: alt,
marker: marker
});
result.warnings.push(`Remote URL image queued for download: ${cleanUrl}`);
return marker;
}
// Keep local images as-is for normal processing
return match;
});
}
/**
* 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 = 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 = 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 { public updateConfig(config: Partial<MarkdownPreprocessorConfig>): void {
if (config.vaultPath) { if (config.vaultPath) {
@@ -189,7 +562,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 { public getConfig(): MarkdownPreprocessorConfig {
return { return {
@@ -200,12 +614,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 = { export const DEFAULT_PREPROCESSOR_OPTIONS: PreprocessorOptions = {
preserveFrontmatter: true, preserveFrontmatter: true,
baseUrl: '' 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 = { export const DEFAULT_WIKILINK_CONFIG: WikilinkConfig = {
format: 'md', format: 'md',
extension: '.md' extension: '.md'
+229 -41
View File
@@ -1,28 +1,111 @@
/** /**
* Pandoc to Typst PDF Converter * Pandoc to Typst PDF Converter.
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine *
* 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 with cleanup via the plugin lifecycle.
*/ */
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes'; import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { TempDirectoryManager } from '../core/TempDirectoryManager'; import { TempDirectoryManager } from '../core/TempDirectoryManager';
import { PathUtils } from '../core/PathUtils'; import { PathUtils } from '../core/PathUtils';
import { promises as fs } from 'fs';
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder'; import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor'; 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
* - Cleanup via plugin lifecycle (onunload)
* - 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. Plugin unload calls dispose() to remove temporary files
* 5. dispose() can also be called manually for 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 { export class PandocTypstConverter {
private tempDir: string | null = null; private tempDir: string | null = null;
private cleanupHandlers: (() => void)[] = []; private cleanupHandlers: (() => void)[] = [];
private plugin: obsidianTypstPDFExport; private plugin: obsidianTypstPDFExport;
private commandBuilder: PandocCommandBuilder; private commandBuilder: PandocCommandBuilder;
private pandocExecutor: PandocExecutor; private pandocExecutor: PandocExecutor;
private isDisposed = false;
/** /**
* Create a new PandocTypstConverter instance * Creates a new PandocTypstConverter instance with configuration.
* @param plugin The main plugin instance for accessing settings *
* @param pandocOptions Configuration options for Pandoc * Initializes the converter with the plugin instance and configuration options
* @param typstSettings Settings specific to Typst engine * for both Pandoc and Typst. Temporary files are cleaned up via dispose()
* which is called during plugin unload.
*
* @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( constructor(
plugin: obsidianTypstPDFExport, plugin: obsidianTypstPDFExport,
@@ -32,20 +115,49 @@ export class PandocTypstConverter {
this.plugin = plugin; this.plugin = plugin;
this.commandBuilder = new PandocCommandBuilder(plugin); this.commandBuilder = new PandocCommandBuilder(plugin);
this.pandocExecutor = new PandocExecutor(plugin); this.pandocExecutor = new PandocExecutor(plugin);
// Set up cleanup handlers for process termination
this.setupCleanup();
} }
/** /**
* Convert a markdown file to PDF using Pandoc with Typst engine * Converts a Markdown file to PDF using the Pandoc → Typst → PDF pipeline.
* @param inputPath Path to the input markdown file *
* @param outputPath Path where the PDF should be saved * This is the primary conversion method that handles the complete export process:
* @param progressCallback Optional callback for progress updates * 1. Creates temporary directory for intermediate files
* @returns Promise resolving to conversion result * 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( async convertToPDF(
inputPath: string, inputPath: string,
outputPath: string, outputPath: string,
progressCallback?: ProgressCallback progressCallback?: ProgressCallback
): Promise<ConversionResult> { ): Promise<ConversionResult> {
try { try {
@@ -73,10 +185,9 @@ export class PandocTypstConverter {
// Add the output path to the result if successful // Add the output path to the result if successful
if (result.success) { if (result.success) {
result.outputPath = outputPath; result.outputPath = outputPath;
progressCallback?.('Conversion complete!', 100);
} }
progressCallback?.('Conversion complete!', 100);
return result; return result;
} catch (error) { } catch (error) {
@@ -89,7 +200,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( async convertMarkdownToPDF(
content: string, content: string,
@@ -105,7 +252,8 @@ export class PandocTypstConverter {
const pathUtils = new PathUtils(this.plugin.app); const pathUtils = new PathUtils(this.plugin.app);
const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`); const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
await this.plugin.app.vault.adapter.write(tempInputPath, content); // Use fs.writeFile for temp files since external tools (Pandoc) need absolute paths
await fs.writeFile(tempInputPath, content, 'utf-8');
// Merge options // Merge options
this.pandocOptions = { ...this.pandocOptions, ...options }; this.pandocOptions = { ...this.pandocOptions, ...options };
@@ -115,7 +263,8 @@ export class PandocTypstConverter {
// Cleanup temp file // Cleanup temp file
try { try {
await this.plugin.app.vault.adapter.remove(tempInputPath); // Use fs.unlink for temp files since they're in external temp directories
await fs.unlink(tempInputPath);
} catch (error) { } catch (error) {
console.warn('Failed to cleanup temp file:', error); console.warn('Failed to cleanup temp file:', error);
} }
@@ -131,22 +280,16 @@ export class PandocTypstConverter {
} }
/** /**
* Set up cleanup handlers for temporary files * Cleans up temporary files and directories.
*/ *
private setupCleanup(): void { * This method executes all registered cleanup handlers and removes the temporary
const cleanup = () => { * directory created by the converter. Cleanup failures are logged but don't throw
this.cleanup(); * to avoid interfering with normal operation or other cleanup operations.
}; *
* Called via dispose() during plugin unload.
process.on('exit', cleanup); *
process.on('SIGINT', cleanup); * @private
process.on('SIGTERM', cleanup); * @returns Promise that resolves when cleanup is complete
process.on('uncaughtException', cleanup);
}
/**
* Clean up temporary files and directories
*/ */
private async cleanup(): Promise<void> { private async cleanup(): Promise<void> {
try { try {
@@ -171,20 +314,38 @@ 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> { private async ensureTempDirectory(): Promise<string> {
if (!this.tempDir) { if (!this.tempDir) {
if (this.pandocOptions.vaultBasePath) { if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories // Use TempDirectoryManager for plugin temp directories
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian'; const configDir = this.plugin?.app?.vault?.configDir;
if (!configDir) {
throw new Error('Unable to access vault configuration directory. Plugin may not be properly initialized.');
}
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app); const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc'); this.tempDir = await tempManager.ensureTempDir('pandoc');
} else { } else {
// Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback // Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
const pathUtils = new PathUtils(this.plugin.app); const pathUtils = new PathUtils(this.plugin.app);
const vaultPath = pathUtils.getVaultPath(); const vaultPath = pathUtils.getVaultPath();
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian'; const configDir = this.plugin?.app?.vault?.configDir;
if (!configDir) {
throw new Error('Unable to access vault configuration directory. Plugin may not be properly initialized.');
}
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app }); const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
this.tempDir = await tempManager.ensureTempDir('pandoc'); this.tempDir = await tempManager.ensureTempDir('pandoc');
} }
@@ -194,9 +355,36 @@ 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.
*
* This method also removes all registered process event listeners to prevent
* memory leaks and allow the converter instance to be garbage collected.
*
* @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> { async dispose(): Promise<void> {
if (this.isDisposed) {
return; // Already disposed, avoid double-cleanup
}
this.isDisposed = true;
// Cleanup temporary files and resources
await this.cleanup(); await this.cleanup();
} }
} }
+442 -10
View File
@@ -1,6 +1,39 @@
/** /**
* PDF to Image Converter using pdf-to-img * PDF to Image conversion for embedded PDF files in Obsidian notes.
* Converts PDF files to PNG images for preview in Typst exports *
* 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'; import * as path from 'path';
@@ -11,6 +44,51 @@ import { FileDiscovery } from './pdf/FileDiscovery';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils'; 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 { export interface PdfConversionOptions {
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */ /** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
scale?: number; scale?: number;
@@ -24,6 +102,58 @@ export interface PdfConversionOptions {
quality?: number; 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 { export interface PdfConversionResult {
/** Path to the generated image file */ /** Path to the generated image file */
imagePath: string; imagePath: string;
@@ -43,15 +173,124 @@ export interface PdfConversionResult {
error?: string; 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 { export class PdfToImageConverter {
private static instance: PdfToImageConverter; private static instance: PdfToImageConverter;
private plugin: obsidianTypstPDFExport | undefined; 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) { private constructor(plugin?: obsidianTypstPDFExport) {
this.plugin = plugin; 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 { public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter {
if (!PdfToImageConverter.instance) { if (!PdfToImageConverter.instance) {
PdfToImageConverter.instance = new PdfToImageConverter(plugin); 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( public async convertFirstPageToImage(
pdfPath: string, pdfPath: string,
outputDir: string, outputDir: string,
options: PdfConversionOptions = {} options: PdfConversionOptions = {}
): Promise<PdfConversionResult> { ): Promise<PdfConversionResult> {
try { try {
@@ -92,10 +413,11 @@ export class PdfToImageConverter {
}; };
} }
// Ensure output directory exists // Ensure output directory exists (convert absolute path to vault-relative for vault.adapter)
if (this.plugin?.app) { if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app); const pathUtils = new PathUtils(this.plugin.app);
await pathUtils.ensureDir(outputDir); const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
await pathUtils.ensureDir(relativeOutputDir);
} }
// Generate expected output file name for the first page // Generate expected output file name for the first page
@@ -180,14 +502,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> { public async isValidPdf(filePath: string): Promise<boolean> {
return await PdfProcessor.isValidPdf(filePath); 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<{ public async getPdfInfo(filePath: string): Promise<{
pageCount: number; pageCount: number;
+245 -9
View File
@@ -1,6 +1,50 @@
/** /**
* Pandoc Command Builder * Command-line argument builder for Pandoc-to-Typst PDF conversion.
* Handles construction of Pandoc command-line arguments for 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'; import * as path from 'path';
@@ -11,12 +55,58 @@ import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils'; 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 { export class PandocCommandBuilder {
private plugin: obsidianTypstPDFExport; private plugin: obsidianTypstPDFExport;
private variableMapper: TypstVariableMapper; private variableMapper: TypstVariableMapper;
private resourcePathResolver: ResourcePathResolver; private resourcePathResolver: ResourcePathResolver;
private pathResolver: PathResolver; 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) { constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin; this.plugin = plugin;
this.variableMapper = new TypstVariableMapper(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[]> { async buildPandocArgs(inputPath: string, outputPath: string, pandocOptions: PandocOptions): Promise<string[]> {
const args: string[] = []; const args: string[] = [];
@@ -46,6 +201,7 @@ export class PandocCommandBuilder {
// Enable standalone mode (required for PDF output) // Enable standalone mode (required for PDF output)
args.push('--standalone'); args.push('--standalone');
// Embed resources (images, etc.) directly into the output // Embed resources (images, etc.) directly into the output
args.push('--embed-resources'); args.push('--embed-resources');
@@ -73,7 +229,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> { private async addResourcePaths(args: string[], pandocOptions: PandocOptions): Promise<void> {
if (!pandocOptions.vaultBasePath) { if (!pandocOptions.vaultBasePath) {
@@ -91,7 +260,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> { private async addTemplateConfiguration(args: string[], pandocOptions: PandocOptions): Promise<void> {
// Use universal wrapper with --template and pass actual template as template_path variable // Use universal wrapper with --template and pass actual template as template_path variable
@@ -125,19 +316,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 { private addTypstVariables(args: string[], pandocOptions: PandocOptions): void {
// Map all variables (ExportConfig + plugin settings fallbacks) using the variable mapper // Map all variables (ExportConfig + plugin settings fallbacks) using the variable mapper
const typstVariables = this.variableMapper.mapAllVariablesToTypst(pandocOptions); const typstVariables = this.variableMapper.mapAllVariablesToTypst(pandocOptions);
// Convert to pandoc arguments and add to args // Convert to pandoc arguments and add to args
const variableArgs = this.variableMapper.convertVariablesToPandocArgs(typstVariables); const variableArgs = this.variableMapper.convertVariablesToPandocArgs(typstVariables);
args.push(...variableArgs); 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 { private addTypstEngineOptions(args: string[], pandocOptions: PandocOptions): void {
if (pandocOptions.typstSettings?.engineOptions) { if (pandocOptions.typstSettings?.engineOptions) {
@@ -148,7 +372,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 { private addTypstDiagnostics(args: string[], pandocOptions: PandocOptions): void {
// Add Typst diagnostic options for better error reporting // 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'; import type { obsidianTypstPDFExport } from '../../../main';
/** /**
* Handles pandoc process execution, monitoring, and error parsing. * Process executor for Pandoc command-line conversions with progress monitoring.
* Manages the spawning and lifecycle of pandoc processes for document conversion. *
* 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 { export class PandocExecutor {
private pathResolver: PathResolver; private pathResolver: PathResolver;
/**
* Creates a new PandocExecutor.
*
* @param plugin - Plugin instance for accessing PathResolver configuration
*/
constructor(plugin: obsidianTypstPDFExport) { constructor(plugin: obsidianTypstPDFExport) {
this.pathResolver = new PathResolver(plugin); this.pathResolver = new PathResolver(plugin);
} }
/** /**
* Execute pandoc process with the given arguments * Executes Pandoc process with comprehensive monitoring and error handling.
* @param args Command line arguments for pandoc *
* @param pandocOptions Configuration options including paths and timeout * This is the primary execution method that spawns a Pandoc subprocess, monitors
* @param progressCallback Optional callback for progress updates * its progress, enforces timeouts, and returns a detailed result. The method is
* @returns Promise resolving to conversion result * 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( async executePandoc(
args: string[], args: string[],
pandocOptions: PandocOptions, pandocOptions: PandocOptions,
progressCallback?: ProgressCallback progressCallback?: ProgressCallback
): Promise<ConversionResult> { ): Promise<ConversionResult> {
return new Promise((resolve) => { return new Promise((resolve) => {
@@ -122,9 +244,59 @@ export class PandocExecutor {
} }
/** /**
* Parse progress information from pandoc output and update progress callback * Parses Pandoc's stderr output to detect conversion progress and update the UI.
* @param output Raw output from pandoc stderr *
* @param progressCallback Optional callback to update progress * 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 { private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void {
// Basic progress parsing - could be enhanced based on pandoc output patterns // 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 * Extracts meaningful, user-friendly error messages from Pandoc's raw output.
* @param stderr Standard error output from pandoc *
* @param stdout Standard output from pandoc * This method implements a multi-tier fallback strategy to find the most relevant
* @returns Formatted error message * 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 { private extractErrorMessage(stderr: string, stdout: string): string {
// Look for common error patterns // Look for common error patterns
@@ -154,7 +395,7 @@ export class PandocExecutor {
]; ];
const allOutput = (stderr + '\n' + stdout).split('\n'); const allOutput = (stderr + '\n' + stdout).split('\n');
for (const line of allOutput) { for (const line of allOutput) {
for (const pattern of errorPatterns) { for (const pattern of errorPatterns) {
if (pattern.test(line)) { if (pattern.test(line)) {
+12 -4
View File
@@ -3,6 +3,7 @@
* Handles discovery of pdf2img and other CLI tools in the Obsidian environment. * Handles discovery of pdf2img and other CLI tools in the Obsidian environment.
*/ */
import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils'; import { PathUtils } from '../../core/PathUtils';
@@ -29,8 +30,13 @@ export class BinaryLocator {
// Get the plugin directory - need to handle Obsidian's environment // Get the plugin directory - need to handle Obsidian's environment
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path // In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
// Try multiple strategies to find the plugin directory // Try multiple strategies to find the plugin directory
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export'; // Extract just the plugin folder name from manifest.dir (e.g., "typst-pdf-export" from ".obsidian/plugins/typst-pdf-export")
const configDir = plugin?.app.vault.configDir || '.obsidian'; const fullManifestDir = plugin?.manifest?.dir || 'typst-pdf-export';
const pluginDirName = path.basename(fullManifestDir);
const configDir = plugin?.app.vault.configDir;
if (!configDir) {
throw new Error('Unable to determine Obsidian configuration directory');
}
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir); const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
// Find the first directory that exists and has node_modules // Find the first directory that exists and has node_modules
@@ -131,13 +137,16 @@ export class BinaryLocator {
* @returns Array of possible plugin directory paths * @returns Array of possible plugin directory paths
*/ */
private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] { private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] {
const pathUtils = plugin ? new PathUtils(plugin.app) : null;
return [ return [
// Strategy 1: From process.cwd() if it's in the vault // Strategy 1: From process.cwd() if it's in the vault
path.join(process.cwd(), configDir, 'plugins', pluginDirName), path.join(process.cwd(), configDir, 'plugins', pluginDirName),
// Strategy 2: Assuming we're running from vault root // Strategy 2: Assuming we're running from vault root
path.join(configDir, 'plugins', pluginDirName), path.join(configDir, 'plugins', pluginDirName),
// Strategy 3: From vault base path if plugin is available // Strategy 3: From vault base path if plugin is available
...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : []) // Use PathUtils.joinPath to handle absolute paths correctly on Windows
...(pathUtils ? [pathUtils.joinPath(pathUtils.getVaultPath(), plugin!.manifest.dir!)] : [])
]; ];
} }
@@ -151,7 +160,6 @@ export class BinaryLocator {
try { try {
if (!plugin?.app) { if (!plugin?.app) {
// This should not happen in normal plugin operation, but provide fallback // This should not happen in normal plugin operation, but provide fallback
const fs = require('fs').promises;
await fs.access(binaryPath); await fs.access(binaryPath);
return true; return true;
} }
+2 -4
View File
@@ -3,6 +3,7 @@
* Handles filename pattern matching when pdf2img generates files with different names. * Handles filename pattern matching when pdf2img generates files with different names.
*/ */
import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import { PathUtils } from '../../core/PathUtils'; import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
@@ -35,7 +36,6 @@ export class FileDiscovery {
if (!plugin?.app) { if (!plugin?.app) {
// Fallback to path for external tool output directories // Fallback to path for external tool output directories
const expectedOutputPath = path.join(outputDir, expectedFileName); const expectedOutputPath = path.join(outputDir, expectedFileName);
const fs = require('fs').promises;
try { try {
await fs.access(expectedOutputPath); await fs.access(expectedOutputPath);
return { return {
@@ -112,8 +112,7 @@ export class FileDiscovery {
files = dirList.files.map(f => path.basename(f)); files = dirList.files.map(f => path.basename(f));
} else { } else {
// Use filesystem fallback for absolute/external paths // Use filesystem fallback for absolute/external paths
const fs = require('fs').promises; files = await fs.readdir(outputDir);
files = await fs.readdir(outputDir);
} }
// Look for any image files that might match // Look for any image files that might match
@@ -180,7 +179,6 @@ export class FileDiscovery {
expectedOutputPath: string expectedOutputPath: string
): Promise<FileDiscoveryResult> { ): Promise<FileDiscoveryResult> {
try { try {
const fs = require('fs').promises;
// Debug: List what files are actually in the output directory // Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir); const files = await fs.readdir(outputDir);
+17 -23
View File
@@ -3,6 +3,8 @@
* Handles format conversion, quality management, and dimension detection. * Handles format conversion, quality management, and dimension detection.
*/ */
import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import { PathUtils } from '../../core/PathUtils'; import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
@@ -58,7 +60,6 @@ export class ImageOptimizer {
quality: number = 90 quality: number = 90
): Promise<{success: boolean; error?: string}> { ): Promise<{success: boolean; error?: string}> {
try { try {
const { spawn } = require('child_process');
// Use ImageMagick to convert PNG to JPEG // Use ImageMagick to convert PNG to JPEG
const convertProcess = spawn('magick', [ const convertProcess = spawn('magick', [
@@ -108,7 +109,6 @@ export class ImageOptimizer {
fallbackDimensions: ImageDimensions = { width: 800, height: 600 } fallbackDimensions: ImageDimensions = { width: 800, height: 600 }
): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> { ): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> {
try { try {
const { spawn } = require('child_process');
// Use ImageMagick identify to get image dimensions // Use ImageMagick identify to get image dimensions
const identifyProcess = spawn('magick', [ const identifyProcess = spawn('magick', [
@@ -218,22 +218,10 @@ export class ImageOptimizer {
// Clean up the original PNG if conversion succeeded // Clean up the original PNG if conversion succeeded
try { try {
if (plugin?.app) { if (plugin?.app) {
// Convert absolute path to vault-relative path for adapter.remove()
const pathUtils = new PathUtils(plugin.app); const pathUtils = new PathUtils(plugin.app);
const vaultBasePath = pathUtils.getVaultPath(); const relativePath = pathUtils.toVaultRelative(inputImagePath);
let relativePath = inputImagePath;
if (inputImagePath.startsWith(vaultBasePath)) {
// Remove vault base path and leading separator
relativePath = inputImagePath.substring(vaultBasePath.length);
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.substring(1);
}
}
await plugin.app.vault.adapter.remove(relativePath); await plugin.app.vault.adapter.remove(relativePath);
} else { } else {
const fs = require('fs').promises;
await fs.unlink(inputImagePath); await fs.unlink(inputImagePath);
} }
} catch (unlinkError) { } catch (unlinkError) {
@@ -245,11 +233,14 @@ export class ImageOptimizer {
// Just rename the file to PNG format // Just rename the file to PNG format
const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png'); const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png');
if (plugin?.app) { if (plugin?.app) {
const content = await plugin.app.vault.adapter.readBinary(inputImagePath); const pathUtils = new PathUtils(plugin.app);
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content); const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
await plugin.app.vault.adapter.remove(inputImagePath); const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
await plugin.app.vault.adapter.writeBinary(relativePngPath, content);
await plugin.app.vault.adapter.remove(relativeInputPath);
} else { } else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, pngFinalPath); await fs.rename(inputImagePath, pngFinalPath);
} }
actualImagePath = pngFinalPath; actualImagePath = pngFinalPath;
@@ -257,11 +248,14 @@ export class ImageOptimizer {
} else { } else {
// Keep as PNG, just rename to final location // Keep as PNG, just rename to final location
if (plugin?.app) { if (plugin?.app) {
const content = await plugin.app.vault.adapter.readBinary(inputImagePath); const pathUtils = new PathUtils(plugin.app);
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content); const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
await plugin.app.vault.adapter.remove(inputImagePath); const relativeFinalPath = pathUtils.toVaultRelative(finalOutputPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
await plugin.app.vault.adapter.writeBinary(relativeFinalPath, content);
await plugin.app.vault.adapter.remove(relativeInputPath);
} else { } else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, finalOutputPath); await fs.rename(inputImagePath, finalOutputPath);
} }
actualImagePath = finalOutputPath; actualImagePath = finalOutputPath;
+4 -4
View File
@@ -3,11 +3,15 @@
* Executes external pdf2img binary to convert PDF pages to images. * Executes external pdf2img binary to convert PDF pages to images.
*/ */
import { exec } from 'child_process';
import { promisify } from 'util';
import * as path from 'path'; import * as path from 'path';
import { BinaryLocator } from './BinaryLocator'; import { BinaryLocator } from './BinaryLocator';
import { EnvironmentUtils } from './EnvironmentUtils'; import { EnvironmentUtils } from './EnvironmentUtils';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
const execAsync = promisify(exec);
export interface PdfCliOptions { export interface PdfCliOptions {
/** Scale factor for the rendered image */ /** Scale factor for the rendered image */
scale: number; scale: number;
@@ -111,10 +115,6 @@ export class PdfCliExecutor {
plugin?: obsidianTypstPDFExport plugin?: obsidianTypstPDFExport
): Promise<PdfCliResult> { ): Promise<PdfCliResult> {
try { try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
// Get augmented environment for CLI execution // Get augmented environment for CLI execution
const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings); const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings);
@@ -3,6 +3,8 @@
* Extracted from MarkdownPreprocessor for better code organization * Extracted from MarkdownPreprocessor for better code organization
*/ */
import * as yaml from 'js-yaml';
import matter from 'gray-matter';
import { PreprocessingResult } from '../MarkdownPreprocessor'; import { PreprocessingResult } from '../MarkdownPreprocessor';
export interface FrontmatterProcessorConfig { export interface FrontmatterProcessorConfig {
@@ -32,7 +34,6 @@ export class FrontmatterProcessor {
if (!this.FRONTMATTER_PATTERN.test(content)) { if (!this.FRONTMATTER_PATTERN.test(content)) {
// No frontmatter found - add title frontmatter if we have a noteTitle // No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle }; result.metadata.frontmatter = { title: this.noteTitle };
@@ -43,28 +44,30 @@ export class FrontmatterProcessor {
} }
// Use gray-matter for robust frontmatter parsing // Use gray-matter for robust frontmatter parsing
const matter = require('gray-matter');
// Add debugging to see what's being parsed // Add debugging to see what's being parsed
console.log('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected'); console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected', `(content length: ${content.length})`);
console.log('First 200 chars:', content.substring(0, 200));
const parsed = matter(content); const parsed = matter(content);
if (parsed.data && Object.keys(parsed.data).length > 0) { if (parsed.data && Object.keys(parsed.data).length > 0) {
// Replace frontmatter title with filename if noteTitle is provided // Sanitize frontmatter first to prevent citation fields from leaking to downstream consumers
const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
// Store sanitized frontmatter in metadata (with title override if needed)
if (this.noteTitle) { if (this.noteTitle) {
const frontmatterCopy = { ...parsed.data }; result.metadata.frontmatter = {
frontmatterCopy.title = this.noteTitle; ...sanitizedFrontmatter,
result.metadata.frontmatter = frontmatterCopy; title: this.noteTitle
};
} else { } else {
result.metadata.frontmatter = parsed.data; result.metadata.frontmatter = sanitizedFrontmatter;
} }
// Extract tags from frontmatter if they exist // Extract tags from frontmatter if they exist
if (parsed.data.tags) { if (parsed.data.tags) {
let frontmatterTags: string[] = []; let frontmatterTags: string[] = [];
if (Array.isArray(parsed.data.tags)) { if (Array.isArray(parsed.data.tags)) {
// Handle array of tags // Handle array of tags
frontmatterTags = parsed.data.tags frontmatterTags = parsed.data.tags
@@ -77,7 +80,7 @@ export class FrontmatterProcessor {
.map((tag: string) => tag.trim()) .map((tag: string) => tag.trim())
.filter((tag: string) => tag !== ''); .filter((tag: string) => tag !== '');
} }
// Merge with existing tags (avoid duplicates) // Merge with existing tags (avoid duplicates)
for (const tag of frontmatterTags) { for (const tag of frontmatterTags) {
if (!result.metadata.tags.includes(tag)) { if (!result.metadata.tags.includes(tag)) {
@@ -85,22 +88,19 @@ export class FrontmatterProcessor {
} }
} }
} }
// Extract title - use noteTitle if available, otherwise frontmatter title // Extract title - use noteTitle if available, otherwise frontmatter title
if (this.noteTitle) { if (this.noteTitle) {
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
} else if (parsed.data.title && typeof parsed.data.title === 'string') { } else if (parsed.data.title && typeof parsed.data.title === 'string') {
result.metadata.title = parsed.data.title.trim(); result.metadata.title = parsed.data.title.trim();
} }
// Handle frontmatter preservation and display options // Use the sanitized frontmatter from metadata for writing
const finalFrontmatter = this.noteTitle ? const finalFrontmatter = result.metadata.frontmatter;
{ ...parsed.data, title: this.noteTitle } :
parsed.data;
if (this.preserveFrontmatter) { if (this.preserveFrontmatter) {
// Keep the frontmatter in the content, but reconstruct it with the modified title // Keep the frontmatter in the content, but reconstruct it with the modified title
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(finalFrontmatter); const newFrontmatter = yaml.dump(finalFrontmatter);
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`; let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
@@ -115,7 +115,6 @@ export class FrontmatterProcessor {
// Return content without frontmatter, but add title as frontmatter for Pandoc // Return content without frontmatter, but add title as frontmatter for Pandoc
let processedContent: string; let processedContent: string;
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`; processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
} else { } else {
@@ -141,7 +140,6 @@ export class FrontmatterProcessor {
} else { } else {
// No frontmatter found - add title frontmatter if we have a noteTitle // No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle }; result.metadata.frontmatter = { title: this.noteTitle };
@@ -152,8 +150,7 @@ export class FrontmatterProcessor {
} }
} catch (error: unknown) { } catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
console.log('FrontmatterProcessor: gray-matter failed with error:', errorMessage); console.error('FrontmatterProcessor: gray-matter failed with error:', errorMessage, `(content length: ${content.length})`);
console.log('Content being parsed (first 500 chars):', content.substring(0, 500));
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`); result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
// Fallback to simple regex-based parsing // Fallback to simple regex-based parsing
@@ -185,7 +182,6 @@ export class FrontmatterProcessor {
if (this.preserveFrontmatter) { if (this.preserveFrontmatter) {
// Reconstruct frontmatter with modified title // Reconstruct frontmatter with modified title
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(frontmatter); const newFrontmatter = yaml.dump(frontmatter);
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
@@ -205,7 +201,6 @@ export class FrontmatterProcessor {
} else { } else {
// Add title as frontmatter for Pandoc even when not preserving original // Add title as frontmatter for Pandoc even when not preserving original
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
@@ -230,7 +225,6 @@ export class FrontmatterProcessor {
} else { } else {
// No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter // No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter
if (this.noteTitle) { if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle }); const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle; result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle }; result.metadata.frontmatter = { title: this.noteTitle };
@@ -242,6 +236,20 @@ export class FrontmatterProcessor {
} }
} }
/**
* Strip citation-related fields from frontmatter to prevent Pandoc bibliography processing
*/
private stripCitationFields(frontmatter: Record<string, unknown>): Record<string, unknown> {
const citationFields = ['bibliography', 'references', 'csl', 'citation-style', 'nocite', 'link-citations', 'reference-section-title'];
const sanitized = { ...frontmatter };
for (const field of citationFields) {
delete sanitized[field];
}
return sanitized;
}
/** /**
* Format frontmatter as a readable display block * Format frontmatter as a readable display block
*/ */
@@ -265,13 +273,19 @@ export class FrontmatterProcessor {
if (Array.isArray(value)) { if (Array.isArray(value)) {
// For arrays, put each item on its own line if there are many items // For arrays, put each item on its own line if there are many items
if (value.length > 3) { if (value.length > 3) {
formattedValue = '\n\n' + value.map(item => `- ${item}`).join('\n') + '\n'; formattedValue = '\n\n' + value.map(item => {
const itemStr = typeof item === 'object' ? JSON.stringify(item) : String(item);
return `- ${itemStr}`;
}).join('\n') + '\n';
} else { } else {
formattedValue = value.join(', '); formattedValue = value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : String(item)
).join(', ');
} }
} else if (typeof value === 'object') { } else if (typeof value === 'object' && value !== null) {
formattedValue = JSON.stringify(value); formattedValue = JSON.stringify(value);
} else { } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
// Handle primitive values
const valueStr = String(value); const valueStr = String(value);
// If the value is very long (like email lists), break it up // If the value is very long (like email lists), break it up
if (valueStr.length > 80 && valueStr.includes(',')) { if (valueStr.length > 80 && valueStr.includes(',')) {
@@ -308,8 +322,12 @@ export class FrontmatterProcessor {
} else { } else {
formattedValue = valueStr; formattedValue = valueStr;
} }
} else {
// Handle null, undefined, or any other unexpected types
console.debug('FrontmatterProcessor: Unexpected type in frontmatter display formatting', `key: ${key}, type: ${typeof value}`);
formattedValue = '';
} }
// Add line break after the property label, then the value // Add line break after the property label, then the value
if (formattedValue.startsWith('\n')) { if (formattedValue.startsWith('\n')) {
// Value already starts with newline (like lists), so just add the label // Value already starts with newline (like lists), so just add the label
+267 -18
View File
@@ -1,19 +1,79 @@
/** /**
* 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 { DEPENDENCY_CONSTANTS } from './constants';
import { ExportErrorHandler } from './ExportErrorHandler'; import { ExportErrorHandler } from './ExportErrorHandler';
import { ExecutableChecker, DependencyInfo } from './ExecutableChecker'; 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
* @property outdatedDependencies - Array of names of dependencies with versions below minimum
*/
export interface DependencyCheckResult { export interface DependencyCheckResult {
pandoc: DependencyInfo; pandoc: DependencyInfo;
typst: DependencyInfo; typst: DependencyInfo;
imagemagick: DependencyInfo; imagemagick: DependencyInfo;
allAvailable: boolean; allAvailable: boolean;
missingDependencies: string[]; missingDependencies: string[];
outdatedDependencies: 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 { export class DependencyChecker {
@@ -23,7 +83,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( public static async checkAllDependencies(
pandocPath?: string, pandocPath?: string,
@@ -39,26 +143,76 @@ export class DependencyChecker {
]); ]);
const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([ const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([
ExecutableChecker.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/), ExecutableChecker.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/i, DEPENDENCY_CONSTANTS.MINIMUM_VERSIONS.pandoc),
ExecutableChecker.checkDependency('Typst', typstExec, '--version', /typst\s+([\d.]+)/), ExecutableChecker.checkDependency('Typst', typstExec, '--version', /typst\s+([\d.]+)/i, DEPENDENCY_CONSTANTS.MINIMUM_VERSIONS.typst),
ExecutableChecker.checkDependency('ImageMagick', imagemagickExec, '--version', /ImageMagick\s+([\d.-]+)/) ExecutableChecker.checkDependency('ImageMagick', imagemagickExec, '--version', /ImageMagick\s+([\d.-]+)/i, DEPENDENCY_CONSTANTS.MINIMUM_VERSIONS.imagemagick)
]); ]);
const missingDependencies = [pandocInfo, typstInfo, imagemagickInfo] const missingDependencies = [pandocInfo, typstInfo, imagemagickInfo]
.filter(dep => !dep.isAvailable) .filter(dep => !dep.isAvailable)
.map(dep => dep.name); .map(dep => dep.name);
const outdatedDependencies = [pandocInfo, typstInfo, imagemagickInfo]
.filter(dep => dep.isAvailable && !dep.meetsMinimumVersion)
.map(dep => dep.name);
return { return {
pandoc: pandocInfo, pandoc: pandocInfo,
typst: typstInfo, typst: typstInfo,
imagemagick: imagemagickInfo, imagemagick: imagemagickInfo,
allAvailable: missingDependencies.length === 0, allAvailable: missingDependencies.length === 0,
missingDependencies missingDependencies,
outdatedDependencies
}; };
} }
/** /**
* 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( public static checkDependenciesSync(
pandocPath?: string, pandocPath?: string,
@@ -87,7 +241,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( public static async showDependencyStatus(
pandocPath?: string, pandocPath?: string,
@@ -102,29 +296,84 @@ export class DependencyChecker {
additionalPaths additionalPaths
); );
const formatVersion = (dep: DependencyInfo) => dep.isAvailable ? (dep.version || 'Available') : 'Not found'; const formatVersion = (dep: DependencyInfo) => {
if (!dep.isAvailable) return 'Not found';
if (!dep.meetsMinimumVersion) return `${dep.version} (minimum: ${dep.minimumVersion})`;
return dep.version || 'Available';
};
const statusLines: string[] = [];
// Build status messages
if (!dependencyResult.allAvailable) {
statusLines.push(`Missing dependencies: ${dependencyResult.missingDependencies.join(', ')}. Please install them and check the paths in settings.`);
} else if (dependencyResult.outdatedDependencies.length > 0) {
statusLines.push(`⚠️ Outdated versions detected: ${dependencyResult.outdatedDependencies.join(', ')}.`);
statusLines.push(`Please update to avoid compatibility issues.`);
} else {
statusLines.push('✓ All dependencies found and up to date!');
}
const message = `Dependency Status: const message = `Dependency Status:
Pandoc: ${formatVersion(dependencyResult.pandoc)} Pandoc: ${formatVersion(dependencyResult.pandoc)}
Typst: ${formatVersion(dependencyResult.typst)} Typst: ${formatVersion(dependencyResult.typst)}
ImageMagick: ${formatVersion(dependencyResult.imagemagick)} ImageMagick: ${formatVersion(dependencyResult.imagemagick)}
${dependencyResult.allAvailable ${statusLines.join('\n')}`;
? 'All dependencies found!'
: `Missing dependencies: ${dependencyResult.missingDependencies.join(', ')}. Please install them and check the paths in settings.`}`; ExportErrorHandler.showProgressNotice(message, 15000); // Show for 15 seconds (longer due to version info)
ExportErrorHandler.showProgressNotice(message, 12000); // Show for 12 seconds (longer due to more content)
} }
/** /**
* 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
*
* @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
* DependencyChecker.checkDependenciesOnStartup(
* 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( public static checkDependenciesOnStartup(
pandocPath?: string, pandocPath?: string,
typstPath?: string, typstPath?: string,
imagemagickPath?: string, imagemagickPath?: string,
additionalPaths: string[] = [] additionalPaths: string[] = []
): Promise<void> { ): void {
// Check dependencies silently on startup // Check dependencies silently on startup
try { try {
const missingDeps = this.checkDependenciesSync( const missingDeps = this.checkDependenciesSync(
+230 -33
View File
@@ -1,41 +1,124 @@
/** /**
* Executable checking utilities for Obsidian Typst PDF Export plugin * Executable checking utilities for Obsidian Typst PDF Export plugin.
* Handles path resolution, version detection, and availability checking for external executables *
* 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 { spawn, spawnSync } from 'child_process';
import { DEPENDENCY_CONSTANTS } from './constants'; import { DEPENDENCY_CONSTANTS } from './constants';
import { isVersionAtLeast } from '../utils/versionUtils';
import * as path from 'path';
/**
* 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
* @property meetsMinimumVersion - Whether the version meets the minimum requirement (true if no version check performed)
* @property minimumVersion - The minimum required version string (null if not checked)
*/
export interface DependencyInfo { export interface DependencyInfo {
name: string; name: string;
version: string | null; version: string | null;
isAvailable: boolean; isAvailable: boolean;
executablePath: string; executablePath: string;
meetsMinimumVersion: boolean;
minimumVersion: string | null;
} }
/** /**
* 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 { 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.
*
* Uses platform-specific path delimiters (';' on Windows, ':' on Unix) and
* filters out empty segments to prevent PATH corruption.
*
* @param additionalPaths - Optional array of additional paths to include
* @returns The augmented PATH string with all paths separated by platform-specific delimiter
* @private
*/ */
private static getAugmentedPath(additionalPaths: string[] = []): string { private static getAugmentedPath(additionalPaths: string[] = []): string {
const homeDir = process.env.HOME || process.env.USERPROFILE || ''; const homeDir = process.env.HOME || process.env.USERPROFILE || '';
// Build default system paths - always included regardless of user settings // Build default system paths - always included regardless of user settings
const homeRelativePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.map(p => homeDir + p); const homeRelativePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.map(p => homeDir + p);
const absolutePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE; const absolutePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE;
const defaultSystemPaths = [...homeRelativePaths, ...absolutePaths]; const defaultSystemPaths = [...homeRelativePaths, ...absolutePaths];
// Combine default system paths with user-provided additional paths // Combine default system paths with user-provided additional paths
const allAdditionalPaths = [...defaultSystemPaths, ...additionalPaths]; const allAdditionalPaths = [...defaultSystemPaths, ...additionalPaths];
return `${process.env.PATH}:${allAdditionalPaths.join(':')}`; // Use platform-specific delimiter (';' on Windows, ':' on Unix)
const delimiter = process.platform === 'win32' ? ';' : ':';
// Filter out empty segments and join with platform-specific delimiter
const segments = [
process.env.PATH ?? '',
...allAdditionalPaths.filter(p => p && p.trim() !== '')
];
return segments.filter(Boolean).join(delimiter);
} }
/** /**
* 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 { private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
return { return {
@@ -45,16 +128,32 @@ 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> { private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
const { spawn } = require('child_process');
try { try {
const stdout = await new Promise<string>((resolve, reject) => { const stdout = await new Promise<string>((resolve, reject) => {
const env = this.getAugmentedEnv(additionalPaths); const env = this.getAugmentedEnv(additionalPaths);
const whichProcess = spawn('which', [executableName], { // Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
const whichProcess = spawn(whichCommand, [executableName], {
stdio: ['pipe', 'pipe', 'pipe'], stdio: ['pipe', 'pipe', 'pipe'],
env: env env: env
}); });
@@ -91,11 +190,39 @@ 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> { public static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
// If user provided a full path (contains /), use it as-is // If user provided an absolute path, use it as-is
if (userPath && userPath.trim() !== '' && userPath.includes('/')) { if (userPath && userPath.trim() !== '' && path.isAbsolute(userPath)) {
return userPath; return userPath;
} }
@@ -113,21 +240,34 @@ 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 { public static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
// If user provided a full path (contains /), use it as-is // If user provided an absolute path, use it as-is
if (userPath && userPath.trim() !== '' && userPath.includes('/')) { if (userPath && userPath.trim() !== '' && path.isAbsolute(userPath)) {
return userPath; return userPath;
} }
// If user provided just an executable name or empty path, resolve it // If user provided just an executable name or empty path, resolve it
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName; const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
// Try to find the executable using which command synchronously // Try to find the executable using which command synchronously
const { spawnSync } = require('child_process'); // Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
try { try {
const result = spawnSync('which', [searchName], { const result = spawnSync(whichCommand, [searchName], {
encoding: 'utf8', encoding: 'utf8',
env: this.getAugmentedEnv(additionalPaths) env: this.getAugmentedEnv(additionalPaths)
}); });
@@ -147,16 +287,50 @@ 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. Optionally validates against minimum required version
* 4. 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
* @param minimumVersion - Optional minimum required version (e.g., "0.13.0")
* @returns DependencyInfo object with availability and version information
*
* @example
* ```typescript
* const info = await ExecutableChecker.checkDependency(
* 'Pandoc',
* '/usr/bin/pandoc',
* '--version',
* /pandoc (\d+\.\d+(?:\.\d+)?)/,
* '3.7.0'
* );
*
* if (info.isAvailable && info.meetsMinimumVersion) {
* console.log(`Found ${info.name} version ${info.version}`);
* } else if (info.isAvailable) {
* console.warn(`${info.name} ${info.version} is below minimum ${info.minimumVersion}`);
* } else {
* console.error(`${info.name} not available at ${info.executablePath}`);
* }
* ```
*/ */
public static async checkDependency( public static async checkDependency(
name: string, name: string,
executablePath: string, executablePath: string,
versionCommand: string, versionCommand: string,
versionRegex: RegExp versionRegex: RegExp,
minimumVersion: string | null = null
): Promise<DependencyInfo> { ): Promise<DependencyInfo> {
const { spawn } = require('child_process');
try { try {
// Use spawn instead of exec for security - arguments passed separately // Use spawn instead of exec for security - arguments passed separately
const stdout = await new Promise<string>((resolve, reject) => { const stdout = await new Promise<string>((resolve, reject) => {
@@ -191,29 +365,52 @@ export class ExecutableChecker {
const match = stdout.match(versionRegex); const match = stdout.match(versionRegex);
const version = match ? match[1] : null; const version = match ? match[1] : null;
// Check version against minimum if both are available
const meetsMinimumVersion = minimumVersion && version
? isVersionAtLeast(version, minimumVersion)
: true; // No minimum version check or version unavailable
return { return {
name, name,
version, version,
isAvailable: true, isAvailable: true,
executablePath executablePath,
meetsMinimumVersion,
minimumVersion
}; };
} catch { } catch {
return { return {
name, name,
version: null, version: null,
isAvailable: false, isAvailable: false,
executablePath executablePath,
meetsMinimumVersion: true, // Not checking if unavailable
minimumVersion
}; };
} }
} }
/** /**
* 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 { public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
const { spawnSync } = require('child_process');
try { try {
const result = spawnSync(executablePath, versionCommand.split(' '), { const result = spawnSync(executablePath, versionCommand.split(' '), {
encoding: 'utf8', encoding: 'utf8',
+324 -21
View File
@@ -1,27 +1,118 @@
/** /**
* 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, debug)
* - Specialized handlers for different error types (dependency, processing, validation)
*/ */
import { Notice } from 'obsidian'; import { Notice } from 'obsidian';
import { EXPORT_CONSTANTS } from './constants'; 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 { export interface BatchExportResult {
successful: number; successful: number;
failed: number; failed: number;
errors: string[]; 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 { export interface ExportError {
fileName?: string; fileName?: string;
operation: string; operation: string;
error: Error | string; error: Error | string;
shouldShowNotice?: boolean; shouldShowNotice?: boolean;
logLevel?: 'error' | 'warn' | 'info'; logLevel?: 'error' | 'warn' | 'debug';
} }
/**
* 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 { 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( public static handleBatchResult(
result: BatchExportResult, 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 { public static handleExportError(exportError: ExportError): string {
const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError; const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError;
@@ -60,8 +180,8 @@ export class ExportErrorHandler {
case 'warn': case 'warn':
console.warn(`${operation}:`, error); console.warn(`${operation}:`, error);
break; break;
case 'info': case 'debug':
console.info(`${operation}:`, error); console.debug(`${operation}:`, error);
break; break;
} }
@@ -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( public static handleProcessingError(
operation: string, 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(): { public static createBatchTracker(): {
tracker: BatchExportResult; 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 { public static handleSingleExportError(error: Error | string): void {
const errorMessage = error instanceof Error ? error.message : String(error); 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( public static handleDependencyError(
dependency: string, dependency: string,
@@ -146,7 +367,7 @@ export class ExportErrorHandler {
): void { ): void {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`Error checking ${dependency}:`, error); console.error(`Error checking ${dependency}:`, error);
if (showNotice) { if (showNotice) {
new Notice( new Notice(
`${dependency} error: ${errorMessage}`, `${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 { public static showProgressNotice(message: string, timeout?: number): Notice {
return new Notice(message, timeout || 0); 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 { public static showCancellationNotice(): void {
new Notice('Export cancelled'); 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 { public static showValidationError(field: string, validationMessage: string): void {
new Notice(`Invalid ${field}: ${validationMessage}`); 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 { public static showTemplateError(error: Error | string): void {
const errorMessage = error instanceof Error ? error.message : String(error); 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 { public static showFontError(error: Error | string, showFallback: boolean = true): void {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
new Notice(`Font caching failed: ${errorMessage}. Using fallback fonts.`, 5000); new Notice(`Font caching failed: ${errorMessage}. Using fallback fonts.`, 5000);
if (showFallback) { if (showFallback) {
new Notice('Font list may be incomplete. Check debug mode for details.', 3000); 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 { public static showExportSuccess(outputPath: string): void {
new Notice(`PDF exported successfully to ${outputPath}`); 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 { public static showFileNotFoundWarning(context: string): void {
new Notice(`Please open a ${context} file to export`); 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 { public static showNoFilesWarning(context: string = 'files'): void {
new Notice(`No ${context} to export`); 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 { public static showSettingsReset(): void {
new Notice('Settings reset to defaults'); new Notice('Settings reset to defaults');
+178 -12
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 { TFile } from 'obsidian';
import { obsidianTypstPDFExportSettings } from './settings'; import { obsidianTypstPDFExportSettings, ExportFormat } from './settings';
import { ExportConfigModalSettings } from '../ui/modal/modalTypes'; 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 { export interface ModalSettingsInput {
/** Primary file for the export */ /** Primary file for the export */
file: TFile; file: TFile;
@@ -17,9 +36,75 @@ export interface ModalSettingsInput {
settings: obsidianTypstPDFExportSettings; 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 { 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> { public static prepareModalSettings(input: ModalSettingsInput): Partial<ExportConfigModalSettings> {
const { file, additionalFiles, availableTemplates, settings } = input; 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> { private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record<string, string | number | boolean | undefined> {
const baseVariables = { const baseVariables = {
@@ -68,8 +179,8 @@ export class ModalSettingsHelper {
}; };
// Auto-adjust width for single-page landscape mode // Auto-adjust width for single-page landscape mode
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape' const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
&& settings.exportDefaults.format === 'single-page' && settings.exportDefaults.format === ExportFormat.SinglePage
? { width: 'auto' } ? { width: 'auto' }
: {}; : {};
@@ -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( public static prepareForSingleFile(
file: TFile, file: TFile,
availableTemplates: string[], availableTemplates: string[],
settings: obsidianTypstPDFExportSettings settings: obsidianTypstPDFExportSettings
): Partial<ExportConfigModalSettings> { ): Partial<ExportConfigModalSettings> {
return this.prepareModalSettings({ 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( public static prepareForMultiFile(
files: TFile[], files: TFile[],
availableTemplates: string[], availableTemplates: string[],
settings: obsidianTypstPDFExportSettings settings: obsidianTypstPDFExportSettings
): Partial<ExportConfigModalSettings> { ): Partial<ExportConfigModalSettings> {
const [primaryFile, ...additionalFiles] = files; const [primaryFile, ...additionalFiles] = files;
+178 -13
View File
@@ -1,14 +1,55 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations // ABOUTME: Centralized path utilities for safe Obsidian API operations
// ABOUTME: Handles vault paths, plugin directories, and file operations // ABOUTME: Handles vault paths, plugin directories, and file operations
import { promises as fs } from 'fs';
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian'; import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
import type { App, PluginManifest } 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 { export class PathUtils {
/**
* Creates a new PathUtils instance.
*
* @param app - The Obsidian App instance used for vault operations
*/
constructor(private app: App) {} 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 { getVaultPath(): string {
const adapter = this.app.vault.adapter; const adapter = this.app.vault.adapter;
@@ -20,24 +61,74 @@ 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 { getPluginDir(pluginManifest: PluginManifest): string {
return normalizePath(pluginManifest.dir || ''); return normalizePath(pluginManifest.dir || '');
} }
/** /**
* Join path segments with normalizePath * 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 { joinPath(...segments: string[]): string {
// Filter out empty segments
const filtered = segments.filter(s => s); const filtered = segments.filter(s => s);
const joined = filtered.join('/'); if (filtered.length === 0) {
return normalizePath(joined); return '';
}
const result = path.join(...filtered);
// Don't use normalizePath on absolute paths as it strips the leading slash
// Only normalize vault-relative paths
if (path.isAbsolute(result)) {
return result;
}
return normalizePath(result);
} }
/** /**
* 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> { async ensureDir(path: string): Promise<void> {
const normalizedPath = normalizePath(path); const normalizedPath = normalizePath(path);
@@ -47,13 +138,31 @@ export class PathUtils {
await this.app.vault.adapter.mkdir(normalizedPath); await this.app.vault.adapter.mkdir(normalizedPath);
} }
} catch (error) { } catch (error) {
new Notice(`Failed to create directory: ${normalizedPath}`); const errorMessage = error instanceof Error ? error.message : String(error);
throw error; const userMessage = `Failed to create output directory "${normalizedPath}". ${errorMessage.includes('parent') || errorMessage.includes('ENOENT') ? 'The parent directory may not exist or you may not have write permissions.' : 'You may not have write permissions or the path is invalid.'}`;
new Notice(userMessage);
throw new Error(userMessage);
} }
} }
/** /**
* 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> { async cleanupDir(path: string): Promise<boolean> {
const normalizedPath = normalizePath(path); const normalizedPath = normalizePath(path);
@@ -74,8 +183,33 @@ export class PathUtils {
} }
/** /**
* Check if file or directory exists * Checks if a file or directory exists at the given path.
* Handles both vault-relative paths and absolute filesystem paths *
* 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> { async fileExists(path: string): Promise<boolean> {
try { try {
@@ -112,7 +246,6 @@ export class PathUtils {
if (isAbsolutePath) { if (isAbsolutePath) {
try { try {
const fs = require('fs').promises;
await fs.access(path); await fs.access(path);
return true; return true;
} catch { } catch {
@@ -122,4 +255,36 @@ export class PathUtils {
return false; return false;
} }
/**
* Converts an absolute path to a vault-relative path.
*
* This method is used to convert absolute filesystem paths to vault-relative
* paths suitable for use with Obsidian's vault adapter operations. If the path
* does not start with the vault base path, it is returned unchanged.
*
* @param absolutePath - The absolute path to convert
* @returns The vault-relative path (without leading slash) or the original path if not within vault
*
* @example
* ```typescript
* const pathUtils = new PathUtils(app);
* const vaultPath = '/Users/name/vault';
* const absolutePath = '/Users/name/vault/folder/file.md';
* const relative = pathUtils.toVaultRelative(absolutePath);
* // Returns: 'folder/file.md'
* ```
*/
toVaultRelative(absolutePath: string): string {
const vaultBasePath = this.getVaultPath();
if (!absolutePath.startsWith(vaultBasePath)) {
return absolutePath;
}
let relativePath = absolutePath.substring(vaultBasePath.length);
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.substring(1);
}
return relativePath;
}
} }
+303 -33
View File
@@ -1,26 +1,132 @@
/** /**
* 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'; 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 { export class SecurityUtils {
/** /**
* Validates that an output folder path is safe and doesn't contain traversal attempts * Validates that an output folder path is safe for file operations.
* @param outputFolder The folder path to validate *
* @returns true if the path is safe, false otherwise * 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 in any path segment (CON, PRN, AUX, etc.)
* including when followed by extensions (e.g., CON.txt, AUX.log)
*
* 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('reports/CON/file'); // false - reserved in segment
* SecurityUtils.validateOutputPath('AUX.txt'); // false - reserved with extension
* SecurityUtils.validateOutputPath('test<>file'); // false - invalid chars
* SecurityUtils.validateOutputPath('path//with//double'); // false - suspicious
* ```
*/ */
static validateOutputPath(outputFolder: string): boolean { static validateOutputPath(outputFolder: string): boolean {
if (!outputFolder || typeof outputFolder !== 'string') { if (!outputFolder || typeof outputFolder !== 'string') {
return false; return false;
} }
// Normalize and resolve the path to detect traversal attempts // Normalize path (reject absolute paths so exports stay inside the vault)
const normalizedPath = path.normalize(outputFolder.trim()); const trimmed = outputFolder.trim();
if (path.isAbsolute(trimmed)) {
return false;
}
const normalizedPath = path.normalize(trimmed);
// Check for path traversal attempts // Check for path traversal attempts
if (normalizedPath.includes('..') || if (normalizedPath.includes('..') ||
normalizedPath.startsWith('/') || normalizedPath.startsWith('/') ||
normalizedPath.startsWith('\\') || normalizedPath.startsWith('\\') ||
normalizedPath.includes('\x00')) { normalizedPath.includes('\x00')) {
return false; return false;
@@ -30,17 +136,80 @@ export class SecurityUtils {
const suspiciousPatterns = [ const suspiciousPatterns = [
/\.\./, // Directory traversal /\.\./, // Directory traversal
/\/\//, // Double slashes /\/\//, // Double slashes
/[<>:"|?*]/, // Invalid filename characters /[<>:"|?*]/ // Invalid filename characters
/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i // Windows reserved names
]; ];
return !suspiciousPatterns.some(pattern => pattern.test(normalizedPath)); if (suspiciousPatterns.some(pattern => pattern.test(normalizedPath))) {
return false;
}
// Check for Windows reserved names in any path segment
// Reserved names are invalid even with extensions (e.g., CON.txt, AUX.log)
const reservedNamePattern = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
const hasReservedName = normalizedPath
.split(/[\\/]+/)
.filter(segment => segment && segment !== '.')
.some(segment => {
// Strip extension and check base name
const baseName = segment.split('.')[0] ?? '';
return reservedNamePattern.test(baseName);
});
return !hasReservedName;
} }
/** /**
* Validates that an executable path is safe for use in shell commands * 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 * 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 { static validateExecutablePath(executablePath: string): boolean {
// Allow empty paths (will use system PATH) // Allow empty paths (will use system PATH)
@@ -52,8 +221,8 @@ export class SecurityUtils {
// Check for command injection attempts // Check for command injection attempts
const dangerousPatterns = [ const dangerousPatterns = [
/[;&|`$(){}[\]]/, // Shell metacharacters /[;&|`$<>{}[\]]/, // Shell metacharacters that can't appear in safe paths
// eslint-disable-next-line no-control-regex // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
/\x00/, // Null bytes /\x00/, // Null bytes
/\n|\r/, // Newlines /\n|\r/, // Newlines
/\s*[;&|]\s*/, // Command separators with whitespace /\s*[;&|]\s*/, // Command separators with whitespace
@@ -66,17 +235,63 @@ export class SecurityUtils {
} }
/** /**
* Gets a human-readable error message for invalid paths * Generates a human-readable error message explaining why a path is invalid.
* @param outputFolder The invalid path *
* @returns Description of why the 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 in paths (found: CON)"
* 'reports/AUX/file', // "Reserved system names are not allowed in paths (found: AUX)"
* 'COM1.txt', // "Reserved system names are not allowed in paths (found: COM1.txt)"
* '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 { static getPathValidationError(outputFolder: string): string {
if (!outputFolder || typeof outputFolder !== 'string') { if (!outputFolder || typeof outputFolder !== 'string') {
return 'Output folder is required'; return 'Output folder is required';
} }
const normalizedPath = path.normalize(outputFolder.trim()); // Normalize path (reject absolute paths so exports stay inside the vault)
const trimmed = outputFolder.trim();
if (path.isAbsolute(trimmed)) {
return 'Absolute paths are not allowed - use relative paths from vault root';
}
const normalizedPath = path.normalize(trimmed);
if (normalizedPath.includes('..')) { if (normalizedPath.includes('..')) {
return 'Path traversal attempts (..) are not allowed'; return 'Path traversal attempts (..) are not allowed';
} }
@@ -92,17 +307,71 @@ export class SecurityUtils {
if (/[<>:"|?*]/.test(normalizedPath)) { if (/[<>:"|?*]/.test(normalizedPath)) {
return 'Invalid characters found in path'; return 'Invalid characters found in path';
} }
if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(normalizedPath)) {
return 'Reserved system names are not allowed as folder names'; // Check for Windows reserved names in any path segment
const reservedNamePattern = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
const reservedSegment = normalizedPath
.split(/[\\/]+/)
.filter(segment => segment && segment !== '.')
.find(segment => {
const baseName = segment.split('.')[0] ?? '';
return reservedNamePattern.test(baseName);
});
if (reservedSegment) {
return `Reserved system names are not allowed in paths (found: ${reservedSegment})`;
} }
return 'Invalid path format'; return 'Invalid path format';
} }
/** /**
* Gets a human-readable error message for invalid executable paths * Generates a human-readable error message for invalid executable paths.
* @param executablePath The invalid executable path *
* @returns Description of why the path is invalid * 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 { static getExecutablePathValidationError(executablePath: string): string {
if (!executablePath || typeof executablePath !== 'string') { if (!executablePath || typeof executablePath !== 'string') {
@@ -111,10 +380,11 @@ export class SecurityUtils {
const normalizedPath = path.normalize(executablePath.trim()); const normalizedPath = path.normalize(executablePath.trim());
if (/[;&|`$(){}[\]]/.test(normalizedPath)) { if (/[;&|`$<>]/.test(normalizedPath)) {
return 'Shell metacharacters are not allowed in executable paths'; return 'Shell metacharacters are not allowed in executable paths';
} }
if (/\x00/.test(normalizedPath)) { // eslint-disable-line no-control-regex // eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
if (/\x00/.test(normalizedPath)) {
return 'Null bytes are not allowed in paths'; return 'Null bytes are not allowed in paths';
} }
if (/\n|\r/.test(normalizedPath)) { if (/\n|\r/.test(normalizedPath)) {
+381 -23
View File
@@ -1,10 +1,39 @@
// 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 { PLUGIN_DIRS } from './constants';
import { normalizePath } from 'obsidian'; import { normalizePath } from 'obsidian';
import type { App } from 'obsidian'; import type { App } from 'obsidian';
import * as path from 'path';
import { promises as fs } from 'fs';
/**
* 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 { export interface TempDirectoryOptions {
/** Base path for the vault */ /** Base path for the vault */
vaultPath: string; vaultPath: string;
@@ -16,12 +45,101 @@ export interface TempDirectoryOptions {
app: App; 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 { export class TempDirectoryManager {
private readonly vaultPath: string; private readonly vaultPath: string;
private readonly configDir: string; private readonly configDir: string;
private readonly pluginName: string; private readonly pluginName: string;
private readonly app: App; 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) { constructor(options: TempDirectoryOptions) {
this.vaultPath = options.vaultPath; this.vaultPath = options.vaultPath;
this.configDir = options.configDir; this.configDir = options.configDir;
@@ -30,47 +148,180 @@ export class TempDirectoryManager {
} }
/** /**
* Get the plugin directory path * 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 { private getPluginDir(): string {
return normalizePath([this.vaultPath, this.configDir, 'plugins', this.pluginName].join('/')); // path.join automatically handles absolute paths correctly
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
// Don't normalize absolute paths as normalizePath strips the leading slash
return path.isAbsolute(result) ? result : normalizePath(result);
} }
/** /**
* Get the path for a specific temp directory * 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 { public getTempDir(type: 'images' | 'pandoc'): string {
const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC; const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC;
return normalizePath([this.getPluginDir(), dirName].join('/')); const pluginDir = this.getPluginDir();
// Use path.join to properly handle absolute paths
const result = path.join(pluginDir, dirName);
// Don't normalize absolute paths as normalizePath strips the leading slash
return path.isAbsolute(result) ? result : normalizePath(result);
} }
/** /**
* 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> { public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
const tempDir = this.getTempDir(type); const tempDir = this.getTempDir(type);
const exists = await this.app.vault.adapter.exists(tempDir); // Use fs.mkdir for temp directories since external tools (pdf2img, ImageMagick)
if (!exists) { // need to write to them directly with absolute paths
await this.app.vault.adapter.mkdir(tempDir); try {
await fs.access(tempDir);
} catch {
// Directory doesn't exist, create it with recursive option
await fs.mkdir(tempDir, { recursive: true });
} }
return tempDir; return tempDir;
} }
/** /**
* 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> { public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
const tempDir = this.getTempDir(type); const tempDir = this.getTempDir(type);
// Use fs for temp directory cleanup since these directories contain
// files created by external tools
try { try {
const exists = await this.app.vault.adapter.exists(tempDir); const exists = await fs.access(tempDir).then(() => true).catch(() => false);
if (exists) { if (exists) {
const list = await this.app.vault.adapter.list(tempDir); const files = await fs.readdir(tempDir);
// Remove only files, not subdirectories (matching current pattern) // Remove only files, not subdirectories (matching current pattern)
for (const file of list.files) { for (const file of files) {
await this.app.vault.adapter.remove(file); const filePath = path.join(tempDir, file);
const stat = await fs.stat(filePath);
if (stat.isFile()) {
await fs.unlink(filePath);
}
} }
} }
return true; return true;
@@ -81,7 +332,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 }> { public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> {
return { return {
@@ -91,23 +369,103 @@ 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 { public static create(vaultPath: string, configDir: string, pluginName: string | undefined, app: App): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, configDir, pluginName, app }); return new TempDirectoryManager({ vaultPath, configDir, pluginName, app });
} }
/** /**
* Check if a path is within the plugin's temp directories * 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 { public isPluginTempDir(dirPath: string): boolean {
const pluginDir = this.getPluginDir(); const pluginDir = this.getPluginDir();
const normalizedDirPath = normalizePath(dirPath); const normalizedDirPath = normalizePath(dirPath);
const normalizedPluginDir = normalizePath(pluginDir);
const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/'));
const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/'));
return normalizedDirPath.startsWith(tempImagesDir) || const tempImagesDir = normalizePath(path.join(pluginDir, PLUGIN_DIRS.TEMP_IMAGES));
normalizedDirPath.startsWith(tempPandocDir); const tempPandocDir = normalizePath(path.join(pluginDir, PLUGIN_DIRS.TEMP_PANDOC));
const isImagesDir =
normalizedDirPath === tempImagesDir ||
normalizedDirPath.startsWith(`${tempImagesDir}/`);
const isPandocDir =
normalizedDirPath === tempPandocDir ||
normalizedDirPath.startsWith(`${tempPandocDir}/`);
return isImagesDir || isPandocDir;
} }
} }
+198 -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 = [ export const FALLBACK_FONTS = [
'Times New Roman', 'Times New Roman',
@@ -20,7 +64,27 @@ export const FALLBACK_FONTS = [
] as const; ] 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 = { export const PLUGIN_DIRS = {
TEMP_IMAGES: 'temp-images', TEMP_IMAGES: 'temp-images',
@@ -29,7 +93,31 @@ export const PLUGIN_DIRS = {
} as const; } 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 = { export const EXPORT_CONSTANTS = {
DEFAULT_TIMEOUT: 120000, // 2 minutes DEFAULT_TIMEOUT: 120000, // 2 minutes
@@ -40,24 +128,113 @@ export const EXPORT_CONSTANTS = {
} as const; } 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 = { 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: { DEFAULT_EXECUTABLES: {
pandoc: 'pandoc', pandoc: 'pandoc',
typst: 'typst', typst: 'typst',
imagemagick: 'magick' imagemagick: 'magick'
}, },
/** /**
* Common paths to augment PATH with - these are always checked regardless of user settings * Minimum required versions for external dependencies.
*
* These versions represent the minimum supported versions that have been
* tested with this plugin. Users with older versions will receive warnings.
*
* @property pandoc - Pandoc 3.7.0 (current stable as of plugin development)
* @property typst - Typst 0.13.0 (version used during plugin development)
* @property imagemagick - ImageMagick 7.1.2 (current stable as of plugin development)
*/
MINIMUM_VERSIONS: {
pandoc: '3.7.0',
typst: '0.13.0',
imagemagick: '7.1.2'
},
/**
* 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: { 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: [ HOME_RELATIVE: [
'/.local/bin', '/.local/bin',
@@ -66,7 +243,18 @@ export const DEPENDENCY_CONSTANTS = {
'/.npm-global/bin' '/.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: [ ABSOLUTE: [
'/usr/local/bin', '/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 { export enum ExportFormat {
/** Standard multi-page PDF format */ /** Standard multi-page PDF format with automatic pagination */
Standard = 'standard', Standard = 'standard',
/** Single-page continuous PDF format */ /** Single-page continuous PDF format without page breaks */
SinglePage = 'single-page' 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 { 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; 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; 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; 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: { 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; 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[]; 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 }; 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: { exportDefaults: {
/** Default template to use for exports */ /** Default template to use for exports */
template: string; 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 = { export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
pandocPath: '', pandocPath: '',
typstPath: '', typstPath: '',
+17 -5
View File
@@ -3,7 +3,7 @@
* Handles registration of all plugin commands and their callbacks * Handles registration of all plugin commands and their callbacks
*/ */
import { Editor, MarkdownView } from 'obsidian'; import { Editor, MarkdownView, Notice } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
export class CommandRegistry { export class CommandRegistry {
@@ -18,7 +18,11 @@ export class CommandRegistry {
id: 'export-current-note', id: 'export-current-note',
name: 'Export current note(s)', name: 'Export current note(s)',
editorCallback: (editor: Editor, view: MarkdownView) => { editorCallback: (editor: Editor, view: MarkdownView) => {
this.plugin.exportCurrentNote(view); this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
const errorMessage = error?.message ?? String(error);
new Notice(`Failed to export current note: ${errorMessage}`);
});
} }
}); });
@@ -27,16 +31,24 @@ export class CommandRegistry {
id: 'export-with-config', id: 'export-with-config',
name: 'Export with configuration…', name: 'Export with configuration…',
editorCallback: (editor: Editor, view: MarkdownView) => { editorCallback: (editor: Editor, view: MarkdownView) => {
this.plugin.showExportModal(view); this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
const errorMessage = error?.message ?? String(error);
new Notice(`Failed to show export modal: ${errorMessage}`);
});
} }
}); });
// Check dependencies command // Check dependencies command
this.plugin.addCommand({ this.plugin.addCommand({
id: 'check-dependencies', id: 'check-dependencies',
name: 'Check Pandoc and Typst dependencies', name: 'Check pandoc and typst dependencies',
callback: () => { callback: () => {
this.plugin.showDependencyStatus(); this.plugin.showDependencyStatus().catch(error => {
console.error('Failed to show dependency status:', error);
const errorMessage = error?.message ?? String(error);
new Notice(`Failed to show dependency status: ${errorMessage}`);
});
} }
}); });
} }
+264 -123
View File
@@ -3,12 +3,18 @@
* Handles processing of PDF, image, and file embeds for PDF export * Handles processing of PDF, image, and file embeds for PDF export
*/ */
import { exec } from 'child_process';
import * as util from 'util';
import { TFile } from 'obsidian'; import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import type { PreprocessingResult } from '../converters/MarkdownPreprocessor'; import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
import { ExportErrorHandler } from '../core/ExportErrorHandler'; import { ExportErrorHandler } from '../core/ExportErrorHandler';
import { PathUtils } from '../core/PathUtils'; import { PathUtils } from '../core/PathUtils';
import * as path from 'path'; import * as path from 'path';
import * as https from 'https';
import * as http from 'http';
const execAsync = util.promisify(exec);
export class EmbedProcessor { export class EmbedProcessor {
private readonly pathUtils: PathUtils; private readonly pathUtils: PathUtils;
@@ -16,6 +22,195 @@ export class EmbedProcessor {
constructor(private plugin: obsidianTypstPDFExport) { constructor(private plugin: obsidianTypstPDFExport) {
this.pathUtils = new PathUtils(plugin.app); this.pathUtils = new PathUtils(plugin.app);
} }
/**
* Handle completion of image download and write to vault.
* @param chunks Downloaded image data chunks
* @param outputPath Absolute path where the image should be written
* @param resolve Promise resolver to call with result
*/
private async handleDownloadComplete(
chunks: Buffer[],
outputPath: string,
resolve: (value: string | null) => void
): Promise<void> {
try {
// Check if file already exists to avoid overwriting
const exists = await this.pathUtils.fileExists(outputPath);
if (exists) {
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
resolve(outputPath);
return;
}
// Combine chunks and write using vault adapter
const buffer = Buffer.concat(chunks);
// Convert Buffer to ArrayBuffer for vault adapter
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
// Convert absolute path to vault-relative for adapter operations
const relativeOutputPath = this.pathUtils.toVaultRelative(outputPath);
await this.plugin.app.vault.adapter.writeBinary(relativeOutputPath, arrayBuffer);
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
resolve(outputPath);
} catch (err) {
console.error(`Export: Error writing image file: ${err.message}`);
resolve(null);
}
}
/**
* Resolve a local file path using Obsidian's API and filesystem fallbacks
* @param decodedPath The decoded (non-URL-encoded) path to resolve
* @param vaultBasePath Base path of the vault
* @param currentFile Current file being processed (optional, enables Obsidian API resolution)
* @param additionalPaths Additional paths to try after standard paths
* @param useObsidianApi Whether to try Obsidian's link resolution API first (requires currentFile)
* @returns Full path to file if found, null otherwise
*/
private async resolveLocalPath(
decodedPath: string,
vaultBasePath: string,
currentFile?: TFile,
additionalPaths: string[] = [],
useObsidianApi: boolean = true
): Promise<string | null> {
// Strategy 1: Use Obsidian's link resolution API (if enabled and currentFile provided)
if (useObsidianApi && currentFile) {
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest(
decodedPath,
currentFile.path
);
if (resolvedFile && resolvedFile instanceof TFile) {
// Convert to full filesystem path
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try {
const exists = await this.pathUtils.fileExists(fullPath);
if (exists) {
return fullPath;
}
} catch {
// File exists in metadata but not on filesystem, continue to fallbacks
}
}
}
// Fallback strategies: Try filesystem-based resolution
const possiblePaths = [
// Standard path relative to vault root
path.resolve(vaultBasePath, decodedPath),
// Relative to current file's directory (for local attachments)
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
// Additional paths provided by caller
...additionalPaths
].filter((p): p is string => p !== null);
// Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) {
try {
const exists = await this.pathUtils.fileExists(possiblePath);
if (exists) {
return possiblePath;
}
} catch {
// File doesn't exist, continue to next path
}
}
return null;
}
/**
* Download a remote image to the temp directory
* Returns the local path if successful, null if failed
*/
private async downloadRemoteImage(imageUrl: string, tempDir: string): Promise<string | null> {
return new Promise((resolve, reject) => {
try {
// Parse URL to get filename
const urlObj = new URL(imageUrl);
const urlPath = urlObj.pathname;
const fileName = path.basename(urlPath) || `remote-image-${Date.now()}`;
// Ensure we have a valid file extension
// Extract extension and normalize it (lowercase)
const ext = path.extname(fileName).toLowerCase();
// Preserve any existing extension, or append .png if no extension present
// This handles all image types (svg, ico, avif, etc.) without forcing .png
const finalFileName = ext
? fileName // Has an extension, preserve it
: `${fileName}.png`; // No extension, append .png
const outputPath = path.join(tempDir, finalFileName);
// Select appropriate protocol based on parsed URL (handles case-insensitive schemes)
const protocol = urlObj.protocol === 'https:' ? https : http;
console.debug(`Export:Downloading remote image: ${imageUrl}`);
// Use parsed URL object for the request to ensure correct protocol handling
const request = protocol.get(urlObj, (response) => {
// Handle redirects
if (response.statusCode === 301 || response.statusCode === 302) {
const redirectUrl = response.headers.location;
if (redirectUrl) {
// Resolve relative redirects against the original request URL
// This handles both absolute URLs (e.g., "https://example.com/img.png")
// and relative URLs (e.g., "/assets/img.png" or "../img.png")
const absoluteRedirectUrl = new URL(redirectUrl, imageUrl).href;
console.debug(`Export:Following redirect to: ${absoluteRedirectUrl}`);
// Recursively follow redirect with resolved absolute URL
this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve).catch(reject);
return;
}
}
// Check for successful response
if (response.statusCode !== 200) {
console.warn(`Export: Failed to download image, status code: ${response.statusCode}`);
resolve(null);
return;
}
// Collect response data in memory
const chunks: Buffer[] = [];
response.on('data', (chunk: Buffer) => {
chunks.push(chunk);
});
response.on('end', () => {
void this.handleDownloadComplete(chunks, outputPath, resolve);
});
response.on('error', (err) => {
console.error(`Export: Error receiving image data: ${err.message}`);
resolve(null);
});
});
request.on('error', (err) => {
console.error(`Export: Error downloading image: ${err.message}`);
resolve(null);
});
// Set timeout
request.setTimeout(10000, () => {
request.destroy();
console.warn(`Export: Image download timeout: ${imageUrl}`);
resolve(null);
});
} catch (error) {
console.error(`Export: Error in downloadRemoteImage: ${error.message}`);
resolve(null);
}
});
}
/** /**
* Process PDF embeds - convert PDF pages to images for inclusion * Process PDF embeds - convert PDF pages to images for inclusion
@@ -109,37 +304,46 @@ export class EmbedProcessor {
*/ */
async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise<void> { async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise<void> {
let updatedContent = processedResult.content; let updatedContent = processedResult.content;
for (const imageEmbed of processedResult.metadata?.imageEmbeds || []) { for (const imageEmbed of processedResult.metadata?.imageEmbeds || []) {
try { try {
// Decode the URL-encoded sanitized path back to normal characters // Decode the URL-encoded sanitized path back to normal characters
const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath); const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath);
// Try multiple path resolution strategies let fullImagePath: string | null = null;
const possiblePaths = [
// Strategy 1: Relative to vault root (standard Obsidian behavior) // Check if this is a remote URL (http:// or https://)
path.resolve(vaultBasePath, decodedPath), const isRemoteUrl = /^https?:\/\//i.test(decodedPath);
// Strategy 2: Relative to current file's directory (for local attachments)
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null, if (isRemoteUrl) {
// Strategy 3: Check in attachments folder (common pattern) // Try to download the remote image
path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath)) console.debug(`Export:Attempting to download remote image: ${decodedPath}`);
].filter((p): p is string => p !== null); const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir);
let fullImagePath = null; if (downloadedPath) {
// Successfully downloaded, use it as a local image
// Try each possible path until we find one that exists fullImagePath = downloadedPath;
for (const possiblePath of possiblePaths) { console.debug(`Export:Successfully downloaded and will embed remote image`);
try { } else {
const exists = await this.pathUtils.fileExists(possiblePath); // Download failed, use placeholder
if (exists) { console.warn(`Export: Failed to download remote image: ${decodedPath}`);
fullImagePath = possiblePath; const fallbackOutput = `[🌐 **Remote image download failed:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`;
break; updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
} continue;
} catch {
// File doesn't exist, continue to next path
} }
} else {
// Resolve local file path using helper method
// Note: Image embeds don't use Obsidian API, only filesystem resolution
const attachmentsPath = path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath));
fullImagePath = await this.resolveLocalPath(
decodedPath,
vaultBasePath,
currentFile,
[attachmentsPath],
false // Don't use Obsidian API for image embeds
);
} }
if (!fullImagePath) { if (!fullImagePath) {
console.warn(`Export: Image file not found: ${decodedPath}`); console.warn(`Export: Image file not found: ${decodedPath}`);
// Keep the original marker or replace with placeholder // Keep the original marker or replace with placeholder
@@ -156,15 +360,14 @@ export class EmbedProcessor {
// Convert WebP to PNG using ImageMagick // Convert WebP to PNG using ImageMagick
const originalImageName = path.basename(fullImagePath); const originalImageName = path.basename(fullImagePath);
const pngFileName = originalImageName.replace(/\.webp$/i, '.png'); const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images'); // Use vault-relative path for ensureDir (it uses vault.adapter)
await this.pathUtils.ensureDir(vaultTempImagesDir); const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultRelativeTempDir);
// But use absolute path for ImageMagick
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName); const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
try { try {
// Use PathResolver to get the correct ImageMagick path // Use PathResolver to get the correct ImageMagick path
const { PathResolver } = await import('./PathResolver'); const { PathResolver } = await import('./PathResolver');
@@ -298,48 +501,14 @@ export class EmbedProcessor {
// Decode the URL-encoded sanitized path back to normal characters // Decode the URL-encoded sanitized path back to normal characters
const decodedPath = decodeURIComponent(sanitizedPath); const decodedPath = decodeURIComponent(sanitizedPath);
// Strategy 1: Use Obsidian's link resolution API (primary strategy) // Use helper method with Obsidian API enabled
if (currentFile) { return await this.resolveLocalPath(
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest( decodedPath,
decodedPath, vaultBasePath,
currentFile.path currentFile,
); [], // No additional paths for PDFs
true // Use Obsidian API
if (resolvedFile && resolvedFile instanceof TFile) { );
// Convert to full filesystem path
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try {
const exists = await this.pathUtils.fileExists(fullPath);
if (exists) {
return fullPath;
}
} catch {
// File exists in metadata but not on filesystem, continue to fallbacks
}
}
}
// Fallback strategies: Try filesystem-based resolution
const possiblePaths = [
// Strategy 2: Relative to vault root (standard Obsidian behavior)
path.resolve(vaultBasePath, decodedPath),
// Strategy 3: Relative to current file's directory (for local attachments)
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null
].filter((p): p is string => p !== null);
// Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) {
try {
const exists = await this.pathUtils.fileExists(possiblePath);
if (exists) {
return possiblePath;
}
} catch {
// File doesn't exist, continue to next path
}
}
return null;
} }
/** /**
@@ -349,50 +518,15 @@ export class EmbedProcessor {
// Decode the URL-encoded sanitized path back to normal characters // Decode the URL-encoded sanitized path back to normal characters
const decodedPath = decodeURIComponent(sanitizedPath); const decodedPath = decodeURIComponent(sanitizedPath);
// Strategy 1: Use Obsidian's link resolution API (primary strategy) // Use helper method with Obsidian API enabled and attachments folder as additional path
if (currentFile) { const attachmentsPath = path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath));
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest( return await this.resolveLocalPath(
decodedPath, decodedPath,
currentFile.path vaultBasePath,
); currentFile,
[attachmentsPath], // Check attachments folder as additional path
if (resolvedFile && resolvedFile instanceof TFile) { true // Use Obsidian API
// Convert to full filesystem path );
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try {
const exists = await this.pathUtils.fileExists(fullPath);
if (exists) {
return fullPath;
}
} catch {
// File exists in metadata but not on filesystem, continue to fallbacks
}
}
}
// Fallback strategies: Try filesystem-based resolution
const possiblePaths = [
// Strategy 2: Relative to vault root (standard Obsidian behavior)
path.resolve(vaultBasePath, decodedPath),
// Strategy 3: Relative to current file's directory (for local attachments)
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
// Strategy 4: Check in attachments folder (common pattern)
path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath))
].filter((p): p is string => p !== null);
// Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) {
try {
const exists = await this.pathUtils.fileExists(possiblePath);
if (exists) {
return possiblePath;
}
} catch {
// File doesn't exist, continue to next path
}
}
return null;
} }
/** /**
@@ -410,8 +544,11 @@ export class EmbedProcessor {
vaultBasePath: string vaultBasePath: string
): Promise<{ relativeImagePath: string; relativePdfPath: string }> { ): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
// Copy image to vault temp directory for access // Copy image to vault temp directory for access
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images'); // Use vault-relative path for ensureDir (it uses vault.adapter)
await this.pathUtils.ensureDir(vaultTempImagesDir); const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultRelativeTempDir);
// But use absolute path for file operations
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
// Sanitize the basename for use in filename - replace problematic characters // Sanitize the basename for use in filename - replace problematic characters
const sanitizedBaseName = baseName const sanitizedBaseName = baseName
@@ -423,8 +560,12 @@ export class EmbedProcessor {
const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName); const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName);
// Copy file using vault adapter // Copy file using vault adapter
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath); // Convert absolute paths to vault-relative paths for adapter operations
await this.plugin.app.vault.adapter.writeBinary(vaultImagePath, sourceBuffer); const relativeSourcePath = this.pathUtils.toVaultRelative(imagePath);
const relativeVaultImagePath = this.pathUtils.toVaultRelative(vaultImagePath);
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSourcePath);
await this.plugin.app.vault.adapter.writeBinary(relativeVaultImagePath, sourceBuffer);
// Get relative paths from vault base // Get relative paths from vault base
const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
+22 -10
View File
@@ -20,10 +20,12 @@ export class EventHandlers {
if (file.extension === 'md') { if (file.extension === 'md') {
menu.addItem((item) => { menu.addItem((item) => {
item item
.setTitle('Export to PDF (Typst)') .setTitle('Export to PDF')
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportFile(file); this.plugin.exportFile(file).catch(error => {
console.error('Failed to export file:', error);
});
}); });
}); });
} }
@@ -35,10 +37,12 @@ export class EventHandlers {
this.plugin.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => { this.plugin.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => {
menu.addItem((item) => { menu.addItem((item) => {
item item
.setTitle('Export to PDF (Typst)') .setTitle('Export to PDF')
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportCurrentNote(view); this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
});
}); });
}); });
}) })
@@ -48,15 +52,17 @@ export class EventHandlers {
this.plugin.registerEvent( this.plugin.registerEvent(
this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => { this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => {
// Filter for markdown files only // Filter for markdown files only
const markdownFiles = files.filter(this.plugin.isMarkdownFile); const markdownFiles = files.filter((file) => this.plugin.isMarkdownFile(file));
if (markdownFiles.length > 0) { if (markdownFiles.length > 0) {
menu.addItem((item) => { menu.addItem((item) => {
item item
.setTitle(`Export to PDF (Typst)`) .setTitle(`Export to PDF`)
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportFiles(markdownFiles); this.plugin.exportFiles(markdownFiles).catch(error => {
console.error('Failed to export files:', error);
});
}); });
}); });
@@ -65,7 +71,9 @@ export class EventHandlers {
.setTitle(`Export with configuration...`) .setTitle(`Export with configuration...`)
.setIcon('settings') .setIcon('settings')
.onClick(() => { .onClick(() => {
this.plugin.showExportModalForFiles(markdownFiles); this.plugin.showExportModalForFiles(markdownFiles).catch(error => {
console.error('Failed to show export modal for files:', error);
});
}); });
}); });
} }
@@ -92,7 +100,9 @@ export class EventHandlers {
.setTitle('Export current note(s)') .setTitle('Export current note(s)')
.setIcon('file-output') .setIcon('file-output')
.onClick(() => { .onClick(() => {
this.plugin.exportFile(activeView.file!); this.plugin.exportFile(activeView.file!).catch(error => {
console.error('Failed to export file:', error);
});
}) })
); );
@@ -101,7 +111,9 @@ export class EventHandlers {
.setTitle('Export with configuration…') .setTitle('Export with configuration…')
.setIcon('settings') .setIcon('settings')
.onClick(() => { .onClick(() => {
this.plugin.showExportModal(activeView); this.plugin.showExportModal(activeView).catch(error => {
console.error('Failed to show export modal:', error);
});
}) })
); );
+10 -9
View File
@@ -143,7 +143,7 @@ export class ExportOrchestrator {
this.plugin.currentExportController = new AbortController(); this.plugin.currentExportController = new AbortController();
try { try {
// Create temp directory for conversion // Create temp directories for conversion
const tempManager = new TempDirectoryManager({ const tempManager = new TempDirectoryManager({
vaultPath: vaultPath, vaultPath: vaultPath,
configDir: this.plugin.app.vault.configDir, configDir: this.plugin.app.vault.configDir,
@@ -151,20 +151,21 @@ export class ExportOrchestrator {
pluginName: this.plugin.manifest.id pluginName: this.plugin.manifest.id
}); });
const tempDir = await tempManager.ensureTempDir('pandoc'); const tempDir = await tempManager.ensureTempDir('pandoc');
const tempImagesDir = await tempManager.ensureTempDir('images');
// Load file content // Load file content
const content = await this.plugin.app.vault.read(file); const content = await this.plugin.app.vault.read(file);
// Create progress notice with cancel button // Create progress notice with cancel button
const progressNotice = new Notice('', 0); const progressNotice = new Notice('', 0);
const cancelButton = progressNotice.noticeEl.createEl('button', { const cancelButton = progressNotice.messageEl.createEl('button', {
text: 'Cancel', text: 'Cancel',
cls: 'mod-warning' cls: 'mod-warning'
}); });
cancelButton.addEventListener('click', () => this.cancelExport()); cancelButton.addEventListener('click', () => this.cancelExport());
progressNotice.setMessage('Preprocessing markdown content...'); progressNotice.setMessage('Preprocessing Markdown content...');
// Preprocess markdown // Preprocess Markdown
const preprocessor = new MarkdownPreprocessor({ const preprocessor = new MarkdownPreprocessor({
vaultPath: vaultPath, vaultPath: vaultPath,
options: { options: {
@@ -179,7 +180,7 @@ export class ExportOrchestrator {
noteTitle: file.basename noteTitle: file.basename
}); });
const processedResult = await preprocessor.process(content); const processedResult = preprocessor.process(content);
if (processedResult.errors.length > 0) { if (processedResult.errors.length > 0) {
console.warn('Preprocessing errors:', processedResult.errors); console.warn('Preprocessing errors:', processedResult.errors);
@@ -191,12 +192,12 @@ export class ExportOrchestrator {
// Process PDF embeds if any were found // Process PDF embeds if any were found
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) { if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles; const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles;
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles); await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempImagesDir, file, embedPdfFiles);
} }
// Process image embeds if any were found // Process image embeds if any were found
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) { if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempDir, file); await this.plugin.processImageEmbeds(processedResult, vaultPath, tempImagesDir, file);
} }
// Process file embeds if any were found // Process file embeds if any were found
@@ -319,10 +320,10 @@ export class ExportOrchestrator {
*/ */
async handleFolderExport(folder: TFolder): Promise<void> { async handleFolderExport(folder: TFolder): Promise<void> {
// Get all markdown files in the folder // Get all markdown files in the folder
const markdownFiles = folder.children.filter(this.plugin.isMarkdownFile); const markdownFiles = folder.children.filter((file) => this.plugin.isMarkdownFile(file));
if (markdownFiles.length === 0) { if (markdownFiles.length === 0) {
new Notice('No markdown files found in this folder'); new Notice('No Markdown files found in this folder');
return; return;
} }
+1 -2
View File
@@ -3,6 +3,7 @@
* Handles font discovery, caching, and retrieval for the plugin * Handles font discovery, caching, and retrieval for the plugin
*/ */
import { spawn } from 'child_process';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { ExportErrorHandler } from '../core/ExportErrorHandler'; import { ExportErrorHandler } from '../core/ExportErrorHandler';
import { FALLBACK_FONTS } from '../core/constants'; import { FALLBACK_FONTS } from '../core/constants';
@@ -16,8 +17,6 @@ export class FontManager {
*/ */
async cacheAvailableFonts(): Promise<void> { async cacheAvailableFonts(): Promise<void> {
try { try {
const { spawn } = require('child_process');
const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst'); const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
// Use spawn instead of exec for security - arguments passed separately // Use spawn instead of exec for security - arguments passed separately
+17 -8
View File
@@ -3,6 +3,7 @@
* Handles executable path resolution and output path preparation * Handles executable path resolution and output path preparation
*/ */
import { spawnSync } from 'child_process';
import { TFile } from 'obsidian'; import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { SecurityUtils } from '../core/SecurityUtils'; import { SecurityUtils } from '../core/SecurityUtils';
@@ -26,14 +27,16 @@ export class PathResolver {
} }
// Try to find the executable using which command // Try to find the executable using which command
const { spawnSync } = require('child_process'); // Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
try { try {
const augmentedEnv = { const augmentedEnv = {
...process.env, ...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}` PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
}; };
const result = spawnSync('which', [defaultName], { const result = spawnSync(whichCommand, [defaultName], {
encoding: 'utf8', encoding: 'utf8',
env: augmentedEnv env: augmentedEnv
}); });
@@ -56,16 +59,21 @@ export class PathResolver {
* Prepare the output path for a file * Prepare the output path for a file
*/ */
async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> { async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> {
// Check if output folder is set
if (!outputFolder || outputFolder.trim() === '') {
throw new Error('Output folder is not set. Please configure the output folder in plugin settings.');
}
// Validate output folder for security // Validate output folder for security
if (!SecurityUtils.validateOutputPath(outputFolder)) { if (!SecurityUtils.validateOutputPath(outputFolder)) {
throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`); throw new Error(`Invalid output folder path: "${outputFolder}". Path contains invalid characters or traversal attempts.`);
} }
const vaultPath = this.pathUtils.getVaultPath(); const vaultPath = this.pathUtils.getVaultPath();
const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder); const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder);
// Create output directory if it doesn't exist // Create output directory if it doesn't exist (use vault-relative path for vault adapter)
await this.pathUtils.ensureDir(outputDir); await this.pathUtils.ensureDir(outputFolder);
// Preserve folder structure if configured // Preserve folder structure if configured
let relativePath = ''; let relativePath = '';
@@ -73,8 +81,9 @@ export class PathResolver {
const folderPath = path.dirname(file.path); const folderPath = path.dirname(file.path);
if (folderPath !== '.') { if (folderPath !== '.') {
relativePath = folderPath; relativePath = folderPath;
const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath); // Use vault-relative path for vault adapter
await this.pathUtils.ensureDir(fullOutputDir); const vaultRelativeOutputDir = this.pathUtils.joinPath(outputFolder, relativePath);
await this.pathUtils.ensureDir(vaultRelativeOutputDir);
} }
} }
+22 -19
View File
@@ -51,33 +51,36 @@ export class PluginLifecycle {
// Clean up any leftover temp directories from previous sessions // Clean up any leftover temp directories from previous sessions
this.cleanupStartupTempDirectories(); this.cleanupStartupTempDirectories();
// Check dependencies on startup (async, don't await) // Check dependencies on startup
this.plugin.checkDependenciesAsync(); this.plugin.checkDependenciesOnStartup();
// Cache available fonts (async, don't await) // Cache available fonts (async, don't await)
this.plugin.cacheAvailableFonts(); void this.plugin.cacheAvailableFonts();
} }
/** /**
* Clean up resources during onunload * Clean up resources during onunload
*/ */
cleanup(): void { async cleanup(): Promise<void> {
// Cancel any ongoing exports // Cancel any ongoing exports
if (this.plugin.currentExportController) { if (this.plugin.currentExportController) {
this.plugin.currentExportController.abort(); this.plugin.currentExportController.abort();
} }
// Clean up temp directories on plugin unload (fire-and-forget async) // Dispose converter to clean up its temp directories
(async () => { if (this.plugin.converter) {
try { await this.plugin.converter.dispose();
const vaultPath = this.pathUtils.getVaultPath(); }
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
await cleanupManager.cleanupAllTempDirs(); // Clean up temp directories on plugin unload
} catch (error) { try {
console.warn('Export: Failed to clean up temp directories during unload:', error); const vaultPath = this.pathUtils.getVaultPath();
} const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
})(); await cleanupManager.cleanupAllTempDirs();
} catch (error) {
console.warn('Export: Failed to clean up temp directories during unload:', error);
}
} }
/** /**
@@ -85,11 +88,11 @@ export class PluginLifecycle {
*/ */
private cleanupStartupTempDirectories(): void { private cleanupStartupTempDirectories(): void {
// Clean up temp directories (fire-and-forget async) // Clean up temp directories (fire-and-forget async)
(async () => { void (async () => {
try { try {
const vaultPath = this.pathUtils.getVaultPath(); const vaultPath = this.pathUtils.getVaultPath();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app); const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
const _result = await cleanupManager.cleanupAllTempDirs(); await cleanupManager.cleanupAllTempDirs();
if (this.plugin.settings.behavior.debugMode) { if (this.plugin.settings.behavior.debugMode) {
// Debug logging was here but empty in original // Debug logging was here but empty in original
+31 -21
View File
@@ -9,6 +9,7 @@ import {
Setting, Setting,
normalizePath normalizePath
} from 'obsidian'; } from 'obsidian';
import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { ExportFormat } from '../core/settings'; import { ExportFormat } from '../core/settings';
import { SecurityUtils } from '../core/SecurityUtils'; import { SecurityUtils } from '../core/SecurityUtils';
@@ -27,9 +28,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
display(): void { display(): void {
const { containerEl } = this; const { containerEl } = this;
containerEl.empty(); containerEl.empty();
containerEl.createEl('h2', { text: 'Typst PDF Export Settings' });
// Executable paths section // Executable paths section
this.createExecutablePathsSection(containerEl); this.createExecutablePathsSection(containerEl);
@@ -47,14 +46,16 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createExecutablePathsSection(containerEl: HTMLElement): void { private createExecutablePathsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Executable Paths' }); new Setting(containerEl)
.setName('Executable paths')
.setHeading();
// Add dependency check button // Add dependency check button
new Setting(containerEl) new Setting(containerEl)
.setName('Dependencies') .setName('Dependencies')
.setDesc('Check the status of external dependencies') .setDesc('Check the status of external dependencies')
.addButton(button => button .addButton(button => button
.setButtonText('Check Dependencies') .setButtonText('Check dependencies')
.setCta() .setCta()
.onClick(async () => { .onClick(async () => {
await this.plugin.showDependencyStatus(); await this.plugin.showDependencyStatus();
@@ -62,9 +63,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Pandoc path') .setName('Pandoc path')
.setDesc('Path to pandoc executable (leave empty to use system PATH)') .setDesc('Path to pandoc executable (leave empty to use system path)')
.addText(text => text .addText(text => text
.setPlaceholder('pandoc') .setPlaceholder('Pandoc')
.setValue(this.plugin.settings.pandocPath) .setValue(this.plugin.settings.pandocPath)
.onChange(async (value) => { .onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) { if (!SecurityUtils.validateExecutablePath(value)) {
@@ -77,9 +78,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Typst path') .setName('Typst path')
.setDesc('Path to typst executable (leave empty to use system PATH)') .setDesc('Path to typst executable (leave empty to use system path)')
.addText(text => text .addText(text => text
.setPlaceholder('typst') .setPlaceholder('Typst')
.setValue(this.plugin.settings.typstPath) .setValue(this.plugin.settings.typstPath)
.onChange(async (value) => { .onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) { if (!SecurityUtils.validateExecutablePath(value)) {
@@ -91,10 +92,10 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
})); }));
new Setting(containerEl) new Setting(containerEl)
.setName('ImageMagick path') .setName('Imagemagick path')
.setDesc('Path to ImageMagick executable (leave empty to use system PATH)') .setDesc('Path to imagemagick executable (leave empty to use system path)')
.addText(text => text .addText(text => text
.setPlaceholder('magick') .setPlaceholder('Magick')
.setValue(this.plugin.settings.executablePaths.imagemagickPath) .setValue(this.plugin.settings.executablePaths.imagemagickPath)
.onChange(async (value) => { .onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) { if (!SecurityUtils.validateExecutablePath(value)) {
@@ -131,11 +132,13 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createExportDefaultsSection(containerEl: HTMLElement): void { private createExportDefaultsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Export Defaults' }); new Setting(containerEl)
.setName('Export defaults')
.setHeading();
new Setting(containerEl) new Setting(containerEl)
.setName('Default template') .setName('Default template')
.setDesc('Default Typst template for exports') .setDesc('Default typst template for exports')
.addDropdown(async (dropdown) => { .addDropdown(async (dropdown) => {
try { try {
const templates = await this.plugin.templateManager.getAvailableTemplates(); const templates = await this.plugin.templateManager.getAvailableTemplates();
@@ -157,7 +160,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} catch (error) { } catch (error) {
console.error('Failed to load templates:', error); console.error('Failed to load templates:', error);
// Fallback to text input // Fallback to text input
dropdown.addOption('default.typ', 'default.typ'); dropdown.addOption('default.typ', 'Default.typ');
dropdown.setValue(this.plugin.settings.exportDefaults.template); dropdown.setValue(this.plugin.settings.exportDefaults.template);
} }
}); });
@@ -176,13 +179,14 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
new Setting(containerEl) new Setting(containerEl)
.setName('Output folder') .setName('Output folder')
.setDesc('Default folder for exported PDFs (relative to vault root)') .setDesc('Folder for exported pdfs (relative to vault root)')
.addText(text => { .addText(text => {
text text
.setPlaceholder('exports') .setPlaceholder('Exports')
.setValue(this.plugin.settings.outputFolder) .setValue(this.plugin.settings.outputFolder)
.onChange(async (value) => { .onChange(async (value) => {
const normalizedValue = normalizePath(value); // Don't normalize absolute paths as normalizePath strips the leading slash
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
if (!SecurityUtils.validateOutputPath(normalizedValue)) { if (!SecurityUtils.validateOutputPath(normalizedValue)) {
ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue)); ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue));
return; return;
@@ -229,7 +233,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createTypographyDefaultsSection(containerEl: HTMLElement): void { private createTypographyDefaultsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Typography Defaults' }); new Setting(containerEl)
.setName('Typography defaults')
.setHeading();
// Use helper method for all three font dropdowns // Use helper method for all three font dropdowns
this.createFontDropdown( this.createFontDropdown(
@@ -293,7 +299,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createPageSetupSection(containerEl: HTMLElement): void { private createPageSetupSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Page Setup' }); new Setting(containerEl)
.setName('Page setup')
.setHeading();
new Setting(containerEl) new Setting(containerEl)
.setName('Page size') .setName('Page size')
@@ -363,7 +371,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
} }
private createBehaviorSection(containerEl: HTMLElement): void { private createBehaviorSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Behavior' }); new Setting(containerEl)
.setName('Behavior')
.setHeading();
new Setting(containerEl) new Setting(containerEl)
.setName('Open after export') .setName('Open after export')
+3 -10
View File
@@ -36,15 +36,7 @@ export class TemplateManager {
} }
// Read directory contents - convert absolute path to vault-relative // Read directory contents - convert absolute path to vault-relative
const vaultBasePath = this.pathUtils.getVaultPath(); const vaultRelativePath = this.pathUtils.toVaultRelative(this.templatesPath);
let vaultRelativePath = this.templatesPath;
// Convert absolute path to vault-relative path
if (this.templatesPath.startsWith(vaultBasePath)) {
vaultRelativePath = this.templatesPath.substring(vaultBasePath.length);
// Remove leading separators
vaultRelativePath = vaultRelativePath.replace(/^[/\\]+/, '');
}
const list = await this.plugin.app.vault.adapter.list(vaultRelativePath); const list = await this.plugin.app.vault.adapter.list(vaultRelativePath);
const files = list.files.map(filePath => path.basename(filePath)); const files = list.files.map(filePath => path.basename(filePath));
@@ -127,11 +119,12 @@ export class TemplateManager {
case 'version': case 'version':
metadata.version = value; metadata.version = value;
break; break;
case 'variable': case 'variable': {
// Parse variable definition (e.g., @variable: font:string:Body font family) // Parse variable definition (e.g., @variable: font:string:Body font family)
const [name, type, description] = value.split(':'); const [name, type, description] = value.split(':');
metadata.variables.push({ name, type, description }); metadata.variables.push({ name, type, description });
break; break;
}
} }
} }
+6 -4
View File
@@ -57,8 +57,9 @@ export class EmbeddedTemplateManager {
} }
try { try {
// Ensure templates directory exists // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
await this.pathUtils.ensureDir(this.templatesDir); const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
await this.pathUtils.ensureDir(relativeTemplatesDir);
// Extract template content // Extract template content
const content = extractTemplate(templateName, filePath); const content = extractTemplate(templateName, filePath);
@@ -105,8 +106,9 @@ export class EmbeddedTemplateManager {
const embeddedNames = getAllTemplateNames(); const embeddedNames = getAllTemplateNames();
// Ensure templates directory exists // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
await this.pathUtils.ensureDir(this.templatesDir); const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
await this.pathUtils.ensureDir(relativeTemplatesDir);
for (const templateName of embeddedNames) { for (const templateName of embeddedNames) {
try { try {
+8 -8
View File
@@ -20,7 +20,7 @@ export class ExportConfigModal extends Modal {
plugin: obsidianTypstPDFExport; plugin: obsidianTypstPDFExport;
private state: ModalState; private state: ModalState;
private sections: Map<string, ModalSection> = new Map(); private sections: Map<string, ModalSection> = new Map();
private onSubmit: (config: ExportConfig) => void; private onSubmit: (config: ExportConfig) => void | Promise<void>;
private onCancel?: () => void; private onCancel?: () => void;
private renderer: ModalRenderer; private renderer: ModalRenderer;
private validator: ModalValidator; private validator: ModalValidator;
@@ -29,7 +29,7 @@ export class ExportConfigModal extends Modal {
app: App, app: App,
plugin: obsidianTypstPDFExport, plugin: obsidianTypstPDFExport,
settings: Partial<ExportConfigModalSettings>, settings: Partial<ExportConfigModalSettings>,
onSubmit: (config: ExportConfig) => void, onSubmit: (config: ExportConfig) => void | Promise<void>,
onCancel?: () => void onCancel?: () => void
) { ) {
super(app); super(app);
@@ -38,7 +38,7 @@ export class ExportConfigModal extends Modal {
this.onCancel = onCancel; this.onCancel = onCancel;
// Initialize state // Initialize state
this.state = new ModalState(settings); this.state = new ModalState(settings, app);
// Register sections // Register sections
this.registerSections(); this.registerSections();
@@ -81,9 +81,9 @@ export class ExportConfigModal extends Modal {
// Initialize renderer with content container // Initialize renderer with content container
this.renderer.initialize(contentContainer); this.renderer.initialize(contentContainer);
// Load available templates // Load available templates
this.loadAvailableTemplates(); void this.loadAvailableTemplates();
} }
private async loadAvailableTemplates(): Promise<void> { private async loadAvailableTemplates(): Promise<void> {
@@ -117,10 +117,10 @@ export class ExportConfigModal extends Modal {
// Re-render sections to update UI // Re-render sections to update UI
this.renderer.refreshSections(); this.renderer.refreshSections();
// Reload templates to update the dropdown // Reload templates to update the dropdown
this.loadAvailableTemplates(); void this.loadAvailableTemplates();
ExportErrorHandler.showSettingsReset(); ExportErrorHandler.showSettingsReset();
} }
+19 -244
View File
@@ -10,7 +10,7 @@ import { ModalSection } from './modalTypes';
export interface ModalRendererCallbacks { export interface ModalRendererCallbacks {
onReset: () => void; onReset: () => void;
onCancel: () => void; onCancel: () => void;
onSubmit: () => void; onSubmit: () => void | Promise<void>;
} }
export class ModalRenderer { export class ModalRenderer {
@@ -47,7 +47,6 @@ export class ModalRenderer {
initialize(contentContainer: HTMLElement): void { initialize(contentContainer: HTMLElement): void {
this.contentContainer = contentContainer; this.contentContainer = contentContainer;
this.setupInitialLayout(); this.setupInitialLayout();
this.addModalStyles();
} }
/** /**
@@ -119,9 +118,9 @@ export class ModalRenderer {
// Progress bar container // Progress bar container
const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container'); const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container');
this.progressBar = progressBarContainer.createDiv('export-progress-bar'); this.progressBar = progressBarContainer.createDiv('export-progress-bar');
// Progress percentage // Progress percentage
const _progressPercent = this.progressContainer.createEl('div', { this.progressContainer.createEl('div', {
cls: 'export-progress-percent', cls: 'export-progress-percent',
text: '0%' text: '0%'
}); });
@@ -135,7 +134,7 @@ export class ModalRenderer {
// Reset button (left side) // Reset button (left side)
this.resetButton = buttonContainer.createEl('button', { this.resetButton = buttonContainer.createEl('button', {
text: 'Reset to Defaults', text: 'Reset to defaults',
cls: 'mod-muted' cls: 'mod-muted'
}); });
this.resetButton.addEventListener('click', () => this.callbacks.onReset()); this.resetButton.addEventListener('click', () => this.callbacks.onReset());
@@ -155,7 +154,20 @@ export class ModalRenderer {
text: 'Export', text: 'Export',
cls: 'mod-cta' cls: 'mod-cta'
}); });
this.submitButton.addEventListener('click', () => this.callbacks.onSubmit()); this.submitButton.addEventListener('click', () => {
this.setExportingState(true);
Promise.resolve(this.callbacks.onSubmit()).catch(err => {
// Log the error for debugging
console.error('Export submission failed:', err);
// Show user-facing error feedback
const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred during export';
this.showValidationErrors([errorMessage]);
// Re-enable buttons so user can try again or cancel
this.setExportingState(false);
});
});
} }
/** /**
@@ -219,7 +231,7 @@ export class ModalRenderer {
} }
const errorContainer = this.formContainer.createDiv('validation-errors'); const errorContainer = this.formContainer.createDiv('validation-errors');
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' }); errorContainer.createEl('h4', { text: 'Validation errors', cls: 'error-title' });
const errorList = errorContainer.createEl('ul'); const errorList = errorContainer.createEl('ul');
errors.forEach(error => { errors.forEach(error => {
@@ -251,241 +263,4 @@ export class ModalRenderer {
// Remove after 5 seconds // Remove after 5 seconds
setTimeout(() => warningContainer.remove(), 5000); setTimeout(() => warningContainer.remove(), 5000);
} }
/**
* Add custom CSS styles for the modal
*/
private addModalStyles(): void {
// Add custom styles for the modal
const style = document.createElement('style');
style.textContent = `
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 16px 24px 8px 24px;
border-bottom: 1px solid var(--background-modifier-border);
flex-shrink: 0;
}
.export-config-header h2 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.export-note-title {
margin: 0;
font-size: 14px;
color: var(--text-muted);
opacity: 0.8;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
}
.export-config-section {
margin-bottom: 24px;
}
.export-config-section:last-child {
margin-bottom: 0;
}
.export-config-section-title {
font-weight: 600;
margin-bottom: 12px;
padding-bottom: 4px;
border-bottom: 1px solid var(--background-modifier-border-hover);
}
.export-config-buttons {
padding: 16px 24px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 8px;
}
/* Progress styles */
.export-progress-container {
padding: 24px;
text-align: center;
}
.export-progress-container.export-hidden {
display: none;
}
.export-progress-container.export-progress-visible {
display: block;
}
.export-form-hidden {
display: none !important;
}
.export-progress-text {
margin-bottom: 16px;
font-size: 14px;
color: var(--text-muted);
}
.export-progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--background-modifier-border);
border-radius: 4px;
margin-bottom: 8px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background-color: var(--interactive-accent);
border-radius: 4px;
width: var(--progress-width, 0%);
transition: width 0.3s ease;
}
.export-progress-percent {
font-size: 12px;
color: var(--text-muted);
}
/* Form field styles */
.export-setting-item {
margin-bottom: 16px;
}
.export-setting-item-info {
margin-bottom: 6px;
}
.export-setting-item-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-setting-item-description {
font-size: 12px;
color: var(--text-muted);
}
.export-setting-item-control {
display: flex;
align-items: center;
}
.export-setting-item-control input,
.export-setting-item-control select {
flex: 1;
}
/* Folder suggest styles */
.export-folder-suggest-container {
position: relative;
}
.export-folder-suggest-input {
width: 100%;
padding: 6px 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 4px;
background: var(--background-primary);
color: var(--text-normal);
}
.export-folder-suggest-input:focus {
border-color: var(--interactive-accent);
outline: none;
}
/* Validation styles */
.validation-errors, .validation-warnings {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.validation-warnings {
background: var(--background-modifier-warning);
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.warning-title {
color: var(--text-warning);
margin: 0 0 10px 0;
}
.validation-errors ul, .validation-warnings ul {
margin: 0;
padding-left: 20px;
}
.export-validation-error {
color: var(--text-error);
font-size: 12px;
margin-top: 4px;
}
.export-validation-warning {
color: var(--text-warning);
font-size: 12px;
margin-top: 4px;
}
/* Template variable styles */
.export-template-variables {
margin-top: 12px;
}
.export-template-variable {
margin-bottom: 8px;
padding: 8px;
background: var(--background-secondary);
border-radius: 4px;
font-size: 12px;
}
.export-template-variable-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-template-variable-description {
color: var(--text-muted);
font-style: italic;
}
`;
if (!document.head.querySelector('style[data-export-config-modal]')) {
style.setAttribute('data-export-config-modal', 'true');
document.head.appendChild(style);
}
}
} }
+3 -1
View File
@@ -11,7 +11,9 @@ export class BehaviorSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void { render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Export Behavior' }); new Setting(this.container)
.setName('Export behavior')
.setHeading();
this.createBehaviorToggles(state); this.createBehaviorToggles(state);
} }
+13 -7
View File
@@ -4,6 +4,7 @@
*/ */
import { Setting, App, normalizePath, DropdownComponent } from 'obsidian'; import { Setting, App, normalizePath, DropdownComponent } from 'obsidian';
import * as path from 'path';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { ExportFormat } from '../../../core/settings'; import { ExportFormat } from '../../../core/settings';
import { FolderSuggest } from '../../components/FolderSuggest'; import { FolderSuggest } from '../../components/FolderSuggest';
@@ -18,7 +19,9 @@ export class GeneralSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: App): void { render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app; if (app) this.app = app;
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'General Settings' }); new Setting(this.container)
.setName('General settings')
.setHeading();
this.createTemplateSelection(state); this.createTemplateSelection(state);
this.createFormatSelection(state); this.createFormatSelection(state);
@@ -72,13 +75,14 @@ export class GeneralSection implements ModalSection {
new Setting(this.container) new Setting(this.container)
.setName('Output folder') .setName('Output folder')
.setDesc('Folder where PDFs will be saved (relative to vault root)') .setDesc('Location for exported PDF files (relative to vault root or absolute path)')
.addText(text => { .addText(text => {
const input = text const input = text
.setPlaceholder('exports') .setPlaceholder('PDF exports')
.setValue(state.settings.outputFolder || 'exports') .setValue(state.settings.outputFolder || 'exports')
.onChange(value => { .onChange(value => {
const normalizedValue = normalizePath(value); // Don't normalize absolute paths as normalizePath strips the leading slash
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
state.updateSettings({ outputFolder: normalizedValue }); state.updateSettings({ outputFolder: normalizedValue });
}); });
this.outputFolderInput = input.inputEl; this.outputFolderInput = input.inputEl;
@@ -102,9 +106,11 @@ export class GeneralSection implements ModalSection {
// Validate output folder // Validate output folder
if (this.outputFolderInput) { if (this.outputFolderInput) {
const value = normalizePath(this.outputFolderInput.value.trim()); const rawValue = this.outputFolderInput.value.trim();
if (!SecurityUtils.validateOutputPath(value)) { // Don't normalize absolute paths as normalizePath strips the leading slash
errors.push(SecurityUtils.getPathValidationError(value)); const normalizedValue = path.isAbsolute(rawValue) ? rawValue : normalizePath(rawValue);
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
errors.push(SecurityUtils.getPathValidationError(normalizedValue));
} }
} }
+3 -1
View File
@@ -13,7 +13,9 @@ export class LayoutSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void { render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Layout' }); new Setting(this.container)
.setName('Page layout')
.setHeading();
this.createPageSizeSettings(state); this.createPageSizeSettings(state);
this.createOrientationSettings(state); this.createOrientationSettings(state);
+8 -5
View File
@@ -6,6 +6,7 @@
import { Setting } from 'obsidian'; import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper'; import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
import { ExportFormat } from '../../../core/settings';
export class PageSetupSection implements ModalSection { export class PageSetupSection implements ModalSection {
private container: HTMLElement | null = null; private container: HTMLElement | null = null;
@@ -13,7 +14,9 @@ export class PageSetupSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void { render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Setup' }); new Setting(this.container)
.setName('Page setup')
.setHeading();
this.createPageSizeSettings(state); this.createPageSizeSettings(state);
this.createOrientationSettings(state); this.createOrientationSettings(state);
@@ -53,12 +56,12 @@ export class PageSetupSection implements ModalSection {
.setValue(String(state.templateVariables.orientation || 'portrait')) .setValue(String(state.templateVariables.orientation || 'portrait'))
.onChange(value => { .onChange(value => {
const isLandscape = value === 'landscape'; const isLandscape = value === 'landscape';
state.updateTemplateVariables({ state.updateTemplateVariables({
orientation: value, orientation: value,
flipped: isLandscape, flipped: isLandscape,
// Auto-adjust width for single-page mode when flipped // Auto-adjust width for single-page mode when flipped
...(isLandscape && state.settings.format === 'single-page' ...(isLandscape && state.settings.format === ExportFormat.SinglePage
? { width: 'auto' } ? { width: 'auto' }
: {}) : {})
}); });
}); });
@@ -69,7 +72,7 @@ export class PageSetupSection implements ModalSection {
if (!this.container) return; if (!this.container) return;
const marginsContainer = this.container.createDiv('margins-container'); const marginsContainer = this.container.createDiv('margins-container');
marginsContainer.createEl('h4', { text: 'Text Margins' }); marginsContainer.createEl('h4', { text: 'Text margins' });
marginsContainer.createEl('p', { marginsContainer.createEl('p', {
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")', text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
cls: 'setting-item-description' cls: 'setting-item-description'
+31 -67
View File
@@ -3,7 +3,7 @@
* Handles font selection and size configuration * Handles font selection and size configuration
*/ */
import { Setting, App, DropdownComponent } from 'obsidian'; import { Setting, App } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
export class TypographySection implements ModalSection { export class TypographySection implements ModalSection {
@@ -13,36 +13,41 @@ export class TypographySection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: App): void { render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app; if (app) this.app = app;
this.container = containerEl.createDiv('export-section'); this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Typography' }); new Setting(this.container)
.setName('Typography')
// Create font settings asynchronously .setHeading();
this.createFontSettings(state);
this.createFontSizeSettings(state); // Create font settings asynchronously with explicit error handling
// Font size settings are created after font dropdowns to preserve logical ordering
this.createFontSettings(state).catch(error => {
console.error('Failed to create font settings:', error);
// If font loading fails, getAvailableFonts will use hardcoded fallback fonts
});
} }
private async createFontSettings(state: ModalState): Promise<void> { private async createFontSettings(state: ModalState): Promise<void> {
if (!this.container) return; if (!this.container) return;
// Get available fonts from cache // Get available fonts from cache
const availableFonts = await this.getAvailableFonts(state); const availableFonts = await this.getAvailableFonts(state);
// Body font dropdown // Body font dropdown
new Setting(this.container) new Setting(this.container)
.setName('Body font') .setName('Body font')
.setDesc('Primary font for document text') .setDesc('Primary font for document text')
.addDropdown(dropdown => { .addDropdown(dropdown => {
const currentFont = String(state.templateVariables.bodyFont || 'Times New Roman'); const currentFont = String(state.templateVariables.bodyFont || 'Times New Roman');
// Add all available fonts // Add all available fonts
availableFonts.forEach(font => { availableFonts.forEach(font => {
dropdown.addOption(font, font); dropdown.addOption(font, font);
}); });
// Add current font if it's not in the list // Add current font if it's not in the list
if (!availableFonts.includes(currentFont)) { if (!availableFonts.includes(currentFont)) {
dropdown.addOption(currentFont, currentFont); dropdown.addOption(currentFont, currentFont);
} }
// Set current value and change handler // Set current value and change handler
dropdown dropdown
.setValue(currentFont) .setValue(currentFont)
@@ -50,24 +55,24 @@ export class TypographySection implements ModalSection {
state.updateTemplateVariables({ bodyFont: value }); state.updateTemplateVariables({ bodyFont: value });
}); });
}); });
// Heading font dropdown // Heading font dropdown
new Setting(this.container) new Setting(this.container)
.setName('Heading font') .setName('Heading font')
.setDesc('Font for headings and titles') .setDesc('Font for headings and titles')
.addDropdown(dropdown => { .addDropdown(dropdown => {
const currentFont = String(state.templateVariables.headingFont || 'Times New Roman'); const currentFont = String(state.templateVariables.headingFont || 'Times New Roman');
// Add all available fonts // Add all available fonts
availableFonts.forEach(font => { availableFonts.forEach(font => {
dropdown.addOption(font, font); dropdown.addOption(font, font);
}); });
// Add current font if it's not in the list // Add current font if it's not in the list
if (!availableFonts.includes(currentFont)) { if (!availableFonts.includes(currentFont)) {
dropdown.addOption(currentFont, currentFont); dropdown.addOption(currentFont, currentFont);
} }
// Set current value and change handler // Set current value and change handler
dropdown dropdown
.setValue(currentFont) .setValue(currentFont)
@@ -75,24 +80,24 @@ export class TypographySection implements ModalSection {
state.updateTemplateVariables({ headingFont: value }); state.updateTemplateVariables({ headingFont: value });
}); });
}); });
// Monospace font dropdown // Monospace font dropdown
new Setting(this.container) new Setting(this.container)
.setName('Monospace font') .setName('Monospace font')
.setDesc('Font for code blocks and inline code') .setDesc('Font for code blocks and inline code')
.addDropdown(dropdown => { .addDropdown(dropdown => {
const currentFont = String(state.templateVariables.monospaceFont || 'Courier New'); const currentFont = String(state.templateVariables.monospaceFont || 'Courier New');
// Add all available fonts // Add all available fonts
availableFonts.forEach(font => { availableFonts.forEach(font => {
dropdown.addOption(font, font); dropdown.addOption(font, font);
}); });
// Add current font if it's not in the list // Add current font if it's not in the list
if (!availableFonts.includes(currentFont)) { if (!availableFonts.includes(currentFont)) {
dropdown.addOption(currentFont, currentFont); dropdown.addOption(currentFont, currentFont);
} }
// Set current value and change handler // Set current value and change handler
dropdown dropdown
.setValue(currentFont) .setValue(currentFont)
@@ -100,8 +105,11 @@ export class TypographySection implements ModalSection {
state.updateTemplateVariables({ monospaceFont: value }); state.updateTemplateVariables({ monospaceFont: value });
}); });
}); });
// Create font size settings after font dropdowns for logical ordering
this.createFontSizeSettings(state);
} }
private createFontSizeSettings(state: ModalState): void { private createFontSizeSettings(state: ModalState): void {
if (!this.container) return; if (!this.container) return;
@@ -160,51 +168,7 @@ export class TypographySection implements ModalSection {
]; ];
} }
} }
private addFallbackBodyFonts(dropdown: DropdownComponent, state: ModalState, fontType: 'body' | 'heading'): void {
dropdown
.addOption('Concourse OT', 'Concourse OT')
.addOption('Times New Roman', 'Times New Roman')
.addOption('Georgia', 'Georgia')
.addOption('Arial', 'Arial')
.addOption('Helvetica', 'Helvetica')
.addOption('Calibri', 'Calibri')
.addOption('Cambria', 'Cambria')
.addOption('Palatino', 'Palatino')
.addOption('Book Antiqua', 'Book Antiqua');
// Set the appropriate value based on font type
const currentValue = fontType === 'body'
? state.templateVariables.bodyFont
: state.templateVariables.headingFont;
dropdown
.setValue(String(currentValue || 'Concourse OT'))
.onChange((value: string) => {
if (fontType === 'body') {
state.updateTemplateVariables({ bodyFont: value });
} else {
state.updateTemplateVariables({ headingFont: value });
}
});
}
private addFallbackMonospaceFonts(dropdown: DropdownComponent, state: ModalState): void {
dropdown
.addOption('Source Code Pro', 'Source Code Pro')
.addOption('Courier New', 'Courier New')
.addOption('Monaco', 'Monaco')
.addOption('Consolas', 'Consolas')
.addOption('Menlo', 'Menlo')
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
.addOption('Liberation Mono', 'Liberation Mono')
.addOption('Ubuntu Mono', 'Ubuntu Mono')
.setValue(String(state.templateVariables.monospaceFont || 'Source Code Pro'))
.onChange((value: string) => {
state.updateTemplateVariables({ monospaceFont: value });
});
}
validate(): ValidationResult { validate(): ValidationResult {
const errors: string[] = []; const errors: string[] = [];
const warnings: string[] = []; const warnings: string[] = [];
+9 -8
View File
@@ -3,6 +3,7 @@
* Centralized state management for the Export Configuration Modal * Centralized state management for the Export Configuration Modal
*/ */
import { App } from 'obsidian';
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes'; import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings'; import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings';
@@ -13,7 +14,7 @@ export class ModalState implements IModalState {
private changeListeners: Set<() => void> = new Set(); private changeListeners: Set<() => void> = new Set();
private static readonly STORAGE_KEY = 'typst-export-modal-state'; private static readonly STORAGE_KEY = 'typst-export-modal-state';
constructor(initialSettings: Partial<ExportConfigModalSettings>) { constructor(initialSettings: Partial<ExportConfigModalSettings>, private app: App) {
// Load from localStorage if available // Load from localStorage if available
const savedState = this.loadFromStorage(); const savedState = this.loadFromStorage();
@@ -174,7 +175,7 @@ export class ModalState implements IModalState {
} }
/** /**
* Save current state to localStorage * Save current state to vault-specific storage
*/ */
private saveToStorage(): void { private saveToStorage(): void {
const stateToSave = { const stateToSave = {
@@ -187,25 +188,25 @@ export class ModalState implements IModalState {
}, },
templateVariables: this.templateVariables templateVariables: this.templateVariables
}; };
try { try {
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave)); this.app.saveLocalStorage(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
} catch (error) { } catch (error) {
console.warn('Failed to save modal state to localStorage:', error); console.warn('Failed to save modal state to vault storage:', error);
} }
} }
/** /**
* Load state from localStorage * Load state from vault-specific storage
*/ */
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null { private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null {
try { try {
const saved = localStorage.getItem(ModalState.STORAGE_KEY); const saved = this.app.loadLocalStorage(ModalState.STORAGE_KEY);
if (saved) { if (saved) {
return JSON.parse(saved); return JSON.parse(saved);
} }
} catch (error) { } catch (error) {
console.warn('Failed to load modal state from localStorage:', error); console.warn('Failed to load modal state from vault storage:', error);
} }
return null; return null;
} }
+54
View File
@@ -0,0 +1,54 @@
/**
* Version Utilities
*
* Lightweight utilities for comparing semantic version strings.
* Used for minimum version validation of external dependencies.
*/
/**
* Compares two semantic version strings.
*
* @param version1 - First version string (e.g., "0.13.0")
* @param version2 - Second version string (e.g., "0.5.0")
* @returns Negative if version1 < version2, 0 if equal, positive if version1 > version2
*
* @example
* ```typescript
* compareVersions("0.13.0", "0.5.0") // Returns 8 (0.13.0 > 0.5.0)
* compareVersions("1.0.0", "1.0.0") // Returns 0 (equal)
* ```
*/
export function compareVersions(version1: string, version2: string): number {
// Extract numeric parts, ignoring pre-release tags and build metadata
const v1Parts = version1.split(/[-+]/)[0].split('.').map(Number);
const v2Parts = version2.split(/[-+]/)[0].split('.').map(Number);
const maxLength = Math.max(v1Parts.length, v2Parts.length);
for (let i = 0; i < maxLength; i++) {
const v1 = v1Parts[i] || 0;
const v2 = v2Parts[i] || 0;
if (v1 !== v2) {
return v1 - v2;
}
}
return 0;
}
/**
* Checks if a version meets a minimum required version.
*
* @param actualVersion - The detected version string
* @param minimumVersion - The minimum required version string
* @returns True if actualVersion >= minimumVersion
*
* @example
* ```typescript
* isVersionAtLeast("0.13.0", "0.13.0") // Returns true
* isVersionAtLeast("0.12.0", "0.13.0") // Returns false
* ```
*/
export function isVersionAtLeast(actualVersion: string, minimumVersion: string): boolean {
return compareVersions(actualVersion, minimumVersion) >= 0;
}
+220
View File
@@ -134,3 +134,223 @@
.export-form-hidden { .export-form-hidden {
display: none !important; display: none !important;
} }
/* Export config modal styles */
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 16px 24px 8px 24px;
border-bottom: 1px solid var(--background-modifier-border);
flex-shrink: 0;
}
.export-config-header h2 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.export-note-title {
margin: 0;
font-size: 14px;
color: var(--text-muted);
opacity: 0.8;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
}
.export-config-section {
margin-bottom: 24px;
}
.export-config-section:last-child {
margin-bottom: 0;
}
.export-config-section-title {
font-weight: 600;
margin-bottom: 12px;
padding-bottom: 4px;
border-bottom: 1px solid var(--background-modifier-border-hover);
}
.export-config-buttons {
padding: 16px 24px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 8px;
}
/* Progress styles */
.export-progress-container {
padding: 24px;
text-align: center;
}
.export-progress-container.export-hidden {
display: none;
}
.export-progress-container.export-progress-visible {
display: block;
}
.export-progress-text {
margin-bottom: 16px;
font-size: 14px;
color: var(--text-muted);
}
.export-progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--background-modifier-border);
border-radius: 4px;
margin-bottom: 8px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background-color: var(--interactive-accent);
border-radius: 4px;
width: var(--progress-width, 0%);
transition: width 0.3s ease;
}
.export-progress-percent {
font-size: 12px;
color: var(--text-muted);
}
/* Form field styles */
.export-setting-item {
margin-bottom: 16px;
}
.export-setting-item-info {
margin-bottom: 6px;
}
.export-setting-item-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-setting-item-description {
font-size: 12px;
color: var(--text-muted);
}
.export-setting-item-control {
display: flex;
align-items: center;
}
.export-setting-item-control input,
.export-setting-item-control select {
flex: 1;
}
/* Folder suggest styles */
.export-folder-suggest-container {
position: relative;
}
.export-folder-suggest-input {
width: 100%;
padding: 6px 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 4px;
background: var(--background-primary);
color: var(--text-normal);
}
.export-folder-suggest-input:focus {
border-color: var(--interactive-accent);
outline: none;
}
/* Validation styles */
.validation-errors, .validation-warnings {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.validation-warnings {
background: var(--background-modifier-warning);
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.warning-title {
color: var(--text-warning);
margin: 0 0 10px 0;
}
.validation-errors ul, .validation-warnings ul {
margin: 0;
padding-left: 20px;
}
.export-validation-error {
color: var(--text-error);
font-size: 12px;
margin-top: 4px;
}
.export-validation-warning {
color: var(--text-warning);
font-size: 12px;
margin-top: 4px;
}
/* Template variable styles */
.export-template-variables {
margin-top: 12px;
}
.export-template-variable {
margin-bottom: 8px;
padding: 8px;
background: var(--background-secondary);
border-radius: 4px;
font-size: 12px;
}
.export-template-variable-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-template-variable-description {
color: var(--text-muted);
font-style: italic;
}
+309
View File
@@ -0,0 +1,309 @@
import { describe, it, expect } from 'vitest';
import { ModalSettingsHelper } from '../src/core/ModalSettingsHelper';
import { obsidianTypstPDFExportSettings, ExportFormat } from '../src/core/settings';
import { TFile } from 'obsidian';
// Mock TFile
const createMockFile = (path: string, basename: string): TFile => ({
path,
basename,
extension: 'md',
} as TFile);
// Create mock settings
const createMockSettings = (overrides?: Partial<obsidianTypstPDFExportSettings>): obsidianTypstPDFExportSettings => ({
pandocPath: '/usr/bin/pandoc',
typstPath: '/usr/bin/typst',
outputFolder: 'exports',
executablePaths: {
imagemagickPath: '',
additionalPaths: [],
},
customEnvironmentVariables: {},
exportDefaults: {
template: 'default',
format: ExportFormat.Standard,
pageSize: 'a4',
orientation: 'portrait',
marginTop: '2.5cm',
marginBottom: '2.5cm',
marginLeft: '2.5cm',
marginRight: '2.5cm',
bodyFont: 'Georgia',
headingFont: 'Helvetica',
monospaceFont: 'Courier New',
bodyFontSize: '11pt',
},
typography: {
fonts: {
body: 'Georgia',
heading: 'Helvetica',
monospace: 'Courier New',
},
fontSizes: {
body: 11,
heading: 16,
small: 9,
},
},
pageSetup: {
size: 'a4',
orientation: 'portrait',
margins: {
top: 71,
right: 71,
bottom: 71,
left: 71,
},
},
behavior: {
openAfterExport: true,
preserveFolderStructure: false,
exportConcurrency: 3,
debugMode: false,
embedPdfFiles: false,
embedAllFiles: false,
printFrontmatter: false,
},
...overrides,
});
describe('ModalSettingsHelper', () => {
describe('prepareModalSettings', () => {
it('should prepare settings for single file', () => {
const file = createMockFile('notes/test.md', 'test');
const templates = ['default', 'modern'];
const settings = createMockSettings();
const result = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: templates,
settings,
});
expect(result.notePath).toBe('notes/test.md');
expect(result.noteTitle).toBe('test');
expect(result.files).toBeUndefined();
expect(result.template).toBe('default');
expect(result.format).toBe(ExportFormat.Standard);
expect(result.outputFolder).toBe('exports');
expect(result.availableTemplates).toEqual(templates);
});
it('should prepare settings for multi-file export', () => {
const file1 = createMockFile('notes/test1.md', 'test1');
const file2 = createMockFile('notes/test2.md', 'test2');
const file3 = createMockFile('notes/test3.md', 'test3');
const templates = ['default'];
const settings = createMockSettings();
const result = ModalSettingsHelper.prepareModalSettings({
file: file1,
additionalFiles: [file2, file3],
availableTemplates: templates,
settings,
});
expect(result.noteTitle).toBe('3 files');
expect(result.files).toHaveLength(3);
expect(result.files).toContain(file1);
expect(result.files).toContain(file2);
expect(result.files).toContain(file3);
});
it('should include template variables from settings', () => {
const file = createMockFile('notes/test.md', 'test');
const settings = createMockSettings();
const result = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: ['default'],
settings,
});
expect(result.templateVariables).toBeDefined();
expect(result.templateVariables?.pageSize).toBe('a4');
expect(result.templateVariables?.orientation).toBe('portrait');
expect(result.templateVariables?.flipped).toBe(false);
expect(result.templateVariables?.marginTop).toBe('71');
expect(result.templateVariables?.bodyFont).toBe('Georgia');
expect(result.templateVariables?.headingFont).toBe('Helvetica');
expect(result.templateVariables?.monospaceFont).toBe('Courier New');
expect(result.templateVariables?.bodyFontSize).toBe(11);
});
it('should set flipped to true for landscape orientation', () => {
const file = createMockFile('notes/test.md', 'test');
const settings = createMockSettings({
pageSetup: {
size: 'a4',
orientation: 'landscape',
margins: { top: 71, right: 71, bottom: 71, left: 71 },
},
});
const result = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: ['default'],
settings,
});
expect(result.templateVariables?.orientation).toBe('landscape');
expect(result.templateVariables?.flipped).toBe(true);
});
it('should add width:auto for landscape single-page format', () => {
const file = createMockFile('notes/test.md', 'test');
const settings = createMockSettings({
pageSetup: {
size: 'a4',
orientation: 'landscape',
margins: { top: 71, right: 71, bottom: 71, left: 71 },
},
exportDefaults: {
template: 'default',
format: ExportFormat.SinglePage,
pageSize: 'a4',
orientation: 'landscape',
marginTop: '2.5cm',
marginBottom: '2.5cm',
marginLeft: '2.5cm',
marginRight: '2.5cm',
bodyFont: 'Georgia',
headingFont: 'Helvetica',
monospaceFont: 'Courier New',
bodyFontSize: '11pt',
},
});
const result = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: ['default'],
settings,
});
expect(result.templateVariables?.width).toBe('auto');
});
it('should not add width:auto for portrait or standard format', () => {
const file = createMockFile('notes/test.md', 'test');
// Test portrait orientation
const settingsPortrait = createMockSettings();
const resultPortrait = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: ['default'],
settings: settingsPortrait,
});
expect(resultPortrait.templateVariables?.width).toBeUndefined();
// Test landscape with standard format
const settingsLandscapeStandard = createMockSettings({
pageSetup: {
size: 'a4',
orientation: 'landscape',
margins: { top: 71, right: 71, bottom: 71, left: 71 },
},
exportDefaults: {
template: 'default',
format: ExportFormat.Standard,
pageSize: 'a4',
orientation: 'landscape',
marginTop: '2.5cm',
marginBottom: '2.5cm',
marginLeft: '2.5cm',
marginRight: '2.5cm',
bodyFont: 'Georgia',
headingFont: 'Helvetica',
monospaceFont: 'Courier New',
bodyFontSize: '11pt',
},
});
const resultLandscapeStandard = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: ['default'],
settings: settingsLandscapeStandard,
});
expect(resultLandscapeStandard.templateVariables?.width).toBeUndefined();
});
it('should use settings behavior options', () => {
const file = createMockFile('notes/test.md', 'test');
const settings = createMockSettings({
behavior: {
openAfterExport: false,
preserveFolderStructure: true,
exportConcurrency: 3,
debugMode: false,
embedPdfFiles: false,
embedAllFiles: false,
printFrontmatter: false,
},
});
const result = ModalSettingsHelper.prepareModalSettings({
file,
availableTemplates: ['default'],
settings,
});
expect(result.openAfterExport).toBe(false);
expect(result.preserveFolderStructure).toBe(true);
});
});
describe('prepareForSingleFile', () => {
it('should be a convenience wrapper for single file', () => {
const file = createMockFile('notes/test.md', 'test');
const templates = ['default', 'modern'];
const settings = createMockSettings();
const result = ModalSettingsHelper.prepareForSingleFile(
file,
templates,
settings
);
expect(result.notePath).toBe('notes/test.md');
expect(result.noteTitle).toBe('test');
expect(result.files).toBeUndefined();
expect(result.availableTemplates).toEqual(templates);
});
});
describe('prepareForMultiFile', () => {
it('should be a convenience wrapper for multiple files', () => {
const files = [
createMockFile('notes/test1.md', 'test1'),
createMockFile('notes/test2.md', 'test2'),
];
const templates = ['default'];
const settings = createMockSettings();
const result = ModalSettingsHelper.prepareForMultiFile(
files,
templates,
settings
);
expect(result.noteTitle).toBe('2 files');
expect(result.files).toEqual(files);
expect(result.notePath).toBe('notes/test1.md');
});
it('should handle single file array', () => {
const files = [createMockFile('notes/test.md', 'test')];
const settings = createMockSettings();
const result = ModalSettingsHelper.prepareForMultiFile(
files,
['default'],
settings
);
// Single file should still show as single file
expect(result.noteTitle).toBe('test');
expect(result.files).toBeUndefined();
});
});
});
+216
View File
@@ -0,0 +1,216 @@
import { describe, it, expect } from 'vitest';
import { SecurityUtils } from '../src/core/SecurityUtils';
describe('SecurityUtils', () => {
describe('validateOutputPath', () => {
it('should accept valid relative paths', () => {
expect(SecurityUtils.validateOutputPath('exports')).toBe(true);
expect(SecurityUtils.validateOutputPath('my-exports')).toBe(true);
expect(SecurityUtils.validateOutputPath('exports/pdfs')).toBe(true);
expect(SecurityUtils.validateOutputPath('folder_name')).toBe(true);
});
it('should reject empty or invalid input', () => {
expect(SecurityUtils.validateOutputPath('')).toBe(false);
expect(SecurityUtils.validateOutputPath(null as any)).toBe(false);
expect(SecurityUtils.validateOutputPath(undefined as any)).toBe(false);
expect(SecurityUtils.validateOutputPath(123 as any)).toBe(false);
});
it('should reject path traversal attempts', () => {
expect(SecurityUtils.validateOutputPath('..')).toBe(false);
expect(SecurityUtils.validateOutputPath('../')).toBe(false);
expect(SecurityUtils.validateOutputPath('../../secret')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports/../../../etc')).toBe(false);
});
it('should reject absolute paths', () => {
expect(SecurityUtils.validateOutputPath('/etc/passwd')).toBe(false);
expect(SecurityUtils.validateOutputPath('/usr/local')).toBe(false);
expect(SecurityUtils.validateOutputPath('\\Windows\\System32')).toBe(false);
expect(SecurityUtils.validateOutputPath('\\etc\\hosts')).toBe(false);
});
it('should reject null bytes', () => {
expect(SecurityUtils.validateOutputPath('exports\x00malicious')).toBe(false);
expect(SecurityUtils.validateOutputPath('\x00')).toBe(false);
});
it('should reject double slashes', () => {
// Note: path.normalize() resolves double slashes in the middle, so we test edge cases
// that remain problematic even after normalization
expect(SecurityUtils.validateOutputPath('//exports')).toBe(false); // Starts with //
});
it('should reject invalid filename characters', () => {
expect(SecurityUtils.validateOutputPath('exports<test')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports>test')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports:test')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports"test')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports|test')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports?test')).toBe(false);
expect(SecurityUtils.validateOutputPath('exports*test')).toBe(false);
});
it('should reject Windows reserved names', () => {
expect(SecurityUtils.validateOutputPath('CON')).toBe(false);
expect(SecurityUtils.validateOutputPath('PRN')).toBe(false);
expect(SecurityUtils.validateOutputPath('AUX')).toBe(false);
expect(SecurityUtils.validateOutputPath('NUL')).toBe(false);
expect(SecurityUtils.validateOutputPath('COM1')).toBe(false);
expect(SecurityUtils.validateOutputPath('COM9')).toBe(false);
expect(SecurityUtils.validateOutputPath('LPT1')).toBe(false);
expect(SecurityUtils.validateOutputPath('lpt9')).toBe(false); // Case insensitive
});
it('should handle whitespace correctly', () => {
expect(SecurityUtils.validateOutputPath(' exports ')).toBe(true);
expect(SecurityUtils.validateOutputPath(' .. ')).toBe(false);
});
});
describe('validateExecutablePath', () => {
it('should accept empty paths (system PATH)', () => {
expect(SecurityUtils.validateExecutablePath('')).toBe(true);
expect(SecurityUtils.validateExecutablePath(' ')).toBe(true);
});
it('should accept valid executable paths', () => {
expect(SecurityUtils.validateExecutablePath('/usr/bin/pandoc')).toBe(true);
expect(SecurityUtils.validateExecutablePath('/opt/typst/typst')).toBe(true);
expect(SecurityUtils.validateExecutablePath('C:\\Program Files\\Pandoc\\pandoc.exe')).toBe(true);
expect(SecurityUtils.validateExecutablePath('pandoc')).toBe(true);
});
it('should reject shell metacharacters', () => {
expect(SecurityUtils.validateExecutablePath('pandoc;rm -rf /')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc&whoami')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc|cat /etc/passwd')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc`whoami`')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc$(whoami)')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc{}')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc[]')).toBe(false);
});
it('should reject null bytes', () => {
expect(SecurityUtils.validateExecutablePath('pandoc\x00malicious')).toBe(false);
expect(SecurityUtils.validateExecutablePath('\x00')).toBe(false);
});
it('should reject newlines', () => {
expect(SecurityUtils.validateExecutablePath('pandoc\nrm -rf /')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc\r\nmalicious')).toBe(false);
});
it('should reject command separators with whitespace', () => {
expect(SecurityUtils.validateExecutablePath('pandoc ; whoami')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc & whoami')).toBe(false);
expect(SecurityUtils.validateExecutablePath('pandoc | whoami')).toBe(false);
});
it('should reject variable and command substitution', () => {
expect(SecurityUtils.validateExecutablePath('${MALICIOUS}')).toBe(false);
expect(SecurityUtils.validateExecutablePath('`whoami`')).toBe(false);
expect(SecurityUtils.validateExecutablePath('$(malicious)')).toBe(false);
});
it('should handle whitespace in paths', () => {
expect(SecurityUtils.validateExecutablePath(' /usr/bin/pandoc ')).toBe(true);
});
});
describe('getPathValidationError', () => {
it('should return appropriate error for empty path', () => {
expect(SecurityUtils.getPathValidationError('')).toBe('Output folder is required');
expect(SecurityUtils.getPathValidationError(null as any)).toBe('Output folder is required');
expect(SecurityUtils.getPathValidationError(undefined as any)).toBe('Output folder is required');
});
it('should return appropriate error for path traversal', () => {
const error = SecurityUtils.getPathValidationError('..');
expect(error).toBe('Path traversal attempts (..) are not allowed');
});
it('should return appropriate error for absolute paths', () => {
const error = SecurityUtils.getPathValidationError('/etc/passwd');
expect(error).toBe('Absolute paths are not allowed - use relative paths from vault root');
});
it('should return appropriate error for null bytes', () => {
const error = SecurityUtils.getPathValidationError('exports\x00');
expect(error).toBe('Null bytes are not allowed in paths');
});
it('should return appropriate error for double slashes', () => {
// Test with leading // which should fail the absolute path check
const error = SecurityUtils.getPathValidationError('//exports');
expect(error).toBe('Absolute paths are not allowed - use relative paths from vault root');
});
it('should return appropriate error for invalid characters', () => {
const error = SecurityUtils.getPathValidationError('exports<test');
expect(error).toBe('Invalid characters found in path');
});
it('should return appropriate error for reserved names', () => {
const error = SecurityUtils.getPathValidationError('CON');
expect(error).toBe('Reserved system names are not allowed in paths (found: CON)');
});
it('should return generic error for unknown issues', () => {
// For a valid path, it would still return 'Invalid path format' if called
// (though normally you wouldn't call this for valid paths)
const validPath = 'exports';
// This is a bit contrived since we wouldn't normally call this on valid paths
// but it tests the fallback case
expect(SecurityUtils.getPathValidationError(validPath)).toBe('Invalid path format');
});
});
describe('getExecutablePathValidationError', () => {
it('should return appropriate error for empty path', () => {
expect(SecurityUtils.getExecutablePathValidationError(null as any))
.toBe('Executable path is required');
});
it('should return appropriate error for shell metacharacters', () => {
const error = SecurityUtils.getExecutablePathValidationError('pandoc;whoami');
expect(error).toBe('Shell metacharacters are not allowed in executable paths');
});
it('should return appropriate error for null bytes', () => {
const error = SecurityUtils.getExecutablePathValidationError('pandoc\x00');
expect(error).toBe('Null bytes are not allowed in paths');
});
it('should return appropriate error for newlines', () => {
const error = SecurityUtils.getExecutablePathValidationError('pandoc\nrm');
expect(error).toBe('Newlines are not allowed in paths');
});
it('should return appropriate error for command separators', () => {
// The semicolon is caught by shell metacharacters check first
const error = SecurityUtils.getExecutablePathValidationError('pandoc ; whoami');
expect(error).toBe('Shell metacharacters are not allowed in executable paths');
});
it('should return appropriate error for substitution patterns', () => {
// These contain shell metacharacters, which are checked first
const error = SecurityUtils.getExecutablePathValidationError('${VAR}');
expect(error).toBe('Shell metacharacters are not allowed in executable paths');
const error2 = SecurityUtils.getExecutablePathValidationError('`cmd`');
expect(error2).toBe('Shell metacharacters are not allowed in executable paths');
const error3 = SecurityUtils.getExecutablePathValidationError('$(cmd)');
expect(error3).toBe('Shell metacharacters are not allowed in executable paths');
});
it('should return generic error for valid paths when forced', () => {
const validPath = '/usr/bin/pandoc';
// Again, contrived - but tests the fallback
expect(SecurityUtils.getExecutablePathValidationError(validPath))
.toBe('Invalid executable path format');
});
});
});
+387
View File
@@ -0,0 +1,387 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { TempDirectoryManager } from '../src/core/TempDirectoryManager';
import type { App } from 'obsidian';
// Create mock functions that will be used in vi.mock - using vi.hoisted to ensure they're available
const { mockFsAccess, mockFsMkdir, mockFsReaddir, mockFsStat, mockFsUnlink } = vi.hoisted(() => ({
mockFsAccess: vi.fn(),
mockFsMkdir: vi.fn(),
mockFsReaddir: vi.fn(),
mockFsStat: vi.fn(),
mockFsUnlink: vi.fn(),
}));
// Mock the fs module
vi.mock('fs', () => ({
default: {},
promises: {
access: mockFsAccess,
mkdir: mockFsMkdir,
readdir: mockFsReaddir,
stat: mockFsStat,
unlink: mockFsUnlink,
},
}));
describe('TempDirectoryManager', () => {
let mockApp: App;
let mockVaultAdapter: any;
beforeEach(() => {
// Reset all mocks before each test
vi.clearAllMocks();
// Reset mocks before each test
mockVaultAdapter = {
exists: vi.fn(),
mkdir: vi.fn(),
remove: vi.fn(),
list: vi.fn(),
};
mockApp = {
vault: {
adapter: mockVaultAdapter,
},
} as any;
});
describe('constructor and static create', () => {
it('should create an instance with provided options', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'test-plugin',
app: mockApp,
});
expect(manager).toBeInstanceOf(TempDirectoryManager);
});
it('should use default plugin name if not provided', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
app: mockApp,
});
const tempDir = manager.getTempDir('images');
expect(tempDir).toContain('typst-pdf-export');
});
it('should create instance via static create method', () => {
const manager = TempDirectoryManager.create(
'/vault',
'.obsidian',
'test-plugin',
mockApp
);
expect(manager).toBeInstanceOf(TempDirectoryManager);
});
});
describe('getTempDir', () => {
it('should return correct path for images temp directory', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempDir = manager.getTempDir('images');
expect(tempDir).toContain('temp-images');
expect(tempDir).toContain('.obsidian');
expect(tempDir).toContain('plugins');
});
it('should return correct path for pandoc temp directory', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempDir = manager.getTempDir('pandoc');
expect(tempDir).toContain('temp-pandoc');
expect(tempDir).toContain('.obsidian');
expect(tempDir).toContain('plugins');
});
it('should normalize paths correctly', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempDir = manager.getTempDir('images');
// Should use forward slashes after normalization
expect(tempDir).not.toContain('\\');
});
it('should handle absolute vault paths on Windows', () => {
const manager = new TempDirectoryManager({
vaultPath: 'C:/Users/Test/Vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempDir = manager.getTempDir('images');
expect(tempDir).toContain('C:/Users/Test/Vault');
});
});
describe('ensureTempDir', () => {
it('should create directory if it does not exist', async () => {
// fs.access rejects when directory doesn't exist
mockFsAccess.mockRejectedValue(new Error('ENOENT'));
mockFsMkdir.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.ensureTempDir('images');
expect(mockFsAccess).toHaveBeenCalledOnce();
expect(mockFsMkdir).toHaveBeenCalledOnce();
expect(result).toContain('temp-images');
});
it('should not create directory if it already exists', async () => {
// fs.access resolves when directory exists
mockFsAccess.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.ensureTempDir('images');
expect(mockFsAccess).toHaveBeenCalledOnce();
expect(mockFsMkdir).not.toHaveBeenCalled();
expect(result).toContain('temp-images');
});
it('should handle both images and pandoc directories', async () => {
mockFsAccess.mockRejectedValue(new Error('ENOENT'));
mockFsMkdir.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const imagesDir = await manager.ensureTempDir('images');
const pandocDir = await manager.ensureTempDir('pandoc');
expect(imagesDir).toContain('temp-images');
expect(pandocDir).toContain('temp-pandoc');
expect(mockFsMkdir).toHaveBeenCalledTimes(2);
});
});
describe('cleanupTempDir', () => {
it('should remove all files from temp directory', async () => {
mockFsAccess.mockResolvedValue(undefined);
mockFsReaddir.mockResolvedValue(['file1.png', 'file2.png', 'file3.typ']);
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
mockFsUnlink.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.cleanupTempDir('images');
expect(result).toBe(true);
expect(mockFsUnlink).toHaveBeenCalledTimes(3);
});
it('should return true if directory does not exist', async () => {
mockFsAccess.mockRejectedValue(new Error('ENOENT'));
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.cleanupTempDir('images');
expect(result).toBe(true);
expect(mockFsUnlink).not.toHaveBeenCalled();
});
it('should return false and log warning on error', async () => {
mockFsAccess.mockResolvedValue(undefined);
mockFsReaddir.mockRejectedValue(new Error('Access denied'));
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.cleanupTempDir('images');
expect(result).toBe(false);
expect(consoleWarnSpy).toHaveBeenCalled();
consoleWarnSpy.mockRestore();
});
it('should handle errors during file removal', async () => {
mockFsAccess.mockResolvedValue(undefined);
mockFsReaddir.mockResolvedValue(['file1.png']);
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
mockFsUnlink.mockRejectedValue(new Error('Cannot delete'));
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.cleanupTempDir('images');
expect(result).toBe(false);
expect(consoleWarnSpy).toHaveBeenCalled();
consoleWarnSpy.mockRestore();
});
});
describe('cleanupAllTempDirs', () => {
it('should clean up both temp directories', async () => {
mockFsAccess.mockResolvedValue(undefined);
mockFsReaddir.mockResolvedValue(['file1.png']);
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
mockFsUnlink.mockResolvedValue(undefined);
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.cleanupAllTempDirs();
expect(result).toEqual({ images: true, pandoc: true });
expect(mockFsReaddir).toHaveBeenCalledTimes(2);
});
it('should return status for each directory independently', async () => {
let callCount = 0;
mockFsAccess.mockImplementation(() => {
callCount++;
// First call (images) succeeds, second call (pandoc) fails
if (callCount === 1) return Promise.resolve(undefined);
return Promise.reject(new Error('Access denied'));
});
mockFsReaddir.mockResolvedValue(['file1.png']);
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
mockFsUnlink.mockResolvedValue(undefined);
vi.spyOn(console, 'warn').mockImplementation(() => {});
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const result = await manager.cleanupAllTempDirs();
expect(result.images).toBe(true);
expect(result.pandoc).toBe(false);
});
});
describe('isPluginTempDir', () => {
it('should return true for images temp directory', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempImagesDir = manager.getTempDir('images');
expect(manager.isPluginTempDir(tempImagesDir)).toBe(true);
});
it('should return true for pandoc temp directory', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempPandocDir = manager.getTempDir('pandoc');
expect(manager.isPluginTempDir(tempPandocDir)).toBe(true);
});
it('should return true for subdirectories within temp directories', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempImagesDir = manager.getTempDir('images');
const subDir = `${tempImagesDir}/subfolder`;
expect(manager.isPluginTempDir(subDir)).toBe(true);
});
it('should return false for non-temp directories', () => {
const manager = new TempDirectoryManager({
vaultPath: '/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
expect(manager.isPluginTempDir('/vault/some-other-folder')).toBe(false);
expect(manager.isPluginTempDir('/vault/.obsidian/plugins/other-plugin')).toBe(false);
});
it('should handle paths with different separators', () => {
const manager = new TempDirectoryManager({
vaultPath: 'C:/vault',
configDir: '.obsidian',
pluginName: 'typst-pdf-export',
app: mockApp,
});
const tempImagesDir = manager.getTempDir('images');
// Test with backslashes (should be normalized)
const windowsStylePath = tempImagesDir.replace(/\//g, '\\');
expect(manager.isPluginTempDir(windowsStylePath)).toBe(true);
});
});
});
+233
View File
@@ -0,0 +1,233 @@
import { describe, it, expect, vi } from 'vitest';
import { TypstVariableMapper } from '../src/converters/pandoc/TypstVariableMapper';
import { PandocOptions } from '../src/converters/converterTypes';
import { ExportFormat, obsidianTypstPDFExportSettings } from '../src/core/settings';
const createMockPlugin = (settings: Partial<obsidianTypstPDFExportSettings> = {}) => ({
settings: {
pandocPath: '/usr/bin/pandoc',
typstPath: '/usr/bin/typst',
outputFolder: 'exports',
executablePaths: { imagemagickPath: '', additionalPaths: [] },
customEnvironmentVariables: {},
exportDefaults: {
template: 'default',
format: ExportFormat.Standard,
pageSize: 'a4',
orientation: 'portrait' as const,
marginTop: '2.5cm',
marginBottom: '2.5cm',
marginLeft: '2.5cm',
marginRight: '2.5cm',
bodyFont: 'Georgia',
headingFont: 'Helvetica',
monospaceFont: 'Courier',
bodyFontSize: '11pt',
},
typography: {
fonts: { body: 'Georgia', heading: 'Helvetica', monospace: 'Courier' },
fontSizes: { body: 11, heading: 16, small: 9 },
},
pageSetup: {
size: 'a4',
orientation: 'portrait' as const,
margins: { top: 71, right: 71, bottom: 71, left: 71 },
},
behavior: {
openAfterExport: true,
preserveFolderStructure: false,
exportConcurrency: 3,
debugMode: false,
embedPdfFiles: false,
embedAllFiles: false,
printFrontmatter: false,
},
...settings,
},
} as any);
describe('TypstVariableMapper', () => {
describe('transformExportConfigVariable', () => {
it('should map bodyFont to font', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: { bodyFont: 'Arial' },
};
const vars = mapper.mapAllVariablesToTypst(options);
const fontVar = vars.find(v => v.name === 'font');
expect(fontVar).toBeDefined();
expect(fontVar?.value).toBe('Arial');
});
it('should map headingFont to heading_font', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: { headingFont: 'Helvetica' },
};
const vars = mapper.mapAllVariablesToTypst(options);
const headingVar = vars.find(v => v.name === 'heading_font');
expect(headingVar).toBeDefined();
expect(headingVar?.value).toBe('Helvetica');
});
it('should map bodyFontSize to fontsize with pt unit', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: { bodyFontSize: 12 },
};
const vars = mapper.mapAllVariablesToTypst(options);
const sizeVar = vars.find(v => v.name === 'fontsize');
expect(sizeVar).toBeDefined();
expect(sizeVar?.value).toBe('12pt');
});
it('should map pageSize to paper with Typst value', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: { pageSize: 'a4' },
};
const vars = mapper.mapAllVariablesToTypst(options);
const paperVar = vars.find(v => v.name === 'paper');
expect(paperVar).toBeDefined();
expect(paperVar?.value).toBe('a4');
});
it('should map margin variables with cm unit', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: {
marginTop: 2,
marginBottom: 3,
marginLeft: 2.5,
marginRight: 2.5,
},
};
const vars = mapper.mapAllVariablesToTypst(options);
expect(vars.find(v => v.name === 'margin_top')?.value).toBe('2cm');
expect(vars.find(v => v.name === 'margin_bottom')?.value).toBe('3cm');
expect(vars.find(v => v.name === 'margin_left')?.value).toBe('2.5cm');
expect(vars.find(v => v.name === 'margin_right')?.value).toBe('2.5cm');
});
it('should preserve unmapped variables', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: {
orientation: 'landscape',
flipped: true,
customVar: 'value',
},
};
const vars = mapper.mapAllVariablesToTypst(options);
expect(vars.find(v => v.name === 'orientation')?.value).toBe('landscape');
expect(vars.find(v => v.name === 'flipped')?.value).toBe('true');
expect(vars.find(v => v.name === 'customVar')?.value).toBe('value');
});
});
describe('mapPluginSettingsVariables', () => {
it('should add typography variables from settings', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = { variables: {} };
const vars = mapper.mapAllVariablesToTypst(options);
expect(vars.find(v => v.name === 'font')?.value).toBe('Georgia');
expect(vars.find(v => v.name === 'heading_font')?.value).toBe('Helvetica');
expect(vars.find(v => v.name === 'fontsize')?.value).toBe('11pt');
});
it('should not override export config variables', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: { bodyFont: 'Arial' },
};
const vars = mapper.mapAllVariablesToTypst(options);
const fontVars = vars.filter(v => v.name === 'font');
// Should only have one font variable from export config
expect(fontVars).toHaveLength(1);
expect(fontVars[0].value).toBe('Arial');
});
it('should add page setup variables from settings', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = { variables: {} };
const vars = mapper.mapAllVariablesToTypst(options);
expect(vars.find(v => v.name === 'paper')?.value).toBe('a4');
expect(vars.find(v => v.name === 'orientation')?.value).toBe('portrait');
});
});
describe('convertVariablesToPandocArgs', () => {
it('should convert variables to pandoc -V arguments', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const variables = [
{ name: 'font', value: 'Arial' },
{ name: 'fontsize', value: '12pt' },
{ name: 'paper', value: 'a4' },
];
const args = mapper.convertVariablesToPandocArgs(variables);
expect(args).toEqual([
'-V', 'font=Arial',
'-V', 'fontsize=12pt',
'-V', 'paper=a4',
]);
});
it('should handle empty variables array', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const args = mapper.convertVariablesToPandocArgs([]);
expect(args).toEqual([]);
});
});
describe('getExportConfigVariableNames', () => {
it('should return set of variable names including mappings', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = {
variables: {
bodyFont: 'Arial',
pageSize: 'a4',
marginTop: 2,
},
};
const names = mapper.getExportConfigVariableNames(options);
expect(names.has('bodyFont')).toBe(true);
expect(names.has('font')).toBe(true);
expect(names.has('pageSize')).toBe(true);
expect(names.has('paper')).toBe(true);
expect(names.has('marginTop')).toBe(true);
expect(names.has('margin_top')).toBe(true);
});
it('should handle empty variables', () => {
const mapper = new TypstVariableMapper(createMockPlugin());
const options: PandocOptions = { variables: {} };
const names = mapper.getExportConfigVariableNames(options);
expect(names.size).toBe(0);
});
});
});
+65
View File
@@ -0,0 +1,65 @@
// Mock Obsidian API for testing
import { vi } from 'vitest';
export class Notice {
constructor(message: string) {}
}
export class Plugin {
app: any;
manifest: any;
}
export class PluginSettingTab {
constructor(app: any, plugin: any) {}
}
export class Setting {
constructor(containerEl: HTMLElement) {}
setName(name: string): this { return this; }
setDesc(desc: string): this { return this; }
addText(cb: any): this { return this; }
addToggle(cb: any): this { return this; }
addDropdown(cb: any): this { return this; }
}
export class Modal {
constructor(app: any) {}
open(): void {}
close(): void {}
}
export class FuzzySuggestModal {
constructor(app: any) {}
}
export class TFile {
path = '';
basename = '';
extension = '';
}
export class TFolder {
path = '';
name = '';
}
export function normalizePath(path: string): string {
return path.replace(/\\/g, '/');
}
export const requestUrl = vi.fn();
// Type exports for compatibility
export interface App {
vault: {
adapter: {
exists: (path: string) => Promise<boolean>;
mkdir: (path: string) => Promise<void>;
remove: (path: string) => Promise<void>;
list: (path: string) => Promise<{ files: string[]; folders: string[] }>;
read: (path: string) => Promise<string>;
write: (path: string, data: string) => Promise<void>;
};
};
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Basic coverage tests for simpler modules
* These tests ensure basic functionality and increase overall coverage
*/
import { describe, it, expect } from 'vitest';
// Import type files and constants
import { FALLBACK_FONTS, PLUGIN_DIRS, EXPORT_CONSTANTS, DEPENDENCY_CONSTANTS } from '../src/core/constants';
import { ExportFormat } from '../src/core/settings';
// Import utilities
import { SUPPORTED_PAPER_SIZES, DEFAULT_PAPER_SIZE, mapToTypstPaperSize, isSupportedPaperSize } from '../src/utils/paperSizeMapper';
describe('Constants and Types Coverage', () => {
describe('FALLBACK_FONTS', () => {
it('should have defined fallback fonts', () => {
expect(FALLBACK_FONTS.length).toBeGreaterThan(0);
expect(FALLBACK_FONTS).toContain('Times New Roman');
});
});
describe('PLUGIN_DIRS', () => {
it('should have temp directory names', () => {
expect(PLUGIN_DIRS.TEMP_IMAGES).toBe('temp-images');
expect(PLUGIN_DIRS.TEMP_PANDOC).toBe('temp-pandoc');
});
});
describe('EXPORT_CONSTANTS', () => {
it('should have timeout constants', () => {
expect(EXPORT_CONSTANTS.DEFAULT_TIMEOUT).toBe(120000);
expect(EXPORT_CONSTANTS.NOTICE_DURATION.SHORT).toBe(5000);
});
});
describe('DEPENDENCY_CONSTANTS', () => {
it('should have default executables', () => {
expect(DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc).toBe('pandoc');
expect(DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst).toBe('typst');
});
it('should have common paths', () => {
expect(DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE).toContain('/.local/bin');
expect(DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE).toContain('/usr/local/bin');
});
});
describe('ExportFormat enum', () => {
it('should have standard and single-page formats', () => {
expect(ExportFormat.Standard).toBe('standard');
expect(ExportFormat.SinglePage).toBe('single-page');
});
});
describe('Paper size utilities', () => {
it('should have multiple paper sizes', () => {
expect(SUPPORTED_PAPER_SIZES.length).toBeGreaterThan(5);
});
it('should map known sizes', () => {
expect(mapToTypstPaperSize('a4')).toBe('a4');
expect(mapToTypstPaperSize('us-letter')).toBe('us-letter');
});
it('should validate paper sizes', () => {
expect(isSupportedPaperSize('a4')).toBe(true);
expect(isSupportedPaperSize('invalid')).toBe(false);
});
it('should have a default paper size', () => {
expect(DEFAULT_PAPER_SIZE).toBe('a4');
});
});
});
+10
View File
@@ -0,0 +1,10 @@
import { describe, it, expect } from 'vitest';
import { ExportFormat } from '../src/core/settings';
// Type definition file - basic import test to ensure types compile
describe('converterTypes', () => {
it('should export ExportFormat enum', () => {
expect(ExportFormat.Standard).toBe('standard');
expect(ExportFormat.SinglePage).toBe('single-page');
});
});
+175
View File
@@ -0,0 +1,175 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
SUPPORTED_PAPER_SIZES,
DEFAULT_PAPER_SIZE,
mapToTypstPaperSize,
getValidTypstPaperSizes,
isSupportedPaperSize,
} from '../src/utils/paperSizeMapper';
describe('paperSizeMapper', () => {
describe('SUPPORTED_PAPER_SIZES', () => {
it('should have all required paper sizes', () => {
expect(SUPPORTED_PAPER_SIZES).toHaveLength(8);
const keys = SUPPORTED_PAPER_SIZES.map(size => size.key);
expect(keys).toContain('a3');
expect(keys).toContain('a4');
expect(keys).toContain('a5');
expect(keys).toContain('a6');
expect(keys).toContain('eu-business-card');
expect(keys).toContain('us-letter');
expect(keys).toContain('us-legal');
expect(keys).toContain('us-business-card');
});
it('should have correct structure for each paper size', () => {
SUPPORTED_PAPER_SIZES.forEach(size => {
expect(size).toHaveProperty('key');
expect(size).toHaveProperty('displayName');
expect(size).toHaveProperty('typstValue');
expect(typeof size.key).toBe('string');
expect(typeof size.displayName).toBe('string');
expect(typeof size.typstValue).toBe('string');
expect(size.key.length).toBeGreaterThan(0);
expect(size.displayName.length).toBeGreaterThan(0);
expect(size.typstValue.length).toBeGreaterThan(0);
});
});
it('should have unique keys', () => {
const keys = SUPPORTED_PAPER_SIZES.map(size => size.key);
const uniqueKeys = new Set(keys);
expect(uniqueKeys.size).toBe(keys.length);
});
it('should have display names with dimensions', () => {
SUPPORTED_PAPER_SIZES.forEach(size => {
// Display names should contain either 'mm' or 'in'
expect(size.displayName).toMatch(/\d+\s*×\s*\d+\s*(mm|in)/);
});
});
});
describe('DEFAULT_PAPER_SIZE', () => {
it('should be a4', () => {
expect(DEFAULT_PAPER_SIZE).toBe('a4');
});
it('should be a valid supported paper size', () => {
expect(isSupportedPaperSize(DEFAULT_PAPER_SIZE)).toBe(true);
});
});
describe('mapToTypstPaperSize', () => {
it('should map supported paper sizes correctly', () => {
expect(mapToTypstPaperSize('a3')).toBe('a3');
expect(mapToTypstPaperSize('a4')).toBe('a4');
expect(mapToTypstPaperSize('a5')).toBe('a5');
expect(mapToTypstPaperSize('a6')).toBe('a6');
expect(mapToTypstPaperSize('us-letter')).toBe('us-letter');
expect(mapToTypstPaperSize('us-legal')).toBe('us-legal');
expect(mapToTypstPaperSize('eu-business-card')).toBe('eu-business-card');
expect(mapToTypstPaperSize('us-business-card')).toBe('us-business-card');
});
it('should return default for unsupported paper sizes', () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(mapToTypstPaperSize('invalid-size')).toBe('a4');
expect(mapToTypstPaperSize('unknown')).toBe('a4');
expect(mapToTypstPaperSize('')).toBe('a4');
expect(consoleWarnSpy).toHaveBeenCalledTimes(3);
consoleWarnSpy.mockRestore();
});
it('should log warning for unsupported sizes', () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
mapToTypstPaperSize('invalid-size');
expect(consoleWarnSpy).toHaveBeenCalledWith(
expect.stringContaining('Unknown paper size: invalid-size')
);
expect(consoleWarnSpy).toHaveBeenCalledWith(
expect.stringContaining('Using default: a4')
);
consoleWarnSpy.mockRestore();
});
it('should handle case-sensitive keys', () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
// Keys are case-sensitive
expect(mapToTypstPaperSize('A4')).toBe('a4'); // Should fall back to default
expect(consoleWarnSpy).toHaveBeenCalled();
consoleWarnSpy.mockRestore();
});
});
describe('getValidTypstPaperSizes', () => {
it('should return all Typst paper size values', () => {
const validSizes = getValidTypstPaperSizes();
expect(validSizes).toHaveLength(8);
expect(validSizes).toContain('a3');
expect(validSizes).toContain('a4');
expect(validSizes).toContain('a5');
expect(validSizes).toContain('a6');
expect(validSizes).toContain('eu-business-card');
expect(validSizes).toContain('us-letter');
expect(validSizes).toContain('us-legal');
expect(validSizes).toContain('us-business-card');
});
it('should return a new array each time', () => {
const sizes1 = getValidTypstPaperSizes();
const sizes2 = getValidTypstPaperSizes();
// Should return different array instances
expect(sizes1).not.toBe(sizes2);
// But with same content
expect(sizes1).toEqual(sizes2);
});
it('should not include duplicate values', () => {
const validSizes = getValidTypstPaperSizes();
const uniqueSizes = new Set(validSizes);
expect(uniqueSizes.size).toBe(validSizes.length);
});
});
describe('isSupportedPaperSize', () => {
it('should return true for supported sizes', () => {
expect(isSupportedPaperSize('a3')).toBe(true);
expect(isSupportedPaperSize('a4')).toBe(true);
expect(isSupportedPaperSize('a5')).toBe(true);
expect(isSupportedPaperSize('a6')).toBe(true);
expect(isSupportedPaperSize('us-letter')).toBe(true);
expect(isSupportedPaperSize('us-legal')).toBe(true);
expect(isSupportedPaperSize('eu-business-card')).toBe(true);
expect(isSupportedPaperSize('us-business-card')).toBe(true);
});
it('should return false for unsupported sizes', () => {
expect(isSupportedPaperSize('invalid')).toBe(false);
expect(isSupportedPaperSize('unknown')).toBe(false);
expect(isSupportedPaperSize('')).toBe(false);
expect(isSupportedPaperSize('A4')).toBe(false); // Case-sensitive
expect(isSupportedPaperSize('letter')).toBe(false); // Missing 'us-' prefix
});
it('should handle edge cases', () => {
expect(isSupportedPaperSize(null as any)).toBe(false);
expect(isSupportedPaperSize(undefined as any)).toBe(false);
expect(isSupportedPaperSize(123 as any)).toBe(false);
});
});
});
+5
View File
@@ -0,0 +1,5 @@
// Mock process.platform for cross-platform testing
Object.defineProperty(process, 'platform', {
value: 'darwin',
writable: true,
});
+2
View File
@@ -11,6 +11,8 @@
"importHelpers": true, "importHelpers": true,
"isolatedModules": true, "isolatedModules": true,
"strictNullChecks": true, "strictNullChecks": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"lib": [ "lib": [
"DOM", "DOM",
"ES5", "ES5",
+4 -1
View File
@@ -3,5 +3,8 @@
"1.0.1": "1.9.12", "1.0.1": "1.9.12",
"1.1.0": "1.9.12", "1.1.0": "1.9.12",
"1.2.0": "1.9.12", "1.2.0": "1.9.12",
"1.2.1": "1.9.12" "1.2.1": "1.9.12",
"1.3.0": "1.9.12",
"1.3.1": "1.9.12",
"1.4.0": "1.9.12"
} }
+39
View File
@@ -0,0 +1,39 @@
import { defineConfig } from 'vitest/config';
import path from 'path';
export default defineConfig({
test: {
globals: true,
environment: 'happy-dom',
setupFiles: ['./tests/setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html', 'lcov'],
include: ['src/**/*.ts'],
exclude: [
'node_modules/**',
'tests/**',
'*.config.*',
'**/*.d.ts',
'**/*.test.ts',
'main.ts', // Entry point, tested through integration
'version-bump.mjs',
'scripts/**',
],
all: true, // Include all source files in coverage report
thresholds: {
lines: 80,
functions: 80,
branches: 80,
statements: 80,
},
},
include: ['tests/**/*.test.ts'],
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'obsidian': path.resolve(__dirname, './tests/__mocks__/obsidian.ts'),
},
},
});