50 Commits
Author SHA1 Message Date
Jarvis 3f138f0b4b fix(FileDiscovery): Use PathUtils.getVaultPath() instead of adapter.basePath
Fixes TypeScript error by using the existing PathUtils.getVaultPath() method
which safely accesses FileSystemAdapter.getBasePath() with proper error handling.
The adapter.basePath property doesn't exist on DataAdapter interface.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:50:36 +02:00
AlexKucera f1d545553b Merge pull request #5 from AlexKucera/1.3.0
Enhances path handling and file resolution
2025-09-25 16:47:12 +02:00
Jarvis ff8e9f9ea3 fix(PathUtils): Improve cross-platform absolute path detection
Replace complex heuristic with precise pattern matching for absolute paths:
- Unix paths: starts with /
- Windows drive letters: C:\ or C:/ using regex /^[a-zA-Z]:[/\\]/
- Windows UNC paths: \\server\share

Removes unreliable temp/tmp path indicators and file: URL checks while
maintaining fs fallback behavior for proper external file processing.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:44:46 +02:00
Jarvis 21ed9e122f fix(FontManager): Improve cross-platform PATH handling and deduplication
- Set both PATH and Path environment variables for Windows compatibility
- Add tilde (~) path expansion for user home directories
- Implement actual path deduplication using Set instead of just filtering empty strings
- Properly split and combine existing PATH with additional platform-specific paths

Ensures spawned typst processes can find executables reliably across all platforms.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:41:27 +02:00
Jarvis 731a76eaf2 fix(FileDiscovery): Add vault path detection for safe adapter.list() usage
Prevents adapter.list() errors on absolute temp paths by detecting whether outputDir
is inside the vault and using filesystem fallback for external/absolute paths.
Only calls adapter.list() with vault-relative paths for proper Obsidian compatibility.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:39:08 +02:00
Jarvis 0cd6b53687 fix(BinaryLocator): Add filesystem fallback for validateBinaryExists when plugin unavailable
Improves binary validation by using fs.promises.access() as fallback when plugin context
is not available, ensuring cross-platform binary detection works reliably.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:37:10 +02:00
Jarvis e084ff38cb fix(TemplateManager): Convert absolute path to vault-relative for adapter.list()
- Fixed adapter.list() call to use vault-relative path instead of absolute templatesPath
- Added proper path conversion by stripping vault base path and leading separators
- Ensures compatibility with Obsidian's vault.adapter API requirements
- Prevents potential file listing failures due to incorrect path format
- Maintains cross-platform path handling with proper separator normalization

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:32:21 +02:00
Jarvis 97b356a912 fix(ExportOrchestrator): Add pluginName to TempDirectoryManager.create() for targeted cleanup
- Fixed TempDirectoryManager.create() to pass plugin.manifest.id instead of undefined
- Ensures temp directory cleanup targets only this plugin's directories
- Prevents interference with other plugins' temp directories
- Improves plugin isolation and cleanup reliability
- Follows proper plugin namespacing patterns established earlier

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:30:53 +02:00
Jarvis c4062d66b0 security(TempDirectoryManager): Fix path traversal vulnerability with normalized path comparison
- Replaced vulnerable string operations (startsWith/includes) with normalized path comparison
- Uses normalizePath() for proper cross-platform path normalization
- Constructs explicit temp directory paths for precise validation
- Prevents path traversal attacks like '../../../etc/passwd' or similar
- Ensures directory validation is based on actual path structure, not string matching
- Maintains functionality while improving security posture

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:29:54 +02:00
Jarvis 4e3ef6ce9c fix(PathUtils): Improve cross-platform absolute path detection without Node.js path module
- Replaced problematic heuristic path.includes('/') && !path.startsWith('.')
- Added explicit checks for Windows drive letters (C:), UNC paths, and Unix absolute paths
- Enhanced detection for temp directories and file URLs across platforms
- Maintains Obsidian API-first approach without importing Node.js path module
- Better handles Windows absolute paths like 'C:\Users\...' and '\UNC\paths'
- Preserves existing fs.access fallback behavior for external files

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:26:11 +02:00
Jarvis d54ac148c0 fix(ImageOptimizer): Convert absolute paths to vault-relative for adapter.remove()
- Fixed vault.adapter.remove() call to use vault-relative paths instead of absolute paths
- Added proper path conversion by stripping vault base path and leading separators
- Maintains fs.unlink fallback when plugin.app is not available
- Prevents potential file removal failures due to incorrect path format
- Follows Obsidian API best practices for vault operations

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:23:54 +02:00
AlexKucera a1293808af Fixes CodeRabbit badge URL
Corrects the CodeRabbit badge URL in the README.
2025-09-25 16:19:48 +02:00
Jarvis 2cdc9c3976 docs(CHANGELOG): Add comprehensive 1.3.1 release notes
- Documents all CodeRabbit review improvements implemented
- Highlights Windows compatibility enhancements
- Details dynamic image format support and pattern matching
- Records cross-platform font discovery improvements
- Notes security and path validation enhancements
- Organizes changes by Added/Fixed/Changed/Security categories

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:12:32 +02:00
Jarvis 0a409076c3 feat(FontManager): Improve path consistency and cross-platform font discovery
- Fixed vault.adapter operations to use vault-relative paths instead of absolute paths
- Added platform detection to cache data for invalidation on OS changes
- Enhanced error recovery with corrupted cache detection and automatic regeneration
- Improved cache validation with structure and content checks
- Added platform-specific PATH building for better Typst executable discovery
- Enhanced Windows, macOS, and Linux font path resolution
- Added comprehensive fallback mechanisms for all error scenarios
- Improved type safety and error handling throughout

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:10:28 +02:00
Jarvis a22bd06b7b fix(ExportOrchestrator): Add plugin namespacing to TempDirectoryManager
- Added pluginName parameter using manifest.id for proper temp directory namespacing
- Improves isolation when multiple similar plugins are installed
- Prevents temp directory conflicts between plugins
- Uses existing TempDirectoryOptions.pluginName field per CodeRabbit review

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:07:20 +02:00
Jarvis 0cc96e9345 feat(FileDiscovery): Add dynamic image extension support with enhanced pattern matching
- Added support for multiple image formats (.png, .jpg, .jpeg, .webp, .gif, .bmp, .tiff)
- Replaced hardcoded PNG-only filtering with dynamic extension detection
- Enhanced pattern matching with 5 progressive strategies:
  1. Exact filename match
  2. Base name match with any supported extension
  3. Sanitized pattern match (removes special characters)
  4. Fuzzy match for pdf2img patterns (handles -1, -page1 suffixes)
  5. Fallback to first available image file
- Updated generateExpectedFilename with format validation and warnings
- Improved error messages to show supported formats and available files

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:06:00 +02:00
Jarvis 24a169d490 feat(BinaryLocator): Add Windows compatibility with platform-specific binary detection
- Added support for Windows executable extensions (.cmd, .bat, .ps1, .exe)
- Implemented comprehensive fallback paths for different installation methods
- Enhanced binary discovery with Windows-specific npm locations
- Improved error reporting with detailed search path information
- Maintains backward compatibility for Unix-like systems

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 16:01:28 +02:00
AlexKucera d20e8cf0ae Adds CodeRabbit Reviews badge to README
Includes a CodeRabbit Reviews badge in the README to provide quick access to code review insights.
2025-09-25 15:37:19 +02:00
Jarvis b47571dccd fix(ResourcePathResolver): Use vault-relative paths for adapter.list()
- Changed adapter.list() to use empty string for vault root instead of absolute path
- Convert vault-relative paths to absolute paths when returning for external tools
- Fixes cross-platform compatibility issues per CodeRabbit review
- Maintains existing functionality while following Obsidian API best practices

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 13:45:57 +02:00
Jarvis 3782f0a7fb fix: remove extra quotes from pandoc resource path arguments
- Remove manual quotes around templatesDir path in PandocCommandBuilder
- Node.js spawn() handles argument quoting automatically
- Manual quotes can break path resolution, especially on Windows
- Follows Node.js best practices for child_process.spawn()

CodeRabbit suggestion implementation 1/6
2025-09-25 13:43:13 +02:00
Jarvis c971c920ce chore: release 1.3.0 2025-09-25 12:46:54 +02:00
Jarvis 37015c8ed6 fix: resolve embedded file path resolution issue in PathUtils.fileExists
- Fix pathUtils.fileExists() to handle absolute filesystem paths
- Add proper conversion from absolute to vault-relative paths
- Add fs fallback for external files outside vault
- Resolves 'File not found' errors for embedded PDF, image, and document files
- Maintains compatibility with both vault-relative and absolute paths

This fixes the path resolution issue that occurred after migrating to vault.adapter,
where embedded files were showing as 'not found' because absolute paths were being
passed to vault.adapter.exists() which only accepts vault-relative paths.
2025-09-25 12:43:00 +02:00
Jarvis 0ff5b4a1b8 refactor: migrate embeddedTemplates.ts to use PathUtils and vault.adapter
- Replace fs operations with vault.adapter methods
- Update constructor to require App parameter
- Make all methods async for vault.adapter compatibility
- Update PluginLifecycle.ts to match new async API
- Remove direct fs/path module dependencies
- Build and lint pass successfully

Safety commit 16/16 - Path migration complete!
2025-09-25 12:39:54 +02:00
Jarvis b6f64d1cf7 refactor: migrate ImageOptimizer.ts to use vault.adapter
- Replace fs.unlink/rename with vault.adapter methods when plugin available
- Replace path.join with PathUtils.joinPath for vault paths
- Add plugin parameter to optimizeImage method for vault.adapter access
- Keep path module for external tool operations
- Add fs fallbacks for temp file operations when plugin unavailable
- Use readBinary/writeBinary pattern for image file moves
- Update PdfToImageConverter.ts to pass plugin to ImageOptimizer
- Maintain dual approach for vault and external temp file handling
2025-09-25 12:35:45 +02:00
Jarvis 497407e288 refactor: migrate FileDiscovery.ts to use vault.adapter
- Replace fs.access/readdir with vault.adapter methods
- Replace path.join with PathUtils.joinPath for vault paths
- Add plugin parameter to methods for vault.adapter access
- Keep path module for basename operations on external files
- Add fs fallback when plugin unavailable (external tool output)
- Update PdfToImageConverter.ts to pass plugin to FileDiscovery
- Maintain dual approach for vault and external file discovery
2025-09-25 12:30:25 +02:00
Jarvis ee79ed3f74 refactor: migrate ResourcePathResolver.ts to use vault.adapter
- Replace all fs operations with vault.adapter methods
- Replace fs.readdirSync with vault.adapter.list for directory scanning
- Replace fs.existsSync with PathUtils.fileExists
- Replace path.join with PathUtils.joinPath for vault paths
- Remove fs/fsPromises imports, add PathUtils import
- Add plugin parameter to constructor for vault.adapter access
- Update PandocCommandBuilder to pass plugin to ResourcePathResolver
- Maintain resource discovery functionality for Pandoc
2025-09-25 12:27:33 +02:00
Jarvis f8142f995a refactor: migrate PandocCommandBuilder.ts to use PathUtils
- Replace fs.existsSync with PathUtils.fileExists()
- Replace path.resolve with PathUtils.joinPath() for vault paths
- Remove fs require, add PathUtils import
- Keep path module for external tool relative path operations (path.relative)
- Follow plan guidance for minimal path usage with external tools
2025-09-25 12:25:25 +02:00
Jarvis 948ec77ae6 refactor: migrate PdfToImageConverter.ts to use vault.adapter
- Replace fs.mkdir with PathUtils.ensureDir()
- Remove fs/promises import
- Keep path module for external PDF file basename extraction
- Add null check for plugin.app availability
- Follow plan guidance for minimal path usage with external files
2025-09-25 12:24:18 +02:00
Jarvis 121fc0a75c refactor: migrate PandocTypstConverter.ts to use PathUtils
- Replace fs.promises operations with vault.adapter methods
- Replace path.join with PathUtils.joinPath for temp file paths
- Replace fsPromises.writeFile/unlink with vault.adapter.write/remove
- Replace fsPromises.rmdir with PathUtils.cleanupDir
- Remove unused path and os imports
- Use TempDirectoryManager consistently for both fallback cases
2025-09-25 12:22:54 +02:00
Jarvis c9304405ee refactor: integrate PathUtils into FontManager.ts
- Replace path.join operations with PathUtils methods
- Remove path module import, use PathUtils for all path operations
- Already used vault.adapter correctly for file operations
- Maintain consistency with other migrated files
2025-09-25 12:19:54 +02:00
Jarvis 86e59c5421 refactor: migrate BinaryLocator.ts to use PathUtils
- Replace unsafe basePath cast with PathUtils.getVaultPath()
- Replace fs.existsSync with PathUtils.fileExists()
- Remove fs fallbacks since app is always available in Obsidian
- Keep path module for command-line path building
- Add proper null checking for plugin.app
2025-09-25 12:18:14 +02:00
Jarvis 610a87d788 refactor: migrate EmbedProcessor to use vault.adapter
- Replaced fs.promises.access with PathUtils.fileExists() for file existence checks
- Replaced fs.promises.mkdir with PathUtils.ensureDir() for directory creation
- Replaced fs.promises.copyFile with vault.adapter readBinary/writeBinary operations
- Replaced path.join with PathUtils.joinPath() for consistent path normalization
- Updated all file resolution methods to use proper Obsidian API methods
- Removed fs import and all direct filesystem operations
- Enhanced copyImageToVaultTemp to use vault.adapter for binary file operations

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 12:14:11 +02:00
Jarvis da904e6ddd refactor: migrate PluginLifecycle to use PathUtils
- Replaced multiple basePath hacks (lines 25, 70, 86) with PathUtils.getVaultPath()
- Replaced path.join with PathUtils.joinPath() and getPluginDir()
- Removed path import after migration to PathUtils
- Added PathUtils integration for consistent path operations
- All three basePath hack locations now use proper Obsidian API methods
- TempDirectoryManager calls already updated in previous commit

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 12:11:00 +02:00
Jarvis c6a5e1f346 refactor: migrate ExportOrchestrator to use PathUtils
- Replaced unsafe basePath hack with PathUtils.getVaultPath()
- Replaced path.join with PathUtils.joinPath() and getPluginDir()
- Removed unused path import after migration
- Added PathUtils integration for consistent path operations
- TempDirectoryManager calls already updated in previous commit

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 12:09:17 +02:00
Jarvis 4498281b7d refactor: migrate TemplateManager to use vault.adapter
- Replaced basePath hack with PathUtils.getVaultPath() and getPluginDir()
- Replaced fs.existsSync with vault.adapter.exists() via PathUtils.fileExists()
- Replaced fs.readdirSync with vault.adapter.list() for directory listing
- Replaced fs.readFileSync with vault.adapter.read() for template content
- Replaced path.join with PathUtils.joinPath() for consistent normalization
- Removed fs import and all direct filesystem operations
- All template operations now use proper Obsidian API methods

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 12:07:31 +02:00
Jarvis d4d5401293 refactor: migrate PathResolver to use PathUtils
- Replaced unsafe basePath hack with PathUtils.getVaultPath()
- Replaced fs.promises.access/mkdir with vault.adapter methods via PathUtils.ensureDir()
- Replaced path.join with PathUtils.joinPath() for consistent normalization
- Removed fs import and direct filesystem operations
- Simplified error handling with PathUtils abstraction
- All path operations now use proper Obsidian API methods

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 12:05:51 +02:00
Jarvis 180155b4e0 refactor: migrate TempDirectoryManager to use vault.adapter exclusively
- Updated TempDirectoryManager to use vault.adapter methods exclusively
- Made all temp directory operations async (ensureTempDir, cleanupTempDir, cleanupAllTempDirs)
- Removed unnecessary fs fallback since App instance is always available in Obsidian plugins
- Updated calling code in PandocTypstConverter and ExportOrchestrator to handle async
- Updated PluginLifecycle cleanup methods to use fire-and-forget async pattern
- All path operations now use normalizePath for cross-platform compatibility
- Simplified interface - App parameter is now required as it should be

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 12:01:47 +02:00
Jarvis 5598e0e538 feat: add PathUtils helper class for centralized path operations
- Add ABOUTME comments following guidelines
- Implement safe FileSystemAdapter access with proper type checking
- Use vault.adapter methods (exists, mkdir, list, remove)
- Use normalizePath() consistently for all paths
- Match existing patterns (cleanupDir only removes files, returns boolean)
- Add user-friendly error messages with Notice
- Place in src/core/ alongside other core utilities

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 11:44:00 +02:00
AlexKucera e320238a79 Updates README downloads badge
Updates the downloads badge in README to link directly to releases instead of the Obsidian plugins page.
This provides a more direct path to the plugin's release notes and associated files.
2025-09-21 22:09:16 +02:00
AlexKucera 09dff9f1fb Updates shields.io badge color
Updates the color parameter in the GitHub release badge URL to maintain consistency with the shields.io query parameter syntax.
2025-09-21 16:04:17 +02:00
AlexKucera bd2a54bb50 Merge branch 'feature/better_templates' into develop 2025-09-21 16:02:47 +02:00
AlexKucera 0a2a324d77 Updates plugin release badge URL
Updates the release badge URL in the README to point to the correct repository name.
2025-09-21 16:02:36 +02:00
AlexKucera 18c0e1736c Removes unused sharp dependency
Removes the `sharp` dependency from the esbuild configuration.

This dependency was not being used, and its removal reduces the bundle size and improves build performance.
2025-09-21 16:02:32 +02:00
AlexKucera 4892b4a6c4 Adds Typst templates for varied document styles
Introduces three new Typst templates: "book," "sidebar," and "two-column."

The "book" template emulates a classic book style with serif fonts, alternating margins, and running headers. It also includes features such as drop caps, email block styling, and a title page.

The "sidebar" template uses a modern sans-serif font and a prominent sidebar for navigation and document information.

The "two-column" template is designed for academic papers or CVs, using a two-column layout, serif fonts, and compact paragraph spacing.

Updates the "modern" template to use a different color scheme for headings and title block.
2025-09-21 16:02:27 +02:00
AlexKucera 9124531c58 Improves Typst error reporting in Pandoc conversion
Replaces intermediate Typst file generation with enhanced diagnostic options

Adds short diagnostic format for better error reporting during Typst PDF engine conversion
Removes complex intermediate file generation and debug file copying logic
Simplifies command builder by focusing on diagnostic improvements
2025-09-11 12:11:33 +02:00
AlexKucera 730e4997eb Merge branch 'master' into develop 2025-09-11 09:42:17 +02:00
AlexKucera 7aae2ce63a Enhances README with plugin motivation and benefits
Adds detailed explanation of the plugin's purpose, highlighting key advantages over native Obsidian PDF export

Provides insights into the motivation behind creating the plugin, emphasizing:
- Professional typesetting quality
- Flexible document generation
- Separation of content and styling
- Continuous reading experience

Illustrates how the plugin transforms Obsidian into a more robust document preparation system
2025-09-11 09:42:02 +02:00
AlexKucera dafa9c2caa Adds development philosophy section to README
Documents AI-assisted development approach with emphasis on quality control

Explains the methodology behind the plugin's development, highlighting:
- Controlled AI code generation
- Strict review and validation processes
- Tools used to prevent low-quality code
- Commitment to maintaining high code standards

Details the systematic approach to leveraging AI while preserving code quality and architectural integrity
2025-09-11 09:41:19 +02:00
AlexKucera 1d0c6c2541 Fixes typo in README Email Block support description
Corrects spelling of "Support" in feature description section

Improves documentation readability by fixing minor typographical error
2025-09-10 23:03:24 +02:00
AlexKucera a1d633772b Merge branch 'release/1.2.1' into develop 2025-09-10 23:00:56 +02:00
27 changed files with 2269 additions and 327 deletions

No files matched your search

+47
View File
@@ -5,6 +5,53 @@ 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
### Added
- **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)
- **Enhanced Pattern Matching**: Five-strategy file discovery system for robust PDF-to-image conversion output detection
- **Cross-Platform Font Discovery**: Platform-specific PATH building for improved Typst executable and font detection
- **Improved Plugin Isolation**: TempDirectoryManager now uses proper plugin namespacing to prevent conflicts
### Fixed
- **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
- **Resource Path Resolution**: Removed extra quotes from Pandoc arguments that could break spawn commands on Windows
- **Font Cache Corruption Recovery**: Enhanced error handling with automatic cache regeneration and validation
- **Template Path Resolution**: Fixed resource path handling in PandocCommandBuilder for better cross-platform compatibility
### Changed
- **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
- **Code Quality**: Improved type safety, error handling, and validation across all affected modules
- **Performance**: Optimized file discovery with progressive pattern matching strategies
### Security
- **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
## [1.3.0] - 2024-12-25
### Added
- PathUtils helper class for centralized path operations and safe Obsidian API usage
- Improved Typst error reporting in Pandoc conversion with enhanced diagnostic output
- New Typst templates for varied document styles (modern, article, report)
- Enhanced README with plugin motivation, development philosophy, and updated badges
### Fixed
- **Critical**: Embedded file path resolution issue that caused "File not found" errors for PDFs, images, and documents
- Proper vault.adapter integration replacing unsafe type casts throughout codebase
- Path handling reliability with comprehensive migration from Node.js fs/path to Obsidian APIs
- File existence checks now handle both vault-relative and absolute filesystem paths
### Changed
- **Major Refactoring**: Complete migration from Node.js fs/path to Obsidian vault.adapter APIs
- Centralized path utilities replacing unsafe `(app.vault.adapter as unknown as { basePath: string }).basePath` patterns
- Improved file system operations security and cross-platform compatibility
- Enhanced error handling and path validation across all modules
- Updated all 16 core files with consistent, safe path handling practices
## [1.2.1] - 2025-01-10 ## [1.2.1] - 2025-01-10
### Fixed ### Fixed
+37 -3
View File
@@ -1,8 +1,9 @@
# Obsidian Typst PDF Export # Obsidian Typst PDF Export
[![GitHub release (latest by date)](https://img.shields.io/github/v/release/akucera/obsidian-typst-pdf-export-blue)](https://github.com/akucera/obsidian-typst-pdf-export/releases) [![GitHub release (latest by date)](https://img.shields.io/github/v/release/AlexKucera/obsidian-typst-pdf-export?color=blue)](https://github.com/AlexKucera/obsidian-typst-pdf-export/releases)
[![License: MIT](https://img.shields.io/github/license/AlexKucera/obsidian-typst-pdf-export?color=yellow)](https://opensource.org/licenses/MIT) [![License: MIT](https://img.shields.io/github/license/AlexKucera/obsidian-typst-pdf-export?color=yellow)](https://opensource.org/licenses/MIT)
[![Obsidian Downloads](https://img.shields.io/github/downloads/AlexKucera/obsidian-typst-pdf-export/total?color=green)](https://obsidian.md/plugins?id=obsidian-typst-pdf-export) [![Downloads](https://img.shields.io/github/downloads/AlexKucera/obsidian-typst-pdf-export/total?color=green)](https://github.com/AlexKucera/obsidian-typst-pdf-export/releases)
[![CodeRabbit Reviews](https://img.shields.io/coderabbit/prs/github/AlexKucera/obsidian-typst-pdf-export)](https://coderabbit.ai/)
![](https://img.shields.io/badge/desktop_only-red?label=obsidian&labelColor=purple) ![](https://img.shields.io/badge/desktop_only-red?label=obsidian&labelColor=purple)
@@ -34,7 +35,20 @@ Export Obsidian notes to PDF using the Typst typesetting system. Supports custom
- **🔍 Font Discovery**: Automatic system font detection and caching - **🔍 Font Discovery**: Automatic system font detection and caching
- **🛡️ Security First**: Path validation and sanitization for safe operations - **🛡️ Security First**: Path validation and sanitization for safe operations
- **📐 Professional Layout**: Paper sizes, margins, typography controls, and more - **📐 Professional Layout**: Paper sizes, margins, typography controls, and more
- **📧 Email Block SUpport**: Supports the YAML Email Block format introduced by the [Email Block plugin](https://github.com/joleaf/obsidian-email-block-plugin) - **📧 Email Block Support**: Supports the YAML Email Block format introduced by the [Email Block plugin](https://github.com/joleaf/obsidian-email-block-plugin)
## Why This Plugin?
This plugin was born from frustration with Obsidian's native PDF export, which simply renders notes using the current Obsidian theme. While functional, this approach lacks the professional typesetting quality needed for serious documents.
The immediate catalyst came from a practical need: my wife required single-page PDFs – documents where the page grows to accommodate all content without pagination breaks. This format is ideal for digital preservation and viewing, keeping everything in one continuous, scrollable document. The native export couldn't provide this. By leveraging Typst's powerful typesetting engine, this plugin delivers:
- **Professional Quality**: Properly typeset documents that look publication-ready, not just screenshots of notes
- **Flexible Page Sizing**: Create single-page PDFs that expand to fit all content – perfect for digital preservation and continuous reading
- **True Separation of Concerns**: Content and styling are properly separated, following best practices in document preparation
- **Consistent Output**: Documents that look good by default, without requiring theme tweaking
This transforms Obsidian from a note-taking tool into a complete document preparation system, bridging the gap between quick notes and professional output.
## Why Typst? ## Why Typst?
@@ -310,6 +324,26 @@ The plugin follows a modular architecture with:
- **Security Layer**: Path validation and sanitization - **Security Layer**: Path validation and sanitization
- **Progress Tracking**: Real-time feedback with cancellation support - **Progress Tracking**: Real-time feedback with cancellation support
## Development Philosophy
This plugin was developed using [vibe coding](https://en.wikipedia.org/wiki/Vibe_coding) techniques with AI assistance, but with crucial safeguards to prevent [AI slop](https://en.wikipedia.org/wiki/AI_slop). Unlike typical vibe coding where code is generated without detailed review, this project employed strict quality control measures:
### AI-Assisted Development with Human Oversight
- **Controlled Generation**: While large portions of code were AI-generated, every function was reviewed and validated
- **Slop Prevention Tools**: Used specialized tools like `slopwatch` and `vibe-check` to catch and prevent low-quality patterns
- **Systematic Review**: All AI suggestions were filtered through domain expertise and architectural consistency checks
- **Test-Driven Validation**: Comprehensive testing ensured generated code met production standards
### Quality Control Measures
- **Pattern Enforcement**: AI was guided by strict architectural patterns and coding standards
- **Memory Management**: Used persistent context tools to maintain consistency across development sessions
- **Iterative Refinement**: Code went through multiple review-refactor cycles to eliminate "code smell"
- **Human Decision Making**: Critical design decisions and architecture remained under human control
This approach allowed rapid development while maintaining the code quality expected of a production Obsidian plugin. The result is clean, maintainable code that leverages AI's productivity benefits without sacrificing quality or introducing the technical debt typically associated with pure vibe coding.
## Contributing ## Contributing
Contributions are welcome. Contributions are welcome.
-1
View File
@@ -86,7 +86,6 @@ const context = await esbuild.context({
"@lezer/common", "@lezer/common",
"@lezer/highlight", "@lezer/highlight",
"@lezer/lr", "@lezer/lr",
"sharp",
...builtins], ...builtins],
format: "cjs", format: "cjs",
target: "es2018", target: "es2018",
+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.2.1", "version": "1.3.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",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "obsidian-typst-pdf-export", "name": "obsidian-typst-pdf-export",
"version": "1.2.1", "version": "1.3.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": {
+232
View File
@@ -0,0 +1,232 @@
# CodeRabbit Suggestions Implementation Plan
## Overview
This plan documents the CodeRabbit review suggestions from PR #5 that should be implemented to improve cross-platform compatibility, code quality, and robustness of the Obsidian Typst PDF Export plugin.
## Implementation Tasks
### 1. ~~manifest.json - Version Compatibility~~ **SKIPPED**
- **Current**: `minAppVersion: "1.9.12"`
- **Decision**: Keep as-is - only up-to-date users should use the plugin
- **Status**: ✅ Skipped per user preference
### 2. PandocCommandBuilder.ts - Path Quoting Fix
**File**: `src/converters/pandoc/PandocCommandBuilder.ts`
**Line**: 113
**Issue**: Extra quotes around path can break spawn command
**Current Code**:
```typescript
args.push('--resource-path', `"${templatesDir}"`);
```
**Fix**:
```typescript
args.push('--resource-path', templatesDir);
```
**Reason**: The spawn command handles quoting automatically. Manual quotes can cause issues, especially on Windows.
### 3. ResourcePathResolver.ts - Vault-Relative Paths
**File**: `src/converters/pandoc/ResourcePathResolver.ts`
**Issues**:
- `adapter.list()` should use vault-relative paths, not absolute
- Should return absolute paths for external tools
- Need better error handling
**Changes Needed**:
- Ensure all `adapter.list()` calls use vault-relative paths
- Convert to absolute paths only when returning for external tool consumption
- Add try-catch blocks around path operations
- Validate paths before adding to resource list
### 4. BinaryLocator.ts - Windows Compatibility
**File**: `src/converters/pdf/BinaryLocator.ts`
**Issues**:
- Missing Windows executable extensions (.cmd, .bat, .ps1)
- No platform-specific binary detection
- Limited fallback mechanisms
**Changes Needed**:
```typescript
// Add Windows-specific executable detection
const windowsExtensions = process.platform === 'win32'
? ['.cmd', '.bat', '.ps1', '.exe']
: [''];
// Check for platform-specific binaries
const binaryName = process.platform === 'win32'
? 'pdf2img.cmd'
: 'pdf2img';
// Add multiple fallback paths for different installation methods
const fallbackPaths = [
path.join(pluginDir, 'node_modules', '.bin'),
path.join(pluginDir, 'node_modules', 'pdf-to-img', 'bin'),
// Windows-specific paths
path.join(process.env.APPDATA || '', 'npm'),
path.join(process.env.LOCALAPPDATA || '', 'npm-cache')
];
```
### 5. FileDiscovery.ts - Dynamic File Extension Support
**File**: `src/converters/pdf/FileDiscovery.ts`
**Issues**:
- Hardcoded to only look for '.png' files
- Should support multiple image formats
- Pattern matching too restrictive
**Changes Needed**:
```typescript
// Dynamic extension support
const supportedImageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.gif'];
// Update file filtering
const imageFiles = files.filter(f =>
supportedImageExtensions.some(ext => f.toLowerCase().endsWith(ext))
);
// Improve pattern matching to handle more filename variations
private static matchFilePattern(files: string[], expectedFileName: string): string | null {
const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName));
// Try multiple matching strategies
// 1. Exact match
// 2. Base name match with any supported extension
// 3. Sanitized pattern match
// 4. Fuzzy match for pdf2img output patterns
}
```
### 6. ExportOrchestrator.ts - Plugin Name for Temp Dir
**File**: `src/plugin/ExportOrchestrator.ts`
**Line**: 147
**Issue**: TempDirectoryManager should receive plugin name for proper namespacing
**Current Code**:
```typescript
const tempManager = new TempDirectoryManager({
vaultPath: vaultPath,
configDir: this.plugin.app.vault.configDir,
app: this.plugin.app
});
```
**Fix**:
```typescript
const tempManager = new TempDirectoryManager({
vaultPath: vaultPath,
configDir: this.plugin.app.vault.configDir,
app: this.plugin.app,
pluginName: this.plugin.manifest.id
});
```
### 7. FontManager.ts - Consistent Path Handling
**File**: `src/plugin/FontManager.ts`
**Issues**:
- Mixed use of absolute and vault-relative paths
- Potential issues with cross-platform font discovery
- Need better validation
**Changes Needed**:
- Ensure all vault.adapter operations use vault-relative paths
- Add platform-specific font discovery improvements
- Validate font paths before caching
- Add error recovery for corrupted cache
### 8. General Improvements
#### Error Handling
- Add comprehensive try-catch blocks
- Provide meaningful error messages to users
- Log detailed errors for debugging
- Implement graceful degradation
#### TypeScript Type Safety
- Remove any remaining `any` types
- Add proper type guards
- Use strict null checks
- Validate external data
#### Resource Cleanup
- Ensure temp files are always cleaned up
- Add finally blocks for cleanup operations
- Implement proper abort handling
- Clean up on plugin unload
#### Cross-Platform Testing Matrix
- Windows 10/11
- macOS (Intel and Apple Silicon)
- Linux (Ubuntu/Debian)
- Different Obsidian versions
## Implementation Order
1. **Critical Path Fixes** (High Priority)
- PandocCommandBuilder.ts - Remove path quotes
- ResourcePathResolver.ts - Fix path handling
- PathUtils.fileExists - Already fixed in previous commit
2. **Cross-Platform Compatibility** (Medium Priority)
- BinaryLocator.ts - Windows support
- FileDiscovery.ts - Dynamic extensions
- FontManager.ts - Platform-specific paths
3. **Code Quality** (Lower Priority)
- ExportOrchestrator.ts - Plugin namespacing
- General error handling improvements
- TypeScript type safety enhancements
## Testing Plan
### Unit Tests Needed
- Path resolution with various input formats
- Binary detection on different platforms
- File discovery with multiple extensions
- Font caching and retrieval
### Integration Tests
- Full export pipeline on Windows/Mac/Linux
- Embedded file resolution
- Template loading and processing
- Temp directory cleanup
### Manual Testing Checklist
- [ ] Export with embedded PDFs
- [ ] Export with various image formats
- [ ] Export with custom templates
- [ ] Export on Windows
- [ ] Export on macOS
- [ ] Export on Linux
- [ ] Verify temp directory cleanup
- [ ] Test cancellation during export
- [ ] Test with special characters in paths
## Expected Outcomes
1. **Improved Reliability**
- Fewer "file not found" errors
- Better error messages
- Graceful degradation
2. **Better Cross-Platform Support**
- Windows users can use the plugin
- Consistent behavior across platforms
- Platform-specific optimizations
3. **Cleaner Codebase**
- Better TypeScript types
- Consistent error handling
- Improved maintainability
## Notes
- All changes should maintain backward compatibility
- Test thoroughly before release
- Document any breaking changes
- Consider adding automated tests in future
## References
- Original PR: https://github.com/AlexKucera/obsidian-typst-pdf-export/pull/5
- CodeRabbit Review Comments: See PR comments
- Obsidian API Documentation: https://docs.obsidian.md/
- TypeScript Best Practices: https://www.typescriptlang.org/docs/handbook/
+15 -11
View File
@@ -3,12 +3,10 @@
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine * Handles the conversion of Markdown to PDF using Pandoc with Typst engine
*/ */
import { promises as fsPromises } from 'fs';
import * as path from 'path';
import * as os from 'os';
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 { PandocCommandBuilder } from './pandoc/PandocCommandBuilder'; import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor'; import { PandocExecutor } from './pandoc/PandocExecutor';
@@ -104,9 +102,10 @@ export class PandocTypstConverter {
// Create temporary markdown file // Create temporary markdown file
await this.ensureTempDirectory(); await this.ensureTempDirectory();
const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`); const pathUtils = new PathUtils(this.plugin.app);
const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
await fsPromises.writeFile(tempInputPath, content, 'utf-8'); await this.plugin.app.vault.adapter.write(tempInputPath, content);
// Merge options // Merge options
this.pandocOptions = { ...this.pandocOptions, ...options }; this.pandocOptions = { ...this.pandocOptions, ...options };
@@ -116,7 +115,7 @@ export class PandocTypstConverter {
// Cleanup temp file // Cleanup temp file
try { try {
await fsPromises.unlink(tempInputPath); await this.plugin.app.vault.adapter.remove(tempInputPath);
} catch (error) { } catch (error) {
console.warn('Failed to cleanup temp file:', error); console.warn('Failed to cleanup temp file:', error);
} }
@@ -162,7 +161,8 @@ export class PandocTypstConverter {
// Remove temporary directory // Remove temporary directory
if (this.tempDir) { if (this.tempDir) {
await fsPromises.rmdir(this.tempDir, { recursive: true }); const pathUtils = new PathUtils(this.plugin.app);
await pathUtils.cleanupDir(this.tempDir);
this.tempDir = null; this.tempDir = null;
} }
} catch (error) { } catch (error) {
@@ -178,11 +178,15 @@ export class PandocTypstConverter {
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 || '.obsidian';
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir); const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = tempManager.ensureTempDir('pandoc'); this.tempDir = await tempManager.ensureTempDir('pandoc');
} else { } else {
// Fallback to system temp if plugin folder not available // Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
this.tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'obsidian-typst-')); const pathUtils = new PathUtils(this.plugin.app);
const vaultPath = pathUtils.getVaultPath();
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
this.tempDir = await tempManager.ensureTempDir('pandoc');
} }
} }
return this.tempDir; return this.tempDir;
+8 -4
View File
@@ -3,13 +3,13 @@
* Converts PDF files to PNG images for preview in Typst exports * Converts PDF files to PNG images for preview in Typst exports
*/ */
import * as fs from 'fs/promises';
import * as path from 'path'; import * as path from 'path';
import { PdfProcessor } from './pdf/PdfProcessor'; import { PdfProcessor } from './pdf/PdfProcessor';
import { ImageOptimizer } from './pdf/ImageOptimizer'; import { ImageOptimizer } from './pdf/ImageOptimizer';
import { PdfCliExecutor } from './pdf/PdfCliExecutor'; import { PdfCliExecutor } from './pdf/PdfCliExecutor';
import { FileDiscovery } from './pdf/FileDiscovery'; import { FileDiscovery } from './pdf/FileDiscovery';
import type { obsidianTypstPDFExport } from '../../main'; import type { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils';
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) */
@@ -93,7 +93,10 @@ export class PdfToImageConverter {
} }
// Ensure output directory exists // Ensure output directory exists
await fs.mkdir(outputDir, { recursive: true }); if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app);
await pathUtils.ensureDir(outputDir);
}
// Generate expected output file name for the first page // Generate expected output file name for the first page
const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath)); const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath));
@@ -121,7 +124,7 @@ export class PdfToImageConverter {
} }
// Find the generated image file (may have different name than expected) // Find the generated image file (may have different name than expected)
const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName); const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName, this.plugin);
if (!fileDiscovery.found) { if (!fileDiscovery.found) {
return { return {
imagePath: '', imagePath: '',
@@ -140,7 +143,8 @@ export class PdfToImageConverter {
{ {
format: opts.format, format: opts.format,
quality: opts.quality quality: opts.quality
} },
this.plugin
); );
if (!optimizationResult.success) { if (!optimizationResult.success) {
+14 -34
View File
@@ -9,6 +9,7 @@ import { TypstVariableMapper } from './TypstVariableMapper';
import { ResourcePathResolver } from './ResourcePathResolver'; import { ResourcePathResolver } from './ResourcePathResolver';
import { PathResolver } from '../../plugin/PathResolver'; import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main'; import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils';
export class PandocCommandBuilder { export class PandocCommandBuilder {
private plugin: obsidianTypstPDFExport; private plugin: obsidianTypstPDFExport;
@@ -19,7 +20,7 @@ export class PandocCommandBuilder {
constructor(plugin: obsidianTypstPDFExport) { constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin; this.plugin = plugin;
this.variableMapper = new TypstVariableMapper(plugin); this.variableMapper = new TypstVariableMapper(plugin);
this.resourcePathResolver = new ResourcePathResolver(); this.resourcePathResolver = new ResourcePathResolver(plugin);
this.pathResolver = new PathResolver(plugin); this.pathResolver = new PathResolver(plugin);
} }
@@ -60,8 +61,8 @@ export class PandocCommandBuilder {
// Add Typst engine options // Add Typst engine options
this.addTypstEngineOptions(args, pandocOptions); this.addTypstEngineOptions(args, pandocOptions);
// Generate intermediate Typst file if requested // Add enhanced Typst diagnostics for better error reporting
await this.addIntermediateTypstOutput(args, pandocOptions); this.addTypstDiagnostics(args, pandocOptions);
// Set working directory for relative paths // Set working directory for relative paths
if (pandocOptions.vaultBasePath) { if (pandocOptions.vaultBasePath) {
@@ -95,21 +96,21 @@ export class PandocCommandBuilder {
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
if (pandocOptions.template) { if (pandocOptions.template) {
const fs = require('fs'); const pathUtils = new PathUtils(this.plugin.app);
const absolutePluginDir = pandocOptions.pluginDir || ''; const absolutePluginDir = pandocOptions.pluginDir || '';
const wrapperPath = path.resolve(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ'); const wrapperPath = pathUtils.joinPath(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ');
// Verify wrapper exists // Verify wrapper exists
if (!fs.existsSync(wrapperPath)) { if (!(await pathUtils.fileExists(wrapperPath))) {
throw new Error(`Universal wrapper template not found at: ${wrapperPath}`); throw new Error(`Universal wrapper template not found at: ${wrapperPath}`);
} }
args.push('--template', wrapperPath); args.push('--template', wrapperPath);
// Add plugin templates directory as a resource path so Typst can find template files // Add plugin templates directory as a resource path so Typst can find template files
const templatesDir = path.resolve(absolutePluginDir, 'templates'); const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates');
// Quote the path to handle spaces and special characters // Path quoting handled automatically by spawn
args.push('--resource-path', `"${templatesDir}"`); args.push('--resource-path', templatesDir);
// Pass the actual template path as a variable // Pass the actual template path as a variable
// Use relative path from vault root for Typst import // Use relative path from vault root for Typst import
@@ -147,32 +148,11 @@ export class PandocCommandBuilder {
} }
/** /**
* Generate intermediate Typst file if requested * Add enhanced Typst diagnostics for better error reporting
*/ */
private async addIntermediateTypstOutput(args: string[], pandocOptions: PandocOptions): Promise<void> { private addTypstDiagnostics(args: string[], pandocOptions: PandocOptions): void {
if (!pandocOptions.generateIntermediateTypst || !pandocOptions.tempDir) { // Add Typst diagnostic options for better error reporting
return; args.push('--pdf-engine-opt', '--diagnostic-format=short');
}
const typstPath = path.join(pandocOptions.tempDir, 'intermediate.typ');
args.push('--output', typstPath);
// Also create a copy to keep for debugging
const debugTypstPath = path.join(pandocOptions.tempDir, 'debug.typ');
// Store cleanup handler in pandocOptions to be handled by the caller
if (!pandocOptions.cleanupHandlers) {
pandocOptions.cleanupHandlers = [];
}
pandocOptions.cleanupHandlers.push(() => {
try {
const fs = require('fs');
if (fs.existsSync(typstPath)) {
fs.copyFileSync(typstPath, debugTypstPath);
}
} catch (e) {
console.warn('Could not create debug Typst file:', e);
}
});
} }
} }
-4
View File
@@ -30,10 +30,6 @@ export class PandocExecutor {
const pandocPath = this.pathResolver.resolveExecutablePath(pandocOptions.pandocPath, 'pandoc'); const pandocPath = this.pathResolver.resolveExecutablePath(pandocOptions.pandocPath, 'pandoc');
const timeout = pandocOptions.timeout || 60000; const timeout = pandocOptions.timeout || 60000;
// Log the exact command being executed for debugging
progressCallback?.('Starting Pandoc process...', 40);
// Determine working directory - use vault base path if available, fallback to plugin directory // Determine working directory - use vault base path if available, fallback to plugin directory
let workingDir: string; let workingDir: string;
+34 -30
View File
@@ -1,36 +1,41 @@
import * as path from 'path'; import { PathUtils } from '../../core/PathUtils';
import { promises as fsPromises } from 'fs'; import type { obsidianTypstPDFExport } from '../../../main';
/** /**
* Handles resource path resolution and caching for Pandoc conversions. * Handles resource path resolution and caching for Pandoc conversions.
* Discovers and caches attachment directories to help Pandoc find embedded resources. * Discovers and caches attachment directories to help Pandoc find embedded resources.
*/ */
export class ResourcePathResolver { export class ResourcePathResolver {
private plugin: obsidianTypstPDFExport | undefined;
private resourcePathCache: string[] = []; private resourcePathCache: string[] = [];
private resourcePathCacheTimestamp: number = 0; private resourcePathCacheTimestamp: number = 0;
private resourcePathCacheVaultPath: string = ''; private resourcePathCacheVaultPath: string = '';
private readonly CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes private readonly CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
constructor(plugin?: obsidianTypstPDFExport) {
this.plugin = plugin;
}
/** /**
* Get all resource paths for the given vault, using cache when possible * Get all resource paths for the given vault, using cache when possible
* @param vaultBasePath The base path of the vault * @param vaultBasePath The base path of the vault
* @returns Array of resource paths for Pandoc to search * @returns Array of resource paths for Pandoc to search
*/ */
async getResourcePaths(vaultBasePath: string): Promise<string[]> { async getResourcePaths(vaultBasePath: string): Promise<string[]> {
if (!vaultBasePath) { if (!vaultBasePath || !this.plugin?.app) {
return []; return [];
} }
const fs = require('fs'); const pathUtils = new PathUtils(this.plugin.app);
const resourcePaths: string[] = []; const resourcePaths: string[] = [];
// Add vault root as primary resource path // Add vault root as primary resource path
resourcePaths.push(vaultBasePath); resourcePaths.push(vaultBasePath);
// Add common attachment directories // Add common attachment directories
const commonPaths = this.getCommonAttachmentPaths(vaultBasePath); const commonPaths = this.getCommonAttachmentPaths(vaultBasePath, pathUtils);
for (const attachPath of commonPaths) { for (const attachPath of commonPaths) {
if (fs.existsSync(attachPath)) { if (await pathUtils.fileExists(attachPath)) {
resourcePaths.push(attachPath); resourcePaths.push(attachPath);
} }
} }
@@ -42,7 +47,7 @@ export class ResourcePathResolver {
resourcePaths.push(...this.resourcePathCache); resourcePaths.push(...this.resourcePathCache);
} else { } else {
// Cache is invalid or expired, perform fresh scan // Cache is invalid or expired, perform fresh scan
const scannedPaths = await this.scanForResourcePaths(vaultBasePath, fs, now); const scannedPaths = await this.scanForResourcePaths(vaultBasePath, pathUtils, now);
resourcePaths.push(...scannedPaths); resourcePaths.push(...scannedPaths);
} }
@@ -52,15 +57,16 @@ export class ResourcePathResolver {
/** /**
* Get common attachment directory paths that Obsidian users typically use * Get common attachment directory paths that Obsidian users typically use
* @param vaultBasePath The base path of the vault * @param vaultBasePath The base path of the vault
* @param pathUtils PathUtils instance for path operations
* @returns Array of common attachment directory paths * @returns Array of common attachment directory paths
*/ */
private getCommonAttachmentPaths(vaultBasePath: string): string[] { private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] {
return [ return [
path.join(vaultBasePath, 'attachments'), pathUtils.joinPath(vaultBasePath, 'attachments'),
path.join(vaultBasePath, 'assets'), pathUtils.joinPath(vaultBasePath, 'assets'),
path.join(vaultBasePath, 'files'), pathUtils.joinPath(vaultBasePath, 'files'),
path.join(vaultBasePath, 'images'), pathUtils.joinPath(vaultBasePath, 'images'),
path.join(vaultBasePath, '.attachments') pathUtils.joinPath(vaultBasePath, '.attachments')
]; ];
} }
@@ -79,36 +85,34 @@ export class ResourcePathResolver {
/** /**
* Scan the vault for directories containing images and cache the results * Scan the vault for directories containing images and cache the results
* @param vaultBasePath The base path of the vault * @param vaultBasePath The base path of the vault
* @param fs File system module * @param pathUtils PathUtils instance for path operations
* @param now Current timestamp * @param now Current timestamp
* @returns Array of resource paths found during scan * @returns Array of resource paths found during scan
*/ */
private async scanForResourcePaths(vaultBasePath: string, fs: typeof import('fs'), now: number): Promise<string[]> { private async scanForResourcePaths(vaultBasePath: string, pathUtils: PathUtils, now: number): Promise<string[]> {
const foundResourcePaths: string[] = []; const foundResourcePaths: string[] = [];
try { try {
const vaultContents = fs.readdirSync(vaultBasePath); if (!this.plugin?.app) {
for (const item of vaultContents) { return foundResourcePaths;
const itemPath = path.join(vaultBasePath, item); }
let stat; // Use vault root (empty string) for adapter.list() to get vault-relative paths
try { const vaultContents = await this.plugin.app.vault.adapter.list('');
stat = await fsPromises.stat(itemPath); for (const item of vaultContents.folders) {
} catch (error) { const itemName = item.split('/').pop() || item;
// File might have been deleted between readdirSync and statSync
console.warn(`Export: Unable to stat ${itemPath}:`, (error as Error).message);
continue;
}
if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) { if (!itemName.startsWith('.') && !itemName.startsWith('_')) {
// Check if this directory contains images // Check if this directory contains images
try { try {
const dirContents = fs.readdirSync(itemPath); const dirContents = await this.plugin.app.vault.adapter.list(item);
const hasImages = dirContents.some((file: string) => const hasImages = dirContents.files.some((file: string) =>
/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
); );
if (hasImages) { if (hasImages) {
foundResourcePaths.push(itemPath); // Convert vault-relative path to absolute path for external tools
const absolutePath = pathUtils.joinPath(vaultBasePath, item);
foundResourcePaths.push(absolutePath);
} }
} catch { } catch {
// Ignore directories we can't read // Ignore directories we can't read
+86 -24
View File
@@ -5,6 +5,7 @@
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';
export interface BinaryLocation { export interface BinaryLocation {
/** Full path to the binary */ /** Full path to the binary */
@@ -19,6 +20,7 @@ export class BinaryLocator {
/** /**
* Find the pdf2img binary in the plugin's node_modules directory. * Find the pdf2img binary in the plugin's node_modules directory.
* Handles the complex Obsidian environment where __dirname points to electron.asar. * Handles the complex Obsidian environment where __dirname points to electron.asar.
* Includes Windows-specific executable detection and fallback paths.
* @param plugin The plugin instance for accessing manifest and settings * @param plugin The plugin instance for accessing manifest and settings
* @returns Binary location info * @returns Binary location info
*/ */
@@ -32,32 +34,26 @@ export class BinaryLocator {
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
const pluginDir = possiblePluginDirs.find(dir => { let pluginDir = possiblePluginDirs[0]; // Default fallback
for (const dir of possiblePluginDirs) {
try { try {
const nodeModulesPath = path.join(dir, 'node_modules'); const nodeModulesPath = path.join(dir, 'node_modules');
return require('fs').existsSync(nodeModulesPath); if (plugin?.app) {
const pathUtils = new PathUtils(plugin.app);
if (await pathUtils.fileExists(nodeModulesPath)) {
pluginDir = dir;
break;
}
}
} catch { } catch {
return false; continue;
} }
}) || possiblePluginDirs[0]; // Fallback to first option
const pdf2imgPath = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img');
// Check if the binary exists
const exists = await this.validateBinaryExists(pdf2imgPath);
if (!exists) {
return {
binaryPath: pdf2imgPath,
exists: false,
error: `PDF2IMG binary not found at: ${pdf2imgPath}`
};
} }
return { // Try to find the binary with platform-specific handling
binaryPath: pdf2imgPath, const binaryLocation = await this.findBinaryWithFallbacks(pluginDir, plugin);
exists: true
}; return binaryLocation;
} catch (error: unknown) { } catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
@@ -69,6 +65,64 @@ export class BinaryLocator {
} }
} }
/**
* Find the pdf2img binary with platform-specific extensions and multiple fallback paths.
* @param pluginDir The plugin directory path
* @param plugin The plugin instance for path utilities
* @returns Binary location info
*/
private static async findBinaryWithFallbacks(pluginDir: string, plugin?: obsidianTypstPDFExport): Promise<BinaryLocation> {
// Define Windows-specific executable extensions
const windowsExtensions = process.platform === 'win32' ? ['.cmd', '.bat', '.ps1', '.exe'] : [''];
// Get platform-specific binary name
const baseBinaryName = 'pdf2img';
// Define fallback search paths for different installation methods
const fallbackPaths = [
// Standard npm binary location
path.join(pluginDir, 'node_modules', '.bin'),
// Direct package binary location
path.join(pluginDir, 'node_modules', 'pdf-to-img', 'bin'),
// Windows-specific npm locations
...(process.platform === 'win32' ? [
path.join(process.env.APPDATA || '', 'npm'),
path.join(process.env.LOCALAPPDATA || '', 'npm-cache'),
// Additional Windows global npm locations
path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'nodejs'),
path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'nodejs')
] : [])
];
// Try each fallback path with platform-specific extensions
for (const searchPath of fallbackPaths) {
for (const extension of windowsExtensions) {
const binaryName = baseBinaryName + extension;
const fullBinaryPath = path.join(searchPath, binaryName);
// Check if this binary exists and is accessible
const exists = await this.validateBinaryExists(fullBinaryPath, plugin);
if (exists) {
return {
binaryPath: fullBinaryPath,
exists: true
};
}
}
}
// If no binary found, return the default expected path for error reporting
const defaultPath = path.join(pluginDir, 'node_modules', '.bin', baseBinaryName);
const finalPath = process.platform === 'win32' ? defaultPath + '.cmd' : defaultPath;
return {
binaryPath: finalPath,
exists: false,
error: `PDF2IMG binary not found. Searched in ${fallbackPaths.length} locations with platform-specific extensions. Expected at: ${finalPath}`
};
}
/** /**
* Get possible plugin directory locations based on different Obsidian environments. * Get possible plugin directory locations based on different Obsidian environments.
* @param plugin Plugin instance * @param plugin Plugin instance
@@ -83,19 +137,27 @@ export class BinaryLocator {
// 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((plugin.app.vault.adapter as unknown as { basePath: string }).basePath, plugin.manifest.dir!)] : []) ...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : [])
]; ];
} }
/** /**
* Validate that a binary exists and is accessible. * Validate that a binary exists and is accessible.
* @param binaryPath Full path to the binary * @param binaryPath Full path to the binary
* @param plugin Plugin instance for PathUtils
* @returns True if binary exists, false otherwise * @returns True if binary exists, false otherwise
*/ */
private static async validateBinaryExists(binaryPath: string): Promise<boolean> { private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> {
try { try {
const fs2 = require('fs'); if (!plugin?.app) {
return fs2.existsSync(binaryPath); // This should not happen in normal plugin operation, but provide fallback
const fs = require('fs').promises;
await fs.access(binaryPath);
return true;
}
const pathUtils = new PathUtils(plugin.app);
return await pathUtils.fileExists(binaryPath);
} catch { } catch {
return false; return false;
} }
+196 -35
View File
@@ -3,8 +3,9 @@
* Handles filename pattern matching when pdf2img generates files with different names. * Handles filename pattern matching when pdf2img generates files with different names.
*/ */
import * as fs from 'fs/promises';
import * as path from 'path'; import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
export interface FileDiscoveryResult { export interface FileDiscoveryResult {
/** Path to the discovered file */ /** Path to the discovered file */
@@ -16,61 +17,188 @@ export interface FileDiscoveryResult {
} }
export class FileDiscovery { export class FileDiscovery {
/** Supported image extensions for PDF conversion output */
private static readonly SUPPORTED_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff'];
/** /**
* Find the generated image file in the output directory. * Find the generated image file in the output directory.
* Handles cases where pdf2img sanitizes filenames differently than expected. * Handles cases where pdf2img sanitizes filenames differently than expected.
* @param outputDir Directory where files were generated * @param outputDir Directory where files were generated
* @param expectedFileName Expected output filename * @param expectedFileName Expected output filename
* @param plugin Plugin instance for PathUtils
* @returns Discovery result with actual file path * @returns Discovery result with actual file path
*/ */
public static async findGeneratedFile( public static async findGeneratedFile(
outputDir: string, outputDir: string,
expectedFileName: string expectedFileName: string,
plugin?: obsidianTypstPDFExport
): Promise<FileDiscoveryResult> { ): Promise<FileDiscoveryResult> {
const expectedOutputPath = path.join(outputDir, expectedFileName); if (!plugin?.app) {
// Fallback to path for external tool output directories
const expectedOutputPath = path.join(outputDir, expectedFileName);
const fs = require('fs').promises;
try {
await fs.access(expectedOutputPath);
return {
filePath: expectedOutputPath,
found: true
};
} catch {
return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath);
}
}
const pathUtils = new PathUtils(plugin.app);
const expectedOutputPath = pathUtils.joinPath(outputDir, expectedFileName);
// Check if the expected output file exists first // Check if the expected output file exists first
try { try {
await fs.access(expectedOutputPath); if (await pathUtils.fileExists(expectedOutputPath)) {
return { return {
filePath: expectedOutputPath, filePath: expectedOutputPath,
found: true found: true
}; };
}
} catch { } catch {
// File not found with expected name, try to find alternatives // Continue to alternative search
return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath);
} }
// File not found with expected name, try to find alternatives
return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath, plugin);
} }
/** /**
* Find alternative files when the expected filename doesn't match. * Find alternative files when the expected filename doesn't match (using vault.adapter).
* @param outputDir Output directory to search * @param outputDir Output directory to search
* @param expectedFileName Expected filename for pattern matching * @param expectedFileName Expected filename for pattern matching
* @param expectedOutputPath Full expected output path * @param expectedOutputPath Full expected output path
* @param plugin Plugin instance for vault access
* @returns Discovery result with alternative file if found * @returns Discovery result with alternative file if found
*/ */
private static async findAlternativeFile( private static async findAlternativeFile(
outputDir: string, outputDir: string,
expectedFileName: string, expectedFileName: string,
expectedOutputPath: string expectedOutputPath: string,
plugin: obsidianTypstPDFExport
): Promise<FileDiscoveryResult> { ): Promise<FileDiscoveryResult> {
try { try {
// Debug: List what files are actually in the output directory const pathUtils = new PathUtils(plugin.app);
const files = await fs.readdir(outputDir);
// Look for any PNG files that might match // Check if outputDir is inside the vault
const pngFiles = files.filter(f => f.endsWith('.png')); let vaultPath = '';
if (pngFiles.length === 0) { try {
vaultPath = pathUtils.getVaultPath();
} catch {
// If vault path unavailable, treat all paths as external
vaultPath = '';
}
let isVaultRelative = false;
let vaultRelativeDir = outputDir;
if (vaultPath) {
// Compute relative path from vault root
const relativePath = path.relative(vaultPath, outputDir);
// Path is inside vault if it doesn't start with '..' or path separator
isVaultRelative = !relativePath.startsWith('..') && !path.isAbsolute(relativePath);
if (isVaultRelative) {
vaultRelativeDir = relativePath;
}
}
let files: string[];
if (isVaultRelative) {
// Use adapter for vault-relative paths
const dirList = await plugin.app.vault.adapter.list(vaultRelativeDir);
files = dirList.files.map(f => path.basename(f));
} else {
// Use filesystem fallback for absolute/external paths
const fs = require('fs').promises;
files = await fs.readdir(outputDir);
}
// Look for any image files that might match
const imageFiles = files.filter(f =>
this.SUPPORTED_IMAGE_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))
);
if (imageFiles.length === 0) {
return { return {
filePath: '', filePath: '',
found: false, found: false,
error: `No PNG files found in output directory: ${outputDir}` error: `No image files found in output directory: ${outputDir}. Supported formats: ${this.SUPPORTED_IMAGE_EXTENSIONS.join(', ')}`
}; };
} }
// Try to find a file that matches the pattern (with or without exact name) // Try to find a file that matches the pattern (with or without exact name)
// pdf2img might sanitize filenames differently // pdf2img might sanitize filenames differently
const matchingFile = this.matchFilePattern(pngFiles, expectedFileName); const matchingFile = this.matchFilePattern(imageFiles, expectedFileName);
if (matchingFile) {
const actualOutputPath = pathUtils.joinPath(outputDir, matchingFile);
// Final check if we found an alternative file
if (await pathUtils.fileExists(actualOutputPath)) {
return {
filePath: actualOutputPath,
found: true
};
} else {
return {
filePath: '',
found: false,
error: `Alternative file not accessible: ${actualOutputPath}`
};
}
} else {
return {
filePath: '',
found: false,
error: `Generated image file not found: ${expectedOutputPath}. Available files: ${imageFiles.join(', ')}`
};
}
} catch (listError: unknown) {
console.error(`Failed to list output directory:`, listError);
const errorMessage = listError instanceof Error ? listError.message : String(listError);
return {
filePath: '',
found: false,
error: `Failed to search output directory: ${errorMessage}`
};
}
}
/**
* Find alternative files when the expected filename doesn't match (fs fallback).
* @param outputDir Output directory to search
* @param expectedFileName Expected filename for pattern matching
* @param expectedOutputPath Full expected output path
* @returns Discovery result with alternative file if found
*/
private static async findAlternativeFileFs(
outputDir: string,
expectedFileName: string,
expectedOutputPath: string
): Promise<FileDiscoveryResult> {
try {
const fs = require('fs').promises;
// Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir);
// Look for any image files that might match
const imageFiles = files.filter((f: string) =>
this.SUPPORTED_IMAGE_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))
);
if (imageFiles.length === 0) {
return {
filePath: '',
found: false,
error: `No image files found in output directory: ${outputDir}. Supported formats: ${this.SUPPORTED_IMAGE_EXTENSIONS.join(', ')}`
};
}
// Try to find a file that matches the pattern (with or without exact name)
// pdf2img might sanitize filenames differently
const matchingFile = this.matchFilePattern(imageFiles, expectedFileName);
if (matchingFile) { if (matchingFile) {
const actualOutputPath = path.join(outputDir, matchingFile); const actualOutputPath = path.join(outputDir, matchingFile);
@@ -93,7 +221,7 @@ export class FileDiscovery {
return { return {
filePath: '', filePath: '',
found: false, found: false,
error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}` error: `Generated image file not found: ${expectedOutputPath}. Available files: ${imageFiles.join(', ')}`
}; };
} }
@@ -109,31 +237,55 @@ export class FileDiscovery {
} }
/** /**
* Match files against expected filename patterns. * Match files against expected filename patterns using multiple strategies.
* Handles filename sanitization that pdf2img might apply. * Handles filename sanitization that pdf2img might apply and supports multiple image formats.
* @param files Array of available filenames * @param files Array of available filenames
* @param expectedFileName Expected filename pattern * @param expectedFileName Expected filename pattern
* @returns Matching filename or null if no match found * @returns Matching filename or null if no match found
*/ */
private static matchFilePattern(files: string[], expectedFileName: string): string | null { private static matchFilePattern(files: string[], expectedFileName: string): string | null {
// Try exact match first const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName));
// Strategy 1: Exact match
const exactMatch = files.find(f => f === expectedFileName); const exactMatch = files.find(f => f === expectedFileName);
if (exactMatch) { if (exactMatch) {
return exactMatch; return exactMatch;
} }
// Try partial match by removing special characters // Strategy 2: Base name match with any supported extension
const simplifiedExpected = this.sanitizeFilename(expectedFileName); const baseNameMatch = files.find(f => {
const matchingFile = files.find(f => { const fileBase = path.basename(f, path.extname(f));
const simplifiedActual = this.sanitizeFilename(f); return fileBase === expectedBase;
return simplifiedActual === simplifiedExpected;
}); });
if (baseNameMatch) {
if (matchingFile) { return baseNameMatch;
return matchingFile;
} }
// Fallback to first PNG file if no pattern matches // Strategy 3: Sanitized pattern match (remove special characters)
const simplifiedExpected = this.sanitizeFilename(expectedBase);
const sanitizedMatch = files.find(f => {
const fileBase = path.basename(f, path.extname(f));
const simplifiedActual = this.sanitizeFilename(fileBase);
return simplifiedActual === simplifiedExpected;
});
if (sanitizedMatch) {
return sanitizedMatch;
}
// Strategy 4: Fuzzy match for pdf2img output patterns (filename-1.ext, filename-page1.ext, etc.)
const fuzzyMatch = files.find(f => {
const fileBase = path.basename(f, path.extname(f));
// Remove common pdf2img suffixes like "-1", "-page1", etc.
const cleanedFileBase = fileBase.replace(/[-_](page)?\d+$/i, '');
const cleanedExpectedBase = expectedBase.replace(/[-_](page)?\d+$/i, '');
return cleanedFileBase === cleanedExpectedBase ||
this.sanitizeFilename(cleanedFileBase) === this.sanitizeFilename(cleanedExpectedBase);
});
if (fuzzyMatch) {
return fuzzyMatch;
}
// Strategy 5: Fallback to first available image file if no pattern matches
return files.length > 0 ? files[0] : null; return files.length > 0 ? files[0] : null;
} }
@@ -148,10 +300,10 @@ export class FileDiscovery {
/** /**
* Generate expected output filename for pdf2img conversion. * Generate expected output filename for pdf2img conversion.
* pdf2img uses the pattern: "filename-1.png" for first page. * pdf2img uses the pattern: "filename-1.ext" for first page.
* @param pdfBaseName Base name of the PDF file (without extension) * @param pdfBaseName Base name of the PDF file (without extension)
* @param pageNumber Page number (1-based) * @param pageNumber Page number (1-based)
* @param format Output format ('png' or 'jpeg') * @param format Output format (defaults to 'png', supports any image format)
* @returns Expected output filename * @returns Expected output filename
*/ */
public static generateExpectedFilename( public static generateExpectedFilename(
@@ -159,6 +311,15 @@ export class FileDiscovery {
pageNumber: number = 1, pageNumber: number = 1,
format: string = 'png' format: string = 'png'
): string { ): string {
return `${pdfBaseName}-${pageNumber}.${format}`; // Validate format is supported
const formatExtension = format.toLowerCase().startsWith('.') ? format.substring(1) : format.toLowerCase();
const supportedFormats = this.SUPPORTED_IMAGE_EXTENSIONS.map(ext => ext.substring(1));
if (!supportedFormats.includes(formatExtension)) {
console.warn(`Unsupported image format '${format}', falling back to PNG`);
return `${pdfBaseName}-${pageNumber}.png`;
}
return `${pdfBaseName}-${pageNumber}.${formatExtension}`;
} }
} }
+46 -6
View File
@@ -3,8 +3,9 @@
* Handles format conversion, quality management, and dimension detection. * Handles format conversion, quality management, and dimension detection.
*/ */
import * as fs from 'fs/promises';
import * as path from 'path'; import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
export interface ImageOptimizationOptions { export interface ImageOptimizationOptions {
/** Output format (default: 'png') */ /** Output format (default: 'png') */
@@ -183,7 +184,8 @@ export class ImageOptimizer {
inputImagePath: string, inputImagePath: string,
outputDir: string, outputDir: string,
baseFileName: string, baseFileName: string,
options: ImageOptimizationOptions = {} options: ImageOptimizationOptions = {},
plugin?: obsidianTypstPDFExport
): Promise<ImageOptimizationResult> { ): Promise<ImageOptimizationResult> {
try { try {
const opts = { const opts = {
@@ -193,7 +195,13 @@ export class ImageOptimizer {
// Generate final output path // Generate final output path
const finalOutputFileName = `${baseFileName}_preview.${opts.format}`; const finalOutputFileName = `${baseFileName}_preview.${opts.format}`;
const finalOutputPath = path.join(outputDir, finalOutputFileName); let finalOutputPath: string;
if (plugin?.app) {
const pathUtils = new PathUtils(plugin.app);
finalOutputPath = pathUtils.joinPath(outputDir, finalOutputFileName);
} else {
finalOutputPath = path.join(outputDir, finalOutputFileName);
}
let actualImagePath = inputImagePath; let actualImagePath = inputImagePath;
@@ -209,7 +217,25 @@ export class ImageOptimizer {
if (conversionResult.success) { if (conversionResult.success) {
// Clean up the original PNG if conversion succeeded // Clean up the original PNG if conversion succeeded
try { try {
await fs.unlink(inputImagePath); if (plugin?.app) {
// Convert absolute path to vault-relative path for adapter.remove()
const pathUtils = new PathUtils(plugin.app);
const vaultBasePath = pathUtils.getVaultPath();
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);
} else {
const fs = require('fs').promises;
await fs.unlink(inputImagePath);
}
} catch (unlinkError) { } catch (unlinkError) {
console.warn(`Could not remove original PNG: ${unlinkError}`); console.warn(`Could not remove original PNG: ${unlinkError}`);
} }
@@ -218,12 +244,26 @@ export class ImageOptimizer {
console.warn(`ImageMagick not available for JPEG conversion, keeping PNG format: ${conversionResult.error}`); console.warn(`ImageMagick not available for JPEG conversion, keeping PNG format: ${conversionResult.error}`);
// 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');
await fs.rename(inputImagePath, pngFinalPath); if (plugin?.app) {
const content = await plugin.app.vault.adapter.readBinary(inputImagePath);
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content);
await plugin.app.vault.adapter.remove(inputImagePath);
} else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, pngFinalPath);
}
actualImagePath = pngFinalPath; actualImagePath = pngFinalPath;
} }
} else { } else {
// Keep as PNG, just rename to final location // Keep as PNG, just rename to final location
await fs.rename(inputImagePath, finalOutputPath); if (plugin?.app) {
const content = await plugin.app.vault.adapter.readBinary(inputImagePath);
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content);
await plugin.app.vault.adapter.remove(inputImagePath);
} else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, finalOutputPath);
}
actualImagePath = finalOutputPath; actualImagePath = finalOutputPath;
} }
+125
View File
@@ -0,0 +1,125 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
// ABOUTME: Handles vault paths, plugin directories, and file operations
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
import type { App, PluginManifest } from 'obsidian';
export class PathUtils {
constructor(private app: App) {}
/**
* Get vault base path safely with FileSystemAdapter check
*/
getVaultPath(): string {
const adapter = this.app.vault.adapter;
if (!(adapter instanceof FileSystemAdapter)) {
new Notice('This plugin requires desktop Obsidian');
throw new Error('FileSystemAdapter not available - desktop Obsidian required');
}
return adapter.getBasePath();
}
/**
* Get plugin directory path
*/
getPluginDir(pluginManifest: PluginManifest): string {
return normalizePath(pluginManifest.dir || '');
}
/**
* Join path segments with normalizePath
*/
joinPath(...segments: string[]): string {
// Filter out empty segments
const filtered = segments.filter(s => s);
const joined = filtered.join('/');
return normalizePath(joined);
}
/**
* Ensure directory exists, create if necessary
*/
async ensureDir(path: string): Promise<void> {
const normalizedPath = normalizePath(path);
try {
const exists = await this.app.vault.adapter.exists(normalizedPath);
if (!exists) {
await this.app.vault.adapter.mkdir(normalizedPath);
}
} catch (error) {
new Notice(`Failed to create directory: ${normalizedPath}`);
throw error;
}
}
/**
* Clean up directory contents (files only, like current TempDirectoryManager)
*/
async cleanupDir(path: string): Promise<boolean> {
const normalizedPath = normalizePath(path);
try {
const exists = await this.app.vault.adapter.exists(normalizedPath);
if (exists && this.app.vault.adapter instanceof FileSystemAdapter) {
const list = await this.app.vault.adapter.list(normalizedPath);
// Remove only files, not subdirectories (matching current pattern)
for (const file of list.files) {
await this.app.vault.adapter.remove(file);
}
}
return true;
} catch (error) {
console.warn(`Failed to cleanup directory ${normalizedPath}:`, error);
return false;
}
}
/**
* Check if file or directory exists
* Handles both vault-relative paths and absolute filesystem paths
*/
async fileExists(path: string): Promise<boolean> {
try {
// First, try as vault-relative path
const normalizedPath = normalizePath(path);
const exists = await this.app.vault.adapter.exists(normalizedPath);
if (exists) {
return true;
}
} catch {
// If vault.adapter fails, path might be absolute
}
// If path is absolute, convert to vault-relative and try again
const vaultBasePath = this.getVaultPath();
if (path.startsWith(vaultBasePath)) {
try {
// Remove vault base path and leading separator
let relativePath = path.substring(vaultBasePath.length);
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.substring(1);
}
const normalizedRelativePath = normalizePath(relativePath);
return await this.app.vault.adapter.exists(normalizedRelativePath);
} catch {
return false;
}
}
// For paths outside vault, use fs fallback (needed for external file processing)
const isAbsolutePath = path.startsWith('/') || // Unix absolute
/^[a-zA-Z]:[/\\]/.test(path) || // Windows drive letter (C:\ or C:/)
path.startsWith('\\\\'); // Windows UNC path (\\server\share)
if (isAbsolutePath) {
try {
const fs = require('fs').promises;
await fs.access(path);
return true;
} catch {
return false;
}
}
return false;
}
}
+33 -27
View File
@@ -1,8 +1,9 @@
/** // ABOUTME: Manages temporary directories for export operations
* Manages temporary directories for export operations // ABOUTME: Uses normalizePath for cross-platform path operations
*/
import { PLUGIN_DIRS } from './constants'; import { PLUGIN_DIRS } from './constants';
import { normalizePath } from 'obsidian';
import type { App } from 'obsidian';
export interface TempDirectoryOptions { export interface TempDirectoryOptions {
/** Base path for the vault */ /** Base path for the vault */
@@ -11,26 +12,28 @@ export interface TempDirectoryOptions {
configDir: string; configDir: string;
/** Plugin directory name (defaults to 'typst-pdf-export') */ /** Plugin directory name (defaults to 'typst-pdf-export') */
pluginName?: string; pluginName?: string;
/** App instance for vault.adapter operations */
app: App;
} }
export class TempDirectoryManager { export class TempDirectoryManager {
private readonly fs = require('fs');
private readonly path = require('path');
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;
constructor(options: TempDirectoryOptions) { constructor(options: TempDirectoryOptions) {
this.vaultPath = options.vaultPath; this.vaultPath = options.vaultPath;
this.configDir = options.configDir; this.configDir = options.configDir;
this.pluginName = options.pluginName || 'typst-pdf-export'; this.pluginName = options.pluginName || 'typst-pdf-export';
this.app = options.app;
} }
/** /**
* Get the plugin directory path * Get the plugin directory path
*/ */
private getPluginDir(): string { private getPluginDir(): string {
return this.path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName); return normalizePath([this.vaultPath, this.configDir, 'plugins', this.pluginName].join('/'));
} }
/** /**
@@ -38,17 +41,18 @@ export class TempDirectoryManager {
*/ */
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 this.path.join(this.getPluginDir(), dirName); return normalizePath([this.getPluginDir(), dirName].join('/'));
} }
/** /**
* Ensure a temp directory exists, creating it if necessary * Ensure a temp directory exists, creating it if necessary
*/ */
public ensureTempDir(type: 'images' | 'pandoc'): string { public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
const tempDir = this.getTempDir(type); const tempDir = this.getTempDir(type);
if (!this.fs.existsSync(tempDir)) { const exists = await this.app.vault.adapter.exists(tempDir);
this.fs.mkdirSync(tempDir, { recursive: true }); if (!exists) {
await this.app.vault.adapter.mkdir(tempDir);
} }
return tempDir; return tempDir;
@@ -57,40 +61,40 @@ export class TempDirectoryManager {
/** /**
* Clean up a specific temp directory * Clean up a specific temp directory
*/ */
public cleanupTempDir(type: 'images' | 'pandoc'): boolean { public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
const tempDir = this.getTempDir(type); const tempDir = this.getTempDir(type);
try { try {
if (this.fs.existsSync(tempDir)) { const exists = await this.app.vault.adapter.exists(tempDir);
const files = this.fs.readdirSync(tempDir); if (exists) {
for (const file of files) { const list = await this.app.vault.adapter.list(tempDir);
this.fs.unlinkSync(this.path.join(tempDir, file)); // Remove only files, not subdirectories (matching current pattern)
for (const file of list.files) {
await this.app.vault.adapter.remove(file);
} }
return true;
} }
return true;
} catch (error) { } catch (error) {
console.warn(`Export: Failed to clean up ${type === 'images' ? 'temp-images' : 'temp-pandoc'} directory:`, error); console.warn(`Export: Failed to clean up ${type === 'images' ? 'temp-images' : 'temp-pandoc'} directory:`, error);
return false; return false;
} }
return true;
} }
/** /**
* Clean up all temp directories * Clean up all temp directories
*/ */
public cleanupAllTempDirs(): { images: boolean; pandoc: boolean } { public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> {
return { return {
images: this.cleanupTempDir('images'), images: await this.cleanupTempDir('images'),
pandoc: this.cleanupTempDir('pandoc') pandoc: await this.cleanupTempDir('pandoc')
}; };
} }
/** /**
* Static helper to create manager from vault path and configDir * Static helper to create manager from vault path and configDir
*/ */
public static create(vaultPath: string, configDir: string, pluginName?: string): TempDirectoryManager { public static create(vaultPath: string, configDir: string, pluginName: string | undefined, app: App): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, configDir, pluginName }); return new TempDirectoryManager({ vaultPath, configDir, pluginName, app });
} }
/** /**
@@ -98,10 +102,12 @@ export class TempDirectoryManager {
*/ */
public isPluginTempDir(dirPath: string): boolean { public isPluginTempDir(dirPath: string): boolean {
const pluginDir = this.getPluginDir(); const pluginDir = this.getPluginDir();
const normalizedPath = this.path.resolve(dirPath); const normalizedDirPath = normalizePath(dirPath);
const normalizedPluginDir = this.path.resolve(pluginDir); const normalizedPluginDir = normalizePath(pluginDir);
const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/'));
const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/'));
return normalizedPath.startsWith(normalizedPluginDir) && return normalizedDirPath.startsWith(tempImagesDir) ||
(dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC)); normalizedDirPath.startsWith(tempPandocDir);
} }
} }
+37 -20
View File
@@ -7,11 +7,15 @@ 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 * as path from 'path'; import * as path from 'path';
import * as fs from 'fs';
export class EmbedProcessor { export class EmbedProcessor {
constructor(private plugin: obsidianTypstPDFExport) {} private readonly pathUtils: PathUtils;
constructor(private plugin: obsidianTypstPDFExport) {
this.pathUtils = new PathUtils(plugin.app);
}
/** /**
* Process PDF embeds - convert PDF pages to images for inclusion * Process PDF embeds - convert PDF pages to images for inclusion
@@ -126,9 +130,11 @@ export class EmbedProcessor {
// Try each possible path until we find one that exists // Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) { for (const possiblePath of possiblePaths) {
try { try {
await fs.promises.access(possiblePath); const exists = await this.pathUtils.fileExists(possiblePath);
fullImagePath = possiblePath; if (exists) {
break; fullImagePath = possiblePath;
break;
}
} catch { } catch {
// File doesn't exist, continue to next path // File doesn't exist, continue to next path
} }
@@ -150,10 +156,10 @@ 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 = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images'); const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); await this.pathUtils.ensureDir(vaultTempImagesDir);
const convertedImagePath = path.join(vaultTempImagesDir, pngFileName); const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
const { exec } = require('child_process'); const { exec } = require('child_process');
const util = require('util'); const util = require('util');
@@ -303,8 +309,10 @@ export class EmbedProcessor {
// Convert to full filesystem path // Convert to full filesystem path
const fullPath = path.resolve(vaultBasePath, resolvedFile.path); const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try { try {
await fs.promises.access(fullPath); const exists = await this.pathUtils.fileExists(fullPath);
return fullPath; if (exists) {
return fullPath;
}
} catch { } catch {
// File exists in metadata but not on filesystem, continue to fallbacks // File exists in metadata but not on filesystem, continue to fallbacks
} }
@@ -322,8 +330,10 @@ export class EmbedProcessor {
// Try each possible path until we find one that exists // Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) { for (const possiblePath of possiblePaths) {
try { try {
await fs.promises.access(possiblePath); const exists = await this.pathUtils.fileExists(possiblePath);
return possiblePath; if (exists) {
return possiblePath;
}
} catch { } catch {
// File doesn't exist, continue to next path // File doesn't exist, continue to next path
} }
@@ -350,8 +360,10 @@ export class EmbedProcessor {
// Convert to full filesystem path // Convert to full filesystem path
const fullPath = path.resolve(vaultBasePath, resolvedFile.path); const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try { try {
await fs.promises.access(fullPath); const exists = await this.pathUtils.fileExists(fullPath);
return fullPath; if (exists) {
return fullPath;
}
} catch { } catch {
// File exists in metadata but not on filesystem, continue to fallbacks // File exists in metadata but not on filesystem, continue to fallbacks
} }
@@ -371,8 +383,10 @@ export class EmbedProcessor {
// Try each possible path until we find one that exists // Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) { for (const possiblePath of possiblePaths) {
try { try {
await fs.promises.access(possiblePath); const exists = await this.pathUtils.fileExists(possiblePath);
return possiblePath; if (exists) {
return possiblePath;
}
} catch { } catch {
// File doesn't exist, continue to next path // File doesn't exist, continue to next path
} }
@@ -396,8 +410,8 @@ 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 = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images'); const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); await this.pathUtils.ensureDir(vaultTempImagesDir);
// 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
@@ -406,8 +420,11 @@ export class EmbedProcessor {
.replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores .replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores
const imageFileName = `${sanitizedBaseName}_preview.png`; const imageFileName = `${sanitizedBaseName}_preview.png`;
const vaultImagePath = path.join(vaultTempImagesDir, imageFileName); const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName);
await fs.promises.copyFile(imagePath, vaultImagePath);
// Copy file using vault adapter
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath);
await this.plugin.app.vault.adapter.writeBinary(vaultImagePath, 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);
+17 -8
View File
@@ -11,10 +11,14 @@ import { ModalSettingsHelper } from '../core/ModalSettingsHelper';
import { MarkdownPreprocessor } from '../converters/MarkdownPreprocessor'; import { MarkdownPreprocessor } from '../converters/MarkdownPreprocessor';
import { TempDirectoryManager } from '../core/TempDirectoryManager'; import { TempDirectoryManager } from '../core/TempDirectoryManager';
import { ExportErrorHandler } from '../core/ExportErrorHandler'; import { ExportErrorHandler } from '../core/ExportErrorHandler';
import * as path from 'path'; import { PathUtils } from '../core/PathUtils';
export class ExportOrchestrator { export class ExportOrchestrator {
constructor(private plugin: obsidianTypstPDFExport) {} private readonly pathUtils: PathUtils;
constructor(private plugin: obsidianTypstPDFExport) {
this.pathUtils = new PathUtils(plugin.app);
}
/** /**
* Export a file with default configuration * Export a file with default configuration
@@ -132,16 +136,21 @@ export class ExportOrchestrator {
* Export a file with specific configuration * Export a file with specific configuration
*/ */
async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> { async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath; const vaultPath = this.pathUtils.getVaultPath();
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!); const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
// Create controller for this export (allows cancellation) // Create controller for this export (allows cancellation)
this.plugin.currentExportController = new AbortController(); this.plugin.currentExportController = new AbortController();
try { try {
// Create temp directory for conversion // Create temp directory for conversion
const tempManager = new TempDirectoryManager({ vaultPath: vaultPath, configDir: this.plugin.app.vault.configDir }); const tempManager = new TempDirectoryManager({
const tempDir = tempManager.ensureTempDir('pandoc'); vaultPath: vaultPath,
configDir: this.plugin.app.vault.configDir,
app: this.plugin.app,
pluginName: this.plugin.manifest.id
});
const tempDir = await tempManager.ensureTempDir('pandoc');
// Load file content // Load file content
const content = await this.plugin.app.vault.read(file); const content = await this.plugin.app.vault.read(file);
@@ -245,8 +254,8 @@ export class ExportOrchestrator {
// Clean up temporary directories // Clean up temporary directories
try { try {
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir); const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, this.plugin.manifest.id, this.plugin.app);
cleanupManager.cleanupAllTempDirs(); await cleanupManager.cleanupAllTempDirs();
} catch (cleanupError) { } catch (cleanupError) {
console.warn('Export: Failed to clean up temporary directories:', cleanupError); console.warn('Export: Failed to clean up temporary directories:', cleanupError);
} }
+141 -22
View File
@@ -6,7 +6,7 @@
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';
import * as path from 'path'; import { PathUtils } from '../core/PathUtils';
export class FontManager { export class FontManager {
constructor(private plugin: obsidianTypstPDFExport) {} constructor(private plugin: obsidianTypstPDFExport) {}
@@ -22,12 +22,17 @@ export class FontManager {
// 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) => {
// Build platform-specific environment with enhanced PATH
const pathValue = this.buildPlatformSpecificPATH();
const enhancedEnv = {
...process.env,
PATH: pathValue,
Path: pathValue
};
const typstProcess = spawn(typstPath, ['fonts'], { const typstProcess = spawn(typstPath, ['fonts'], {
stdio: ['pipe', 'pipe', 'pipe'], stdio: ['pipe', 'pipe', 'pipe'],
env: { env: enhancedEnv
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
}
}); });
let output = ''; let output = '';
@@ -64,10 +69,14 @@ export class FontManager {
const cacheData = { const cacheData = {
fonts: fonts, fonts: fonts,
timestamp: Date.now(), timestamp: Date.now(),
typstPath: typstPath typstPath: typstPath,
platform: process.platform
}; };
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json'); const pathUtils = new PathUtils(this.plugin.app);
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
// Use vault-relative path for adapter operations
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
await this.plugin.app.vault.adapter.write(fontsCachePath, await this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2)); JSON.stringify(cacheData, null, 2));
} catch (error) { } catch (error) {
@@ -83,39 +92,74 @@ export class FontManager {
fonts: fallbackFonts, fonts: fallbackFonts,
timestamp: Date.now(), timestamp: Date.now(),
typstPath: 'fallback', typstPath: 'fallback',
error: error.message platform: process.platform,
error: error instanceof Error ? error.message : String(error)
}; };
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json'); const pathUtils = new PathUtils(this.plugin.app);
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
// Use vault-relative path for adapter operations
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
await this.plugin.app.vault.adapter.write(fontsCachePath, await this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2)); JSON.stringify(cacheData, null, 2));
} }
} }
/** /**
* Get cached fonts list * Get cached fonts list with improved validation and error recovery
*/ */
async getCachedFonts(): Promise<string[]> { async getCachedFonts(): Promise<string[]> {
try { try {
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json'); const pathUtils = new PathUtils(this.plugin.app);
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
// Use vault-relative path for adapter operations
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath); const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);
const cacheData = JSON.parse(cacheContent);
// Check if cache is older than 24 hours or typst path changed let cacheData;
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000; try {
const resolvedTypstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst'); cacheData = JSON.parse(cacheContent);
const pathChanged = cacheData.typstPath !== resolvedTypstPath; } catch (parseError) {
console.error('Corrupted fonts cache file, regenerating:', parseError);
if (isStale || pathChanged) { // Remove corrupted cache and regenerate
// Refresh cache in background await this.plugin.app.vault.adapter.remove(fontsCachePath);
this.cacheAvailableFonts(); await this.cacheAvailableFonts();
return [...FALLBACK_FONTS];
} }
return cacheData.fonts || []; // Validate cache structure
if (!cacheData || typeof cacheData !== 'object' || !Array.isArray(cacheData.fonts)) {
console.warn('Invalid fonts cache structure, regenerating');
await this.plugin.app.vault.adapter.remove(fontsCachePath);
await this.cacheAvailableFonts();
return [...FALLBACK_FONTS];
}
// Check if cache needs refresh
const isStale = Date.now() - (cacheData.timestamp || 0) > 24 * 60 * 60 * 1000;
const resolvedTypstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
const platformChanged = cacheData.platform !== process.platform;
if (isStale || pathChanged || platformChanged) {
// Refresh cache in background
this.cacheAvailableFonts().catch(error => {
console.error('Background font cache refresh failed:', error);
});
}
// Validate fonts array contains valid strings
const validFonts = cacheData.fonts.filter((font: unknown) =>
typeof font === 'string' && font.trim().length > 0
);
return validFonts.length > 0 ? validFonts : [...FALLBACK_FONTS];
} catch (error) { } catch (error) {
console.error('Failed to read fonts cache:', error); console.error('Failed to read fonts cache:', error);
// Try to recreate cache // Try to recreate cache
await this.cacheAvailableFonts(); this.cacheAvailableFonts().catch(cacheError => {
console.error('Failed to recreate fonts cache:', cacheError);
});
// Return fallback fonts // Return fallback fonts
return [...FALLBACK_FONTS]; return [...FALLBACK_FONTS];
@@ -128,4 +172,79 @@ export class FontManager {
async getAvailableFonts(): Promise<string[]> { async getAvailableFonts(): Promise<string[]> {
return await this.getCachedFonts(); return await this.getCachedFonts();
} }
/**
* Build platform-specific PATH environment variable for font discovery
* @private
*/
private buildPlatformSpecificPATH(): string {
const currentPath = process.env.PATH || '';
const pathSeparator = process.platform === 'win32' ? ';' : ':';
// Helper function to expand tilde paths
const expandTildePath = (path: string): string => {
if (path.startsWith('~')) {
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
return path.replace('~', homeDir);
}
return path;
};
// Platform-specific common installation paths
let additionalPaths: string[] = [];
switch (process.platform) {
case 'darwin': // macOS
additionalPaths = [
'/opt/homebrew/bin',
'/usr/local/bin',
'/usr/bin',
'/bin',
'/opt/local/bin', // MacPorts
'/sw/bin' // Fink
];
break;
case 'linux':
additionalPaths = [
'/usr/local/bin',
'/usr/bin',
'/bin',
'/opt/bin',
'/snap/bin', // Snap packages
'~/.cargo/bin', // Rust/Cargo installations
'~/.local/bin' // User local installations
];
break;
case 'win32': // Windows
additionalPaths = [
'C:\\Program Files\\Typst',
'C:\\Program Files (x86)\\Typst',
process.env.LOCALAPPDATA ? `${process.env.LOCALAPPDATA}\\Programs\\Typst` : '',
process.env.APPDATA ? `${process.env.APPDATA}\\Typst` : '',
'C:\\tools\\typst', // Chocolatey common path
process.env.USERPROFILE ? `${process.env.USERPROFILE}\\.cargo\\bin` : ''
].filter(path => path.length > 0);
break;
default:
// Fallback for other platforms
additionalPaths = ['/usr/local/bin', '/usr/bin', '/bin'];
}
// Expand tilde paths and filter empty strings
const expandedPaths = additionalPaths
.map(expandTildePath)
.filter(path => path.length > 0);
// Split current PATH and combine with additional paths
const currentPaths = currentPath.split(pathSeparator).filter(path => path.length > 0);
const allPaths = [...expandedPaths, ...currentPaths];
// Remove duplicates while preserving order
const uniquePaths = [...new Set(allPaths)];
return uniquePaths.join(pathSeparator);
}
} }
+12 -26
View File
@@ -6,11 +6,15 @@
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';
import { PathUtils } from '../core/PathUtils';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs';
export class PathResolver { export class PathResolver {
constructor(private plugin: obsidianTypstPDFExport) {} private readonly pathUtils: PathUtils;
constructor(private plugin: obsidianTypstPDFExport) {
this.pathUtils = new PathUtils(plugin.app);
}
/** /**
* Resolve an executable path, handling empty settings by falling back to system search * Resolve an executable path, handling empty settings by falling back to system search
@@ -57,20 +61,11 @@ export class PathResolver {
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.plugin.app.vault.adapter as unknown as { basePath: string }).basePath; const vaultPath = this.pathUtils.getVaultPath();
const outputDir = path.join(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
try { await this.pathUtils.ensureDir(outputDir);
await fs.promises.access(outputDir);
} catch {
// Directory doesn't exist, create it
try {
await fs.promises.mkdir(outputDir, { recursive: true });
} catch (error) {
throw new Error(`Failed to create output directory ${outputDir}: ${error.message}`);
}
}
// Preserve folder structure if configured // Preserve folder structure if configured
let relativePath = ''; let relativePath = '';
@@ -78,17 +73,8 @@ 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 = path.join(outputDir, relativePath); const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath);
try { await this.pathUtils.ensureDir(fullOutputDir);
await fs.promises.access(fullOutputDir);
} catch {
// Directory doesn't exist, create it
try {
await fs.promises.mkdir(fullOutputDir, { recursive: true });
} catch (error) {
throw new Error(`Failed to create nested output directory ${fullOutputDir}: ${error.message}`);
}
}
} }
} }
@@ -96,6 +82,6 @@ export class PathResolver {
const baseName = file.basename; const baseName = file.basename;
const outputFileName = `${baseName}.pdf`; const outputFileName = `${baseName}.pdf`;
return path.join(outputDir, relativePath, outputFileName); return this.pathUtils.joinPath(outputDir, relativePath, outputFileName);
} }
} }
+33 -24
View File
@@ -9,10 +9,14 @@ import { PandocTypstConverter } from '../converters/PandocTypstConverter';
import { TemplateManager } from '../templates/TemplateManager'; import { TemplateManager } from '../templates/TemplateManager';
import { EmbeddedTemplateManager } from '../templates/embeddedTemplates'; import { EmbeddedTemplateManager } from '../templates/embeddedTemplates';
import { TempDirectoryManager } from '../core/TempDirectoryManager'; import { TempDirectoryManager } from '../core/TempDirectoryManager';
import * as path from 'path'; import { PathUtils } from '../core/PathUtils';
export class PluginLifecycle { export class PluginLifecycle {
constructor(private plugin: obsidianTypstPDFExport) {} private readonly pathUtils: PathUtils;
constructor(private plugin: obsidianTypstPDFExport) {
this.pathUtils = new PathUtils(plugin.app);
}
/** /**
* Initialize the plugin during onload * Initialize the plugin during onload
@@ -22,13 +26,13 @@ export class PluginLifecycle {
await this.plugin.loadSettings(); await this.plugin.loadSettings();
// Initialize embedded template manager // Initialize embedded template manager
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath; const vaultPath = this.pathUtils.getVaultPath();
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!); const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
this.plugin.embeddedTemplateManager = new EmbeddedTemplateManager(pluginDir); this.plugin.embeddedTemplateManager = new EmbeddedTemplateManager(pluginDir, this.plugin.app);
// Extract any missing templates from embedded data // Extract any missing templates from embedded data
try { try {
const extractionResult = this.plugin.embeddedTemplateManager.extractAllMissingTemplates(); const extractionResult = await this.plugin.embeddedTemplateManager.extractAllMissingTemplates();
if (extractionResult.failed.length > 0) { if (extractionResult.failed.length > 0) {
console.warn(`Failed to extract ${extractionResult.failed.length} templates:`, extractionResult.failed); console.warn(`Failed to extract ${extractionResult.failed.length} templates:`, extractionResult.failed);
ExportErrorHandler.showTemplateError(`Failed to extract some templates. Plugin may not work correctly.`); ExportErrorHandler.showTemplateError(`Failed to extract some templates. Plugin may not work correctly.`);
@@ -64,31 +68,36 @@ export class PluginLifecycle {
this.plugin.currentExportController.abort(); this.plugin.currentExportController.abort();
} }
// Clean up temp directories on plugin unload // Clean up temp directories on plugin unload (fire-and-forget async)
try { (async () => {
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath; try {
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir); const vaultPath = this.pathUtils.getVaultPath();
cleanupManager.cleanupAllTempDirs(); const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
} catch (error) { await cleanupManager.cleanupAllTempDirs();
console.warn('Export: Failed to clean up temp directories during unload:', error); } catch (error) {
} console.warn('Export: Failed to clean up temp directories during unload:', error);
}
})();
} }
/** /**
* Clean up leftover temp directories from previous sessions * Clean up leftover temp directories from previous sessions
*/ */
private cleanupStartupTempDirectories(): void { private cleanupStartupTempDirectories(): void {
try { // Clean up temp directories (fire-and-forget async)
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath; (async () => {
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir); try {
const _result = cleanupManager.cleanupAllTempDirs(); const vaultPath = this.pathUtils.getVaultPath();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
const _result = 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
}
} catch (error) {
console.warn('Export: Startup temp directory cleanup failed (non-critical):', error);
// Don't throw - this shouldn't prevent plugin from loading
} }
} catch (error) { })();
console.warn('Export: Startup temp directory cleanup failed (non-critical):', error);
// Don't throw - this shouldn't prevent plugin from loading
}
} }
} }
+26 -15
View File
@@ -4,19 +4,21 @@
*/ */
import { obsidianTypstPDFExport } from '../../main'; import { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs';
export class TemplateManager { export class TemplateManager {
private plugin: obsidianTypstPDFExport; private plugin: obsidianTypstPDFExport;
private templatesPath: string; private templatesPath: string;
private pathUtils: PathUtils;
constructor(plugin: obsidianTypstPDFExport) { constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin; this.plugin = plugin;
this.pathUtils = new PathUtils(plugin.app);
// Templates are stored in the plugin directory // Templates are stored in the plugin directory
this.templatesPath = path.join( this.templatesPath = this.pathUtils.joinPath(
(this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath, this.pathUtils.getVaultPath(),
this.plugin.manifest.dir!, this.pathUtils.getPluginDir(this.plugin.manifest),
'templates' 'templates'
); );
} }
@@ -27,13 +29,25 @@ export class TemplateManager {
async getAvailableTemplates(): Promise<string[]> { async getAvailableTemplates(): Promise<string[]> {
try { try {
// Check if templates directory exists // Check if templates directory exists
if (!fs.existsSync(this.templatesPath)) { const exists = await this.pathUtils.fileExists(this.templatesPath);
if (!exists) {
console.warn('Templates directory does not exist:', this.templatesPath); console.warn('Templates directory does not exist:', this.templatesPath);
return ['default.typ']; return ['default.typ'];
} }
// Read directory contents // Read directory contents - convert absolute path to vault-relative
const files = fs.readdirSync(this.templatesPath); const vaultBasePath = this.pathUtils.getVaultPath();
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 files = list.files.map(filePath => path.basename(filePath));
// Filter for .typ and .pandoc.typ files // Filter for .typ and .pandoc.typ files
const templates = files.filter(file => { const templates = files.filter(file => {
@@ -56,7 +70,7 @@ export class TemplateManager {
* Get the full path to a template file * Get the full path to a template file
*/ */
getTemplatePath(templateName: string): string { getTemplatePath(templateName: string): string {
return path.join(this.templatesPath, templateName); return this.pathUtils.joinPath(this.templatesPath, templateName);
} }
/** /**
@@ -64,11 +78,7 @@ export class TemplateManager {
*/ */
async templateExists(templateName: string): Promise<boolean> { async templateExists(templateName: string): Promise<boolean> {
const templatePath = this.getTemplatePath(templateName); const templatePath = this.getTemplatePath(templateName);
try { return await this.pathUtils.fileExists(templatePath);
return fs.existsSync(templatePath);
} catch {
return false;
}
} }
/** /**
@@ -77,8 +87,9 @@ export class TemplateManager {
async loadTemplate(templateName: string): Promise<string | null> { async loadTemplate(templateName: string): Promise<string | null> {
const templatePath = this.getTemplatePath(templateName); const templatePath = this.getTemplatePath(templateName);
try { try {
if (fs.existsSync(templatePath)) { const exists = await this.pathUtils.fileExists(templatePath);
return fs.readFileSync(templatePath, 'utf-8'); if (exists) {
return await this.plugin.app.vault.adapter.read(templatePath);
} }
} catch (error) { } catch (error) {
console.error('Error loading template:', error); console.error('Error loading template:', error);
+24 -24
View File
@@ -1,6 +1,6 @@
import { extractTemplate, getAllTemplateNames } from 'template-embed:templates'; import { extractTemplate, getAllTemplateNames } from 'template-embed:templates';
import * as fs from 'fs'; import { PathUtils } from '../core/PathUtils';
import * as path from 'path'; import type { App } from 'obsidian';
export interface TemplateInfo { export interface TemplateInfo {
name: string; name: string;
@@ -14,22 +14,26 @@ export interface TemplateInfo {
export class EmbeddedTemplateManager { export class EmbeddedTemplateManager {
private pluginDir: string; private pluginDir: string;
private templatesDir: string; private templatesDir: string;
private pathUtils: PathUtils;
private app: App;
constructor(pluginDir: string) { constructor(pluginDir: string, app: App) {
this.pluginDir = pluginDir; this.pluginDir = pluginDir;
this.templatesDir = path.join(pluginDir, 'templates'); this.app = app;
this.pathUtils = new PathUtils(app);
this.templatesDir = this.pathUtils.joinPath(pluginDir, 'templates');
} }
/** /**
* Get information about all templates * Get information about all templates
*/ */
getTemplateInfo(): TemplateInfo[] { async getTemplateInfo(): Promise<TemplateInfo[]> {
const embeddedNames = getAllTemplateNames(); const embeddedNames = getAllTemplateNames();
const templateInfo: TemplateInfo[] = []; const templateInfo: TemplateInfo[] = [];
for (const name of embeddedNames) { for (const name of embeddedNames) {
const filePath = path.join(this.templatesDir, name); const filePath = this.pathUtils.joinPath(this.templatesDir, name);
const exists = fs.existsSync(filePath); const exists = await this.pathUtils.fileExists(filePath);
templateInfo.push({ templateInfo.push({
name, name,
@@ -44,25 +48,23 @@ export class EmbeddedTemplateManager {
/** /**
* Extract a single template if it doesn't exist * Extract a single template if it doesn't exist
*/ */
extractTemplateIfNeeded(templateName: string): boolean { async extractTemplateIfNeeded(templateName: string): Promise<boolean> {
const filePath = path.join(this.templatesDir, templateName); const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
// Check if template already exists // Check if template already exists
if (fs.existsSync(filePath)) { if (await this.pathUtils.fileExists(filePath)) {
return false; // No extraction needed return false; // No extraction needed
} }
try { try {
// Ensure templates directory exists // Ensure templates directory exists
if (!fs.existsSync(this.templatesDir)) { await this.pathUtils.ensureDir(this.templatesDir);
fs.mkdirSync(this.templatesDir, { recursive: true });
}
// Extract template content // Extract template content
const content = extractTemplate(templateName, filePath); const content = extractTemplate(templateName, filePath);
// Write template to disk // Write template to disk using vault.adapter
fs.writeFileSync(filePath, content, 'utf8'); await this.app.vault.adapter.write(filePath, content);
return true; // Extraction successful return true; // Extraction successful
} catch (error) { } catch (error) {
@@ -74,15 +76,15 @@ export class EmbeddedTemplateManager {
/** /**
* Extract all missing templates * Extract all missing templates
*/ */
extractAllMissingTemplates(): { extracted: string[], failed: string[] } { async extractAllMissingTemplates(): Promise<{ extracted: string[], failed: string[] }> {
const extracted: string[] = []; const extracted: string[] = [];
const failed: string[] = []; const failed: string[] = [];
const templateInfo = this.getTemplateInfo(); const templateInfo = await this.getTemplateInfo();
for (const info of templateInfo) { for (const info of templateInfo) {
if (info.needsExtraction) { if (info.needsExtraction) {
const success = this.extractTemplateIfNeeded(info.name); const success = await this.extractTemplateIfNeeded(info.name);
if (success) { if (success) {
extracted.push(info.name); extracted.push(info.name);
} else { } else {
@@ -97,23 +99,21 @@ export class EmbeddedTemplateManager {
/** /**
* Force extract all templates (overwrites existing ones) * Force extract all templates (overwrites existing ones)
*/ */
forceExtractAllTemplates(): { extracted: string[], failed: string[] } { async forceExtractAllTemplates(): Promise<{ extracted: string[], failed: string[] }> {
const extracted: string[] = []; const extracted: string[] = [];
const failed: string[] = []; const failed: string[] = [];
const embeddedNames = getAllTemplateNames(); const embeddedNames = getAllTemplateNames();
// Ensure templates directory exists // Ensure templates directory exists
if (!fs.existsSync(this.templatesDir)) { await this.pathUtils.ensureDir(this.templatesDir);
fs.mkdirSync(this.templatesDir, { recursive: true });
}
for (const templateName of embeddedNames) { for (const templateName of embeddedNames) {
try { try {
const filePath = path.join(this.templatesDir, templateName); const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
const content = extractTemplate(templateName, filePath); const content = extractTemplate(templateName, filePath);
fs.writeFileSync(filePath, content, 'utf8'); await this.app.vault.adapter.write(filePath, content);
extracted.push(templateName); extracted.push(templateName);
} catch (error) { } catch (error) {
console.error(`Failed to force extract template ${templateName}:`, error); console.error(`Failed to force extract template ${templateName}:`, error);
+414
View File
@@ -0,0 +1,414 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
// Email block styling function - elegant book style
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
width: 100%,
inset: 18pt,
fill: rgb("#fafaf9"),
stroke: 1pt + rgb("#d6d3d1"),
radius: 0pt, // Square corners for book style
breakable: true
)[
#text(size: 1em, weight: "medium", style: "italic", fill: rgb("#57534e"))[Correspondence]
#v(0.4em)
#grid(
columns: (auto, 1fr),
row-gutter: 8pt,
column-gutter: 16pt,
if from != none [
#text(size: 0.9em, fill: rgb("#78716c"))[From:]
] else [],
if from != none [
#text(size: 0.9em)[#from]
] else [],
if to != none [
#text(size: 0.9em, fill: rgb("#78716c"))[To:]
] else [],
if to != none [
#text(size: 0.9em)[#to]
] else [],
if subject != none [
#text(size: 0.9em, fill: rgb("#78716c"))[Subject:]
] else [],
if subject != none [
#text(size: 0.9em, style: "italic")[#subject]
] else [],
if date != none [
#text(size: 0.9em, fill: rgb("#78716c"))[Date:]
] else [],
if date != none [
#text(size: 0.9em)[#date]
] else [],
)
#if body != none [
#v(0.6em)
#line(length: 100%, stroke: 0.5pt + rgb("#d6d3d1"))
#v(0.6em)
#block(
width: 100%,
inset: 0pt,
)[
#text(size: 0.9em)[#body]
]
]
]
}
// Drop cap function for chapter openings
#let drop-cap(text-content) = {
if type(text-content) != str {
text-content
} else {
let first-letter = text-content.slice(0, 1)
let rest = text-content.slice(1)
block(
width: 100%,
inset: 0pt,
)[
#grid(
columns: (auto, 1fr),
column-gutter: 8pt,
align: (left + top, left + top),
// Large decorative first letter
text(
size: 48pt,
weight: "bold",
font: ("Baskerville", "Times New Roman"),
fill: rgb("#7c2d12")
)[#first-letter],
// Rest of the paragraph
text(size: 11pt)[#rest]
)
]
}
}
// Decorative section divider
#let section-divider = {
v(1em)
align(center)[
#text(20pt, fill: rgb("#a8a29e"))[❦ ❦ ❦]
]
v(1em)
}
#let conf(
title: none,
authors: (),
date: none,
lang: "en",
region: "US",
paper: "a4",
margin: (inside: 3cm, outside: 2.5cm, top: 2.5cm, bottom: 2.5cm),
cols: 1,
font: ("Baskerville", "Times New Roman", "Times"),
fontsize: 11pt,
sectionnumbering: none, // Chapters typically don't use numbered sections
pagenumbering: "1",
// Support for UI-configurable options
heading_font: none,
monospace_font: none,
margin_top: none,
margin_right: none,
margin_bottom: none,
margin_left: none,
orientation: "portrait",
export_format: none,
doc,
) = {
// Set document properties
set document(
title: title
// Skip author in document metadata to avoid type issues
)
// Book-style alternating margins for binding
let page-margin = if margin_top != none {
(
top: if margin_top != none { margin_top } else { 2.5cm },
right: if margin_right != none { margin_right } else { 2.5cm },
bottom: if margin_bottom != none { margin_bottom } else { 2.5cm },
left: if margin_left != none { margin_left } else { 3cm },
)
} else {
margin
}
// Book page layout with alternating margins
set page(
paper: paper,
flipped: orientation == "landscape",
margin: page-margin,
..if export_format == "single-page" and orientation == "landscape" {
(width: auto,)
} else if export_format == "single-page" {
(height: auto,)
} else {
(:)
},
numbering: pagenumbering,
// Running headers for book style
header: context {
let page-num = counter(page).get().first()
if page-num > 1 [
#set text(size: 9pt, style: "italic", fill: rgb("#6b7280"))
#if calc.even(page-num) [
// Even pages: book title on left
#if title != none [#title] else [Document]
#h(1fr)
#page-num
] else [
// Odd pages: chapter title on right
#page-num
#h(1fr)
#context {
let headings = query(heading.where(level: 1))
if headings.len() > 0 [
#headings.last().body
] else [
Chapter
]
}
]
#v(-0.5em)
#line(length: 100%, stroke: 0.5pt + rgb("#d1d5db"))
]
}
)
// Classic book typography - serif fonts
let body-font = if font != none and type(font) == str {
(font, "Baskerville", "Times New Roman", "Times")
} else if font != none {
font
} else {
("Baskerville", "Times New Roman", "Times")
}
let body-fontsize = fontsize
set text(
font: body-font,
size: body-fontsize,
lang: lang,
region: region,
fill: rgb("#1f2937")
)
// Book-style paragraph settings with first-line indent
set par(
justify: true,
leading: 0.65em,
spacing: 0.65em,
first-line-indent: 1.2em
)
// Chapter and section numbering
if sectionnumbering != none {
set heading(numbering: sectionnumbering)
}
// Book-style heading fonts (same as body for classic look)
let heading-font = if heading_font != none and type(heading_font) == str {
(heading_font, "Baskerville", "Times New Roman", "Times")
} else if heading_font != none {
heading_font
} else {
("Baskerville", "Times New Roman", "Times")
}
// Chapter styling (Level 1 headings)
show heading.where(level: 1): it => {
pagebreak(weak: true)
v(3cm)
block(
width: 100%,
above: 0em,
below: 2em,
)[
#set align(center)
#set par(first-line-indent: 0em)
// Chapter number (if numbered)
#if it.numbering != none [
#text(
size: 14pt,
weight: "regular",
font: heading-font,
fill: rgb("#6b7280"),
tracking: 2pt
)[CHAPTER #counter(heading).display("I")]
#v(1em)
]
// Chapter title
#text(
size: 24pt,
weight: "bold",
font: heading-font,
fill: rgb("#111827")
)[#it.body]
#v(1.5em)
// Decorative flourish
#text(16pt, fill: rgb("#9ca3af"))[❦]
#v(2em)
]
// Reset paragraph indentation for first paragraph after chapter
par(first-line-indent: 0em)[]
}
// Section styling (Level 2 headings)
show heading.where(level: 2): it => {
v(1.5em)
block(
width: 100%,
below: 1em,
)[
#set align(center)
#set par(first-line-indent: 0em)
#text(
size: 16pt,
weight: "semibold",
font: heading-font,
fill: rgb("#374151")
)[#it.body]
#v(0.5em)
#line(length: 30%, stroke: 1pt + rgb("#9ca3af"))
]
}
// Subsection styling (Level 3 headings)
show heading.where(level: 3): it => block(
width: 100%,
below: 0.8em,
above: 1.2em,
)[
#set par(first-line-indent: 0em)
#text(
size: 13pt,
weight: "medium",
font: heading-font,
fill: rgb("#4b5563"),
style: "italic"
)[#it.body]
]
// Code styling (rare in books but sometimes needed)
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "Courier New", "Monaco")
} else {
("Courier New", "Monaco")
}
show raw: set text(font: code-font, size: body-fontsize * 0.9)
show raw.where(block: true): block.with(
width: 100%,
fill: rgb("#f9fafb"),
inset: 12pt,
radius: 0pt,
stroke: (left: 3pt + rgb("#d1d5db")),
breakable: true,
)
// Enhanced quote styling for books
show quote: it => {
set par(first-line-indent: 0em)
block(
width: 100%,
inset: (left: 2em, right: 2em, top: 1em, bottom: 1em),
)[
#set text(style: "italic", size: body-fontsize * 0.95)
#set par(leading: 0.7em)
#it.body
#if it.attribution != none [
#v(0.5em)
#align(right)[
#text(size: body-fontsize * 0.9, style: "normal")[— #it.attribution]
]
]
]
}
// Book title page (if title provided)
if title != none and title != "" [
#set align(center)
#set par(first-line-indent: 0em)
#v(4cm)
// Main title
#text(
size: 28pt,
weight: "bold",
font: heading-font,
fill: rgb("#111827")
)[#title]
#v(2em)
// Decorative line
#line(length: 40%, stroke: 1pt + rgb("#6b7280"))
#v(2em)
// Authors
#if authors != () and authors != none [
#for (i, author) in authors.enumerate() [
#if author.name != none and author.name != "" [
#text(
size: 16pt,
font: heading-font,
fill: rgb("#374151")
)[#author.name]
#if i < authors.len() - 1 [
#v(0.5em)
]
]
]
#v(2em)
]
// Date
#if date != none [
#text(
size: 12pt,
style: "italic",
fill: rgb("#6b7280")
)[#date]
]
#v(1fr)
#pagebreak()
// Copyright page (if authors provided)
#if authors != () and authors != none [
#v(1fr)
#set align(left)
#set text(size: 9pt, fill: rgb("#6b7280"))
#set par(first-line-indent: 0em, leading: 0.6em)
Copyright © #if date != none [#date] else [2024] by #if authors != () and authors != none [
#for (i, author) in authors.enumerate() [
#if author.name != none and author.name != "" [#author.name]#if i < authors.len() - 1 [, ]
]
] else [Author]
#v(0.5em)
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law.
#pagebreak()
]
]
// Document content
doc
}
+7 -7
View File
@@ -149,7 +149,7 @@
width: 100%, width: 100%,
below: 1em, below: 1em,
above: 1.2em, above: 1.2em,
fill: rgb("#2563eb"), fill: rgb("#0d9488"),
inset: (x: 12pt, y: 8pt), inset: (x: 12pt, y: 8pt),
radius: 6pt, radius: 6pt,
)[ )[
@@ -162,9 +162,9 @@
below: 0.6em, below: 0.6em,
above: 1em, above: 1em,
inset: (bottom: 3pt), inset: (bottom: 3pt),
stroke: (bottom: 2pt + rgb("#2563eb")), stroke: (bottom: 2pt + rgb("#0d9488")),
)[ )[
#set text(font: heading-font, size: heading-fontsize * 0.85, weight: "semibold", fill: rgb("#1e40af")) #set text(font: heading-font, size: heading-fontsize * 0.85, weight: "semibold", fill: rgb("#0f766e"))
#it.body #it.body
] ]
@@ -190,7 +190,7 @@
if title != none and title != "" [ if title != none and title != "" [
#block( #block(
width: 100%, width: 100%,
fill: gradient.linear(rgb("#1e40af"), rgb("#3b82f6"), angle: 45deg), fill: gradient.linear(rgb("#0f766e"), rgb("#14b8a6"), angle: 45deg),
inset: 16pt, inset: 16pt,
radius: (top: 8pt), radius: (top: 8pt),
)[ )[
@@ -204,7 +204,7 @@
#v(0.3em) #v(0.3em)
#for author in authors [ #for author in authors [
#if author.name != none and author.name != "" [ #if author.name != none and author.name != "" [
#text(14pt, fill: rgb("#dbeafe"))[#author.name] #text(14pt, fill: rgb("#ccfbf1"))[#author.name]
] ]
] ]
] ]
@@ -212,7 +212,7 @@
// Contact info sidebar // Contact info sidebar
align(right + top)[ align(right + top)[
#if date != none [ #if date != none [
#text(11pt, fill: rgb("#dbeafe"), style: "italic")[#date] #text(11pt, fill: rgb("#ccfbf1"), style: "italic")[#date]
] ]
] ]
) )
@@ -233,7 +233,7 @@
if authors != () and authors != none [ if authors != () and authors != none [
#for author in authors [ #for author in authors [
#if author.name != none and author.name != "" [ #if author.name != none and author.name != "" [
#text(14pt, weight: "semibold", fill: rgb("#1e40af"))[#author.name] #text(14pt, weight: "semibold", fill: rgb("#0f766e"))[#author.name]
] ]
] ]
] else [], ] else [],
+376
View File
@@ -0,0 +1,376 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
// Email block styling function with modern sidebar-appropriate styling
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
width: 100%,
inset: 14pt,
fill: rgb("#f8fafc"),
stroke: 1pt + rgb("#e2e8f0"),
radius: 8pt,
breakable: true
)[
#text(size: 0.9em, weight: "semibold", fill: rgb("#475569"))[Email]
#v(0.3em)
#grid(
columns: (auto, 1fr),
row-gutter: 6pt,
column-gutter: 12pt,
if from != none [
#text(style: "italic", size: 0.85em, fill: rgb("#64748b"))[From:]
] else [],
if from != none [
#text(size: 0.9em, fill: rgb("#1e293b"))[#from]
] else [],
if to != none [
#text(style: "italic", size: 0.85em, fill: rgb("#64748b"))[To:]
] else [],
if to != none [
#text(size: 0.9em, fill: rgb("#1e293b"))[#to]
] else [],
if subject != none [
#text(style: "italic", size: 0.85em, fill: rgb("#64748b"))[Subject:]
] else [],
if subject != none [
#text(size: 0.9em, weight: "medium", fill: rgb("#0f172a"))[#subject]
] else [],
)
#if body != none [
#v(0.5em)
#block(
width: 100%,
inset: 8pt,
fill: rgb("#ffffff"),
radius: 4pt,
stroke: 0.5pt + rgb("#e2e8f0"),
)[
#text(size: 0.85em, fill: rgb("#374151"))[#body]
]
]
]
}
// Sidebar navigation component
#let sidebar-nav(title: none, authors: (), date: none, body-fontsize: 11pt, pagenumbering: "1") = {
let sidebar-bg = gradient.linear(
rgb("#dc2626"),
rgb("#ea580c"),
rgb("#f97316"),
angle: 160deg
)
place(
top + left,
dx: 0pt,
dy: 0pt,
block(
width: 4.5cm,
height: 27cm,
fill: sidebar-bg,
inset: 18pt,
radius: (right: 12pt),
)[
#set text(fill: white, size: body-fontsize * 0.9)
// Document title in sidebar
#if title != none and title != "" [
#text(15pt, weight: "bold", tracking: 0.5pt)[#upper(title)]
#v(1.2em)
#line(length: 100%, stroke: 1.5pt + rgb("#dbeafe"))
#v(1.2em)
]
// Author information in sidebar
#if authors != () and authors != none [
#text(9pt, weight: "medium", fill: rgb("#dbeafe"), tracking: 1pt)[AUTHORS]
#v(0.5em)
#for (i, author) in authors.enumerate() [
#if author.name != none and author.name != "" [
#text(10pt, weight: "regular")[#author.name]
#if i < authors.len() - 1 [#v(0.3em)]
]
]
#v(1.5em)
]
// Date in sidebar
#if date != none [
#text(9pt, weight: "medium", fill: rgb("#dbeafe"), tracking: 1pt)[DATE]
#v(0.5em)
#text(10pt)[#date]
#v(1.5em)
]
// Enhanced Table of contents in sidebar
#text(9pt, weight: "medium", fill: rgb("#dbeafe"), tracking: 1pt)[CONTENTS]
#v(0.7em)
#context {
let headings-1 = query(heading.where(level: 1))
let headings-2 = query(heading.where(level: 2))
for h1 in headings-1 {
block(
width: 100%,
inset: (y: 0.2em),
fill: rgb(255, 255, 255, 10%),
radius: 3pt
)[
#text(9pt, weight: "semibold")[#h1.body]
]
// Show level 2 headings under this level 1
for h2 in headings-2 {
if h2.location().page() >= h1.location().page() {
text(8pt, fill: rgb("#dbeafe"))[ • #h2.body]
v(0.15em)
}
}
v(0.4em)
}
}
#v(1fr)
// Progress indicator
#context {
let current-page = counter(page).get().first()
let total-pages = counter(page).final().first()
let progress = current-page / total-pages * 100
text(8pt, fill: rgb("#dbeafe"))[Progress]
v(0.3em)
block(
width: 100%,
height: 4pt,
fill: rgb(255, 255, 255, 20%),
radius: 2pt
)[
#place(
left,
block(
width: progress * 1%,
height: 100%,
fill: rgb("#fbbf24"),
radius: 2pt
)
)
]
v(0.5em)
}
// Page number at bottom of sidebar
#if pagenumbering != none [
#line(length: 100%, stroke: 1pt + rgb("#dbeafe"))
#v(0.7em)
#set align(center)
#context {
let current = counter(page).get().first()
let total = counter(page).final().first()
text(13pt, weight: "bold")[#current]
v(0.2em)
text(8pt, fill: rgb("#dbeafe"))[of #total]
}
]
]
)
}
#let conf(
title: none,
authors: (),
date: none,
lang: "en",
region: "US",
paper: "a4",
margin: (left: 8cm, right: 1.5cm, top: 1.5cm, bottom: 1.5cm),
cols: 1,
font: ("Inter", "SF Pro", "Helvetica Neue", "Arial"),
fontsize: 11pt,
sectionnumbering: "1.",
pagenumbering: "1",
// Support for UI-configurable options
heading_font: none,
monospace_font: none,
margin_top: none,
margin_right: none,
margin_bottom: none,
margin_left: none,
orientation: "portrait",
export_format: none,
doc,
) = {
// Set document properties
set document(
title: title
)
// Sidebar layout with fixed left margin for floating sidebar
let page-margin = (
top: if margin_top != none { margin_top } else { 1.5cm },
right: if margin_right != none { margin_right } else { 1.5cm },
bottom: if margin_bottom != none { margin_bottom } else { 1.5cm },
left: 5cm, // Fixed for sidebar - not configurable
)
// Page layout optimized for sidebar
set page(
paper: paper,
flipped: orientation == "landscape",
margin: page-margin,
..if export_format == "single-page" and orientation == "landscape" {
(width: auto,)
} else if export_format == "single-page" {
(height: auto,)
} else {
(:)
},
numbering: pagenumbering,
background: {
// Add the floating sidebar
sidebar-nav(
title: title,
authors: authors,
date: date,
body-fontsize: fontsize,
pagenumbering: pagenumbering
)
}
)
// Modern sans-serif typography
let body-font = if font != none and type(font) == str {
(font, "Inter", "SF Pro", "Helvetica Neue", "Arial")
} else {
font
}
let body-fontsize = fontsize
set text(
font: body-font,
size: body-fontsize,
lang: lang,
region: region,
fill: rgb("#111827")
)
// Clean paragraph settings
set par(justify: true, leading: 0.65em, spacing: 0.8em)
// Set heading numbering
if sectionnumbering != none {
set heading(numbering: sectionnumbering)
}
// Modern heading fonts
let heading-font = if heading_font != none and type(heading_font) == str {
(heading_font, "Inter", "SF Pro", "Helvetica Neue", "Arial")
} else if heading_font != none {
heading_font
} else {
("Inter", "SF Pro", "Helvetica Neue", "Arial")
}
let heading-fontsize = body-fontsize * 1.3
// Color palette coordinated with orange-red sidebar
let primary-color = rgb("#dc2626")
let secondary-color = rgb("#ea580c")
let accent-color = rgb("#f97316")
let text-color = rgb("#374151")
show heading.where(level: 1): it => block(
width: 100%,
below: 1.4em,
above: 2em,
breakable: false,
)[
#set text(font: heading-font, size: heading-fontsize * 1.2, weight: "bold", fill: primary-color)
#it
#v(0.5em)
#line(length: 100%, stroke: 2pt + gradient.linear(primary-color, secondary-color))
]
show heading.where(level: 2): it => block(
width: 100%,
below: 1em,
above: 1.6em,
inset: (left: 0pt, bottom: 8pt),
)[
#set text(font: heading-font, size: heading-fontsize, weight: "semibold", fill: text-color)
#it
#v(0.3em)
#line(length: 40%, stroke: 1pt + primary-color)
]
show heading.where(level: 3): it => block(
width: 100%,
below: 0.8em,
above: 1.2em,
)[
#set text(font: heading-font, size: heading-fontsize * 0.85, weight: "medium", fill: accent-color)
#it
]
// Enhanced code styling
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "SF Mono", "JetBrains Mono", "Courier New")
} else {
("SF Mono", "JetBrains Mono", "Courier New")
}
show raw: set text(font: code-font, size: body-fontsize * 0.9, fill: rgb("#374151"))
show raw.where(block: true): block.with(
width: 100%,
fill: rgb("#f8fafc"),
stroke: 1pt + rgb("#e2e8f0"),
inset: 14pt,
radius: 6pt,
breakable: true,
)
// Enhanced list styling
set list(indent: 1em, body-indent: 0.5em)
show list: it => {
set text(fill: rgb("#374151"))
it
}
// Enhanced quote styling
show quote: it => block(
width: 100%,
fill: rgb("#f1f5f9"),
inset: (left: 16pt, right: 16pt, top: 12pt, bottom: 12pt),
stroke: (left: 4pt + accent-color),
radius: (right: 6pt),
)[
#set text(style: "italic", fill: rgb("#4b5563"))
#it
]
// Figure styling
show figure: it => block(
width: 100%,
breakable: false,
)[
#set align(center)
#it.body
#if it.caption != none [
#v(0.7em)
#text(
size: body-fontsize * 0.9,
style: "italic",
fill: rgb("#6b7280")
)[
Figure #counter(figure).display("1"): #it.caption
]
]
]
// Don't show title/authors in main content since they're in sidebar
// Just start with the document content
doc
}
+307
View File
@@ -0,0 +1,307 @@
// Horizontal rule definition for Pandoc compatibility
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
// Email block styling function
#let email-block(from: none, to: none, subject: none, date: none, body) = {
block(
width: 100%,
inset: 16pt,
stroke: 0.5pt + blue,
radius: 5pt,
breakable: true
)[
#grid(
columns: (auto, 1fr),
row-gutter: 13pt,
column-gutter: 8pt,
if from != none [
#text(style: "italic", size: 1em)[From:]
] else [],
if from != none [
#text(size: 1em)[#from]
] else [],
if to != none [
#text(style: "italic", size: 1em)[To:]
] else [],
if to != none [
#text(size: 1em)[#to]
] else [],
if subject != none [
#text(style: "italic", size: 1em)[Subject:]
] else [],
if subject != none [
#text(size: 1em)[#subject]
] else [],
if date != none [
#text(style: "italic", size: 1em)[Date:]
] else [],
if date != none [
#text(size: 1em)[#date]
] else [],
)
#if body != none [
#block(
width: 100%,
inset: (left: 5pt, top: 6pt),
stroke: (left: 2pt + gray),
)[
#body
]
]
]
}
#let conf(
title: none,
authors: (),
date: none,
lang: "en",
region: "US",
paper: "a4",
margin: (x: 2.5cm, y: 2cm),
cols: 2,
font: ("Libertinus Serif", "Times New Roman", "Times"),
fontsize: 10pt,
sectionnumbering: "1.",
pagenumbering: "1",
// Support for UI-configurable options
heading_font: none,
monospace_font: none,
margin_top: none,
margin_right: none,
margin_bottom: none,
margin_left: none,
orientation: "portrait",
export_format: none,
doc,
) = {
// Set document properties
set document(
title: title
// Skip author in document metadata to avoid type issues
)
// Use UI-configured margins if available, otherwise fall back to template defaults
let page-margin = if margin_top != none {
(
top: if margin_top != none { margin_top } else { 2cm },
right: if margin_right != none { margin_right } else { 2.5cm },
bottom: if margin_bottom != none { margin_bottom } else { 2cm },
left: if margin_left != none { margin_left } else { 2.5cm },
)
} else {
margin
}
// globally set the gutter between page columns
set columns(gutter: 4% + 11pt)
// Single-column page layout
// Two-column page layout with configurable orientation
set page(
paper: paper,
flipped: orientation == "landscape",
margin: page-margin,
columns: 2,
..if export_format == "single-page" and orientation == "landscape" {
(width: auto,)
} else if export_format == "single-page" {
(height: auto,)
} else {
(:)
},
numbering: pagenumbering,
header: context {
if counter(page).get().first() > 1 [
#h(1fr) #counter(page).display("1")
]
}
)
// Academic typography - serif font with good readability
let body-font = if font != none and type(font) == str {
(font, "Libertinus Serif", "Times New Roman", "Times")
} else {
font
}
let body-fontsize = fontsize
set text(
font: body-font,
size: body-fontsize,
lang: lang,
region: region
)
// Justified paragraphs with proper spacing for columns
set par(justify: true, leading: 0.65em, spacing: 0.65em)
// Set heading numbering
if sectionnumbering != none {
set heading(numbering: sectionnumbering)
}
// Academic heading styles
let heading-font = if heading_font != none and type(heading_font) == str {
(heading_font, "Libertinus Serif", "Times New Roman", "Times")
} else if heading_font != none {
heading_font
} else {
("Libertinus Serif", "Times New Roman", "Times")
}
let heading-fontsize = body-fontsize * 1.3
show heading.where(level: 1): it => {
// Level 1 headings span both columns and create section breaks
place(
top + left,
scope: "parent",
float: true,
clearance: 1em,
block(
width: 100%,
below: 1.2em,
above: 1.5em,
breakable: false,
)[
#set text(font: heading-font, size: heading-fontsize * 1.2, weight: "bold")
#set align(left)
#it
#v(0.3em)
#line(length: 100%, stroke: 1pt + gray)
]
)
}
show heading.where(level: 2): it => block(
width: 100%,
below: 0.8em,
above: 1em,
)[
#set text(font: heading-font, size: heading-fontsize, weight: "bold")
#it
]
show heading.where(level: 3): it => block(
width: 100%,
below: 0.6em,
above: 0.8em,
)[
#set text(font: heading-font, size: heading-fontsize * 0.9, weight: "semibold", style: "italic")
#it
]
// Code styling with monospace font
let code-font = if monospace_font != none and type(monospace_font) == str {
(monospace_font, "Courier New", "Monaco", "Menlo")
} else {
("Courier New", "Monaco", "Menlo")
}
show raw: set text(font: code-font, size: body-fontsize * 0.9)
// Code blocks with background
show raw.where(block: true): block.with(
width: 100%,
fill: luma(250),
inset: 8pt,
radius: 3pt,
breakable: true,
)
// Full-width title and author section spanning both columns
if title != none and title != "" [
#place(
top + center,
scope: "parent",
float: true,
clearance: 2em,
block(
width: 100%,
breakable: false,
)[
#set align(center)
#text(18pt, weight: "bold", font: heading-font)[#title]
#if authors != () and authors != none [
#v(0.8em)
#for (i, author) in authors.enumerate() [
#if author.name != none and author.name != "" [
#text(12pt, style: "italic")[#author.name]
#if i < authors.len() - 1 [, ]
]
]
]
#if date != none [
#v(0.5em)
#text(10pt, style: "italic")[#date]
]
#v(1.5em)
#line(length: 60%, stroke: 0.5pt + gray)
]
)
] else [
// If no title, still show authors and date in header if present
#if authors != () and authors != none or date != none [
#place(
top + center,
scope: "parent",
float: true,
clearance: 1em,
block(width: 100%)[
#set align(center)
#if authors != () and authors != none [
#for (i, author) in authors.enumerate() [
#if author.name != none and author.name != "" [
#text(12pt, weight: "semibold")[#author.name]
#if i < authors.len() - 1 [, ]
]
]
]
#if date != none [
#v(0.3em)
#text(10pt, style: "italic")[#date]
]
#v(1em)
#line(length: 40%, stroke: 0.5pt + gray)
]
)
]
]
// Enhanced figure styling for two-column layout
show figure: it => {
block(
width: 100%,
breakable: false,
)[
#set align(center)
#it.body
#if it.caption != none [
#v(0.5em)
#text(size: body-fontsize * 0.9, style: "italic")[
Figure #counter(figure).display("1"): #it.caption
]
]
]
}
// Footnote styling for columns
show footnote.entry: it => {
block(
width: 100%,
inset: (top: 0.3em),
)[
#text(size: body-fontsize * 0.8)[
#super[#it.note.counter.display("1")] #it.note.body
]
]
}
// Document content
doc
}