Enhances path handling and file resolution #5

Merged
AlexKucera merged 36 commits from 1.3.0 into master 2025-09-25 16:47:12 +02:00
21 changed files with 1169 additions and 337 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/),
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
### Fixed
+1
View File
@@ -3,6 +3,7 @@
[![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)
[![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)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "typst-pdf-export",
"name": "Typst PDF Export",
"version": "1.2.1",
"version": "1.3.0",
"minAppVersion": "1.9.12",
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
"author": "Alexander Kucera",
coderabbitai[bot] commented 2025-09-25 13:05:39 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Reconsider minAppVersion: 1.9.12 limits users to early-access builds

Unless you rely on 1.9-only APIs, set minAppVersion to the latest stable (1.8.9) to avoid excluding stable users.

Apply this diff:

-	"version": "1.3.0",
-	"minAppVersion": "1.9.12",
+	"version": "1.3.0",
+	"minAppVersion": "1.8.9",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	"version": "1.3.0",
	"minAppVersion": "1.8.9",
	"description": "Exports a note or collection of notes to a pretty Typst PDF.",
🤖 Prompt for AI Agents
In manifest.json around lines 4 to 6, the minAppVersion is set to "1.9.12" which
restricts users to early-access builds; unless your code uses APIs introduced in
1.9.x, change "minAppVersion" to "1.8.9" to target the latest stable release and
avoid excluding stable users—update that field in the file to "1.8.9" (or
document any 1.9-only dependency if you must keep it).
_⚠️ Potential issue_ | _🟠 Major_ **Reconsider minAppVersion: 1.9.12 limits users to early-access builds** Unless you rely on 1.9-only APIs, set minAppVersion to the latest stable (1.8.9) to avoid excluding stable users. Apply this diff: ```diff - "version": "1.3.0", - "minAppVersion": "1.9.12", + "version": "1.3.0", + "minAppVersion": "1.8.9", ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion "version": "1.3.0", "minAppVersion": "1.8.9", "description": "Exports a note or collection of notes to a pretty Typst PDF.", ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In manifest.json around lines 4 to 6, the minAppVersion is set to "1.9.12" which restricts users to early-access builds; unless your code uses APIs introduced in 1.9.x, change "minAppVersion" to "1.8.9" to target the latest stable release and avoid excluding stable users—update that field in the file to "1.8.9" (or document any 1.9-only dependency if you must keep it). ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated reply by CodeRabbit -->
AlexKucera commented 2025-09-25 15:29:10 +02:00 (Migrated from github.com)
Review

@coderabbitai I will reject this, because 1.9.12 is the most recent version and not in beta.

@coderabbitai I will reject this, because 1.9.12 is the most recent version and not in beta.
coderabbitai[bot] commented 2025-09-25 15:30:10 +02:00 (Migrated from github.com)
Review

@AlexKucera Thank you for the correction! You're absolutely right - I apologize for the incorrect suggestion. As the plugin author, you would have current knowledge of Obsidian's versioning, and if 1.9.12 is indeed the latest stable version rather than early access, then your minAppVersion setting is appropriate.

I appreciate you clarifying this. Your minAppVersion of 1.9.12 is correct for targeting the current stable Obsidian release.


✏️ Learnings added
Learnt from: AlexKucera
PR: AlexKucera/obsidian-typst-pdf-export#5
File: manifest.json:4-6
Timestamp: 2025-09-25T13:30:09.533Z
Learning: Obsidian version 1.9.12 is the current latest stable version, not early access or beta. Plugin authors should use current stable versions in minAppVersion.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@AlexKucera Thank you for the correction! You're absolutely right - I apologize for the incorrect suggestion. As the plugin author, you would have current knowledge of Obsidian's versioning, and if 1.9.12 is indeed the latest stable version rather than early access, then your minAppVersion setting is appropriate. I appreciate you clarifying this. Your minAppVersion of 1.9.12 is correct for targeting the current stable Obsidian release. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera PR: AlexKucera/obsidian-typst-pdf-export#5 File: manifest.json:4-6 Timestamp: 2025-09-25T13:30:09.533Z Learning: Obsidian version 1.9.12 is the current latest stable version, not early access or beta. Plugin authors should use current stable versions in minAppVersion. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> <!-- This is an auto-generated reply by CodeRabbit -->
+1 -1
View File
@@ -1,6 +1,6 @@
{
"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.",
"main": "main.js",
"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/
+16 -12
View File
@@ -3,12 +3,10 @@
* 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 type { obsidianTypstPDFExport } from '../../main';
import { TempDirectoryManager } from '../core/TempDirectoryManager';
import { PathUtils } from '../core/PathUtils';
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor';
@@ -104,9 +102,10 @@ export class PandocTypstConverter {
// Create temporary markdown file
await this.ensureTempDirectory();
const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`);
await fsPromises.writeFile(tempInputPath, content, 'utf-8');
const pathUtils = new PathUtils(this.plugin.app);
const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
await this.plugin.app.vault.adapter.write(tempInputPath, content);
// Merge options
this.pandocOptions = { ...this.pandocOptions, ...options };
@@ -116,7 +115,7 @@ export class PandocTypstConverter {
// Cleanup temp file
try {
await fsPromises.unlink(tempInputPath);
await this.plugin.app.vault.adapter.remove(tempInputPath);
} catch (error) {
console.warn('Failed to cleanup temp file:', error);
}
@@ -162,7 +161,8 @@ export class PandocTypstConverter {
// Remove temporary directory
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;
}
} catch (error) {
@@ -178,11 +178,15 @@ export class PandocTypstConverter {
if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir);
this.tempDir = tempManager.ensureTempDir('pandoc');
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc');
} else {
// Fallback to system temp if plugin folder not available
this.tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'obsidian-typst-'));
// Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
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;
+8 -4
View File
@@ -3,13 +3,13 @@
* Converts PDF files to PNG images for preview in Typst exports
*/
import * as fs from 'fs/promises';
import * as path from 'path';
import { PdfProcessor } from './pdf/PdfProcessor';
import { ImageOptimizer } from './pdf/ImageOptimizer';
import { PdfCliExecutor } from './pdf/PdfCliExecutor';
import { FileDiscovery } from './pdf/FileDiscovery';
import type { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils';
export interface PdfConversionOptions {
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
@@ -93,7 +93,10 @@ export class PdfToImageConverter {
}
// 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
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)
const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName);
const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName, this.plugin);
if (!fileDiscovery.found) {
return {
imagePath: '',
@@ -140,7 +143,8 @@ export class PdfToImageConverter {
{
format: opts.format,
quality: opts.quality
}
},
this.plugin
);
if (!optimizationResult.success) {
+11 -10
View File
@@ -9,6 +9,7 @@ import { TypstVariableMapper } from './TypstVariableMapper';
import { ResourcePathResolver } from './ResourcePathResolver';
import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils';
export class PandocCommandBuilder {
private plugin: obsidianTypstPDFExport;
@@ -19,7 +20,7 @@ export class PandocCommandBuilder {
constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin;
this.variableMapper = new TypstVariableMapper(plugin);
this.resourcePathResolver = new ResourcePathResolver();
this.resourcePathResolver = new ResourcePathResolver(plugin);
this.pathResolver = new PathResolver(plugin);
}
@@ -95,21 +96,21 @@ export class PandocCommandBuilder {
private async addTemplateConfiguration(args: string[], pandocOptions: PandocOptions): Promise<void> {
// Use universal wrapper with --template and pass actual template as template_path variable
if (pandocOptions.template) {
const fs = require('fs');
const pathUtils = new PathUtils(this.plugin.app);
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
if (!fs.existsSync(wrapperPath)) {
if (!(await pathUtils.fileExists(wrapperPath))) {
throw new Error(`Universal wrapper template not found at: ${wrapperPath}`);
}
args.push('--template', wrapperPath);
// Add plugin templates directory as a resource path so Typst can find template files
const templatesDir = path.resolve(absolutePluginDir, 'templates');
// Quote the path to handle spaces and special characters
args.push('--resource-path', `"${templatesDir}"`);
const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates');
// Path quoting handled automatically by spawn
args.push('--resource-path', templatesDir);
// Pass the actual template path as a variable
// Use relative path from vault root for Typst import
1
+37 -33
View File
@@ -1,36 +1,41 @@
import * as path from 'path';
import { promises as fsPromises } from 'fs';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
/**
* Handles resource path resolution and caching for Pandoc conversions.
* Discovers and caches attachment directories to help Pandoc find embedded resources.
*/
export class ResourcePathResolver {
private plugin: obsidianTypstPDFExport | undefined;
private resourcePathCache: string[] = [];
private resourcePathCacheTimestamp: number = 0;
private resourcePathCacheVaultPath: string = '';
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
* @param vaultBasePath The base path of the vault
* @returns Array of resource paths for Pandoc to search
*/
async getResourcePaths(vaultBasePath: string): Promise<string[]> {
if (!vaultBasePath) {
if (!vaultBasePath || !this.plugin?.app) {
return [];
}
const fs = require('fs');
const pathUtils = new PathUtils(this.plugin.app);
const resourcePaths: string[] = [];
// Add vault root as primary resource path
resourcePaths.push(vaultBasePath);
// Add common attachment directories
const commonPaths = this.getCommonAttachmentPaths(vaultBasePath);
const commonPaths = this.getCommonAttachmentPaths(vaultBasePath, pathUtils);
for (const attachPath of commonPaths) {
if (fs.existsSync(attachPath)) {
if (await pathUtils.fileExists(attachPath)) {
resourcePaths.push(attachPath);
}
}
@@ -42,7 +47,7 @@ export class ResourcePathResolver {
resourcePaths.push(...this.resourcePathCache);
} else {
// 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);
}
@@ -52,15 +57,16 @@ export class ResourcePathResolver {
/**
* Get common attachment directory paths that Obsidian users typically use
* @param vaultBasePath The base path of the vault
* @param pathUtils PathUtils instance for path operations
* @returns Array of common attachment directory paths
*/
private getCommonAttachmentPaths(vaultBasePath: string): string[] {
private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] {
return [
path.join(vaultBasePath, 'attachments'),
path.join(vaultBasePath, 'assets'),
path.join(vaultBasePath, 'files'),
path.join(vaultBasePath, 'images'),
path.join(vaultBasePath, '.attachments')
pathUtils.joinPath(vaultBasePath, 'attachments'),
pathUtils.joinPath(vaultBasePath, 'assets'),
pathUtils.joinPath(vaultBasePath, 'files'),
pathUtils.joinPath(vaultBasePath, 'images'),
pathUtils.joinPath(vaultBasePath, '.attachments')
];
}
@@ -79,36 +85,34 @@ export class ResourcePathResolver {
/**
coderabbitai[bot] commented 2025-09-25 13:05:39 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🔴 Critical

Fix: adapter.list must take a vault‑relative path; also return absolute paths for consistency.

  • FileSystemAdapter.list expects a vault‑relative path ('' or '/'), not an absolute filesystem path.
  • Return absolute paths from scan to match other entries and avoid reliance on Pandoc’s cwd.

Apply this diff:

-			const vaultContents = await this.plugin.app.vault.adapter.list(vaultBasePath);
+			const vaultContents = await this.plugin.app.vault.adapter.list('');
 			for (const item of vaultContents.folders) {
 				const itemName = item.split('/').pop() || item;

 				if (!itemName.startsWith('.') && !itemName.startsWith('_')) {
 					// Check if this directory contains images
 					try {
 						const dirContents = await this.plugin.app.vault.adapter.list(item);
 						const hasImages = dirContents.files.some((file: string) =>
 							/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
 						);
 						if (hasImages) {
-							foundResourcePaths.push(item);
+							foundResourcePaths.push(pathUtils.joinPath(vaultBasePath, item));
 						}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const vaultContents = await this.plugin.app.vault.adapter.list('');
			for (const item of vaultContents.folders) {
				const itemName = item.split('/').pop() || item;

				if (!itemName.startsWith('.') && !itemName.startsWith('_')) {
					// Check if this directory contains images
					try {
						const dirContents = await this.plugin.app.vault.adapter.list(item);
						const hasImages = dirContents.files.some((file: string) =>
							/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
						);
						if (hasImages) {
							foundResourcePaths.push(pathUtils.joinPath(vaultBasePath, item));

✅ Addressed in commits 3782f0a to d20e8cf

_⚠️ Potential issue_ | _🔴 Critical_ **Fix: adapter.list must take a vault‑relative path; also return absolute paths for consistency.** - FileSystemAdapter.list expects a vault‑relative path ('' or '/'), not an absolute filesystem path. - Return absolute paths from scan to match other entries and avoid reliance on Pandoc’s cwd. Apply this diff: ```diff - const vaultContents = await this.plugin.app.vault.adapter.list(vaultBasePath); + const vaultContents = await this.plugin.app.vault.adapter.list(''); for (const item of vaultContents.folders) { const itemName = item.split('/').pop() || item; if (!itemName.startsWith('.') && !itemName.startsWith('_')) { // Check if this directory contains images try { const dirContents = await this.plugin.app.vault.adapter.list(item); const hasImages = dirContents.files.some((file: string) => /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) ); if (hasImages) { - foundResourcePaths.push(item); + foundResourcePaths.push(pathUtils.joinPath(vaultBasePath, item)); } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const vaultContents = await this.plugin.app.vault.adapter.list(''); for (const item of vaultContents.folders) { const itemName = item.split('/').pop() || item; if (!itemName.startsWith('.') && !itemName.startsWith('_')) { // Check if this directory contains images try { const dirContents = await this.plugin.app.vault.adapter.list(item); const hasImages = dirContents.files.some((file: string) => /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) ); if (hasImages) { foundResourcePaths.push(pathUtils.joinPath(vaultBasePath, item)); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 3782f0a to d20e8cf
* Scan the vault for directories containing images and cache the results
* @param vaultBasePath The base path of the vault
* @param fs File system module
* @param pathUtils PathUtils instance for path operations
* @param now Current timestamp
* @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[] = [];
try {
const vaultContents = fs.readdirSync(vaultBasePath);
for (const item of vaultContents) {
const itemPath = path.join(vaultBasePath, item);
let stat;
try {
stat = await fsPromises.stat(itemPath);
} catch (error) {
// 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 (!this.plugin?.app) {
return foundResourcePaths;
}
// Use vault root (empty string) for adapter.list() to get vault-relative paths
const vaultContents = await this.plugin.app.vault.adapter.list('');
for (const item of vaultContents.folders) {
const itemName = item.split('/').pop() || item;
if (!itemName.startsWith('.') && !itemName.startsWith('_')) {
// Check if this directory contains images
try {
const dirContents = fs.readdirSync(itemPath);
const hasImages = dirContents.some((file: string) =>
const dirContents = await this.plugin.app.vault.adapter.list(item);
const hasImages = dirContents.files.some((file: string) =>
/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
);
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 {
// Ignore directories we can't read
+87 -25
View File
@@ -5,6 +5,7 @@
import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils';
export interface BinaryLocation {
/** Full path to the binary */
@@ -19,6 +20,7 @@ export class BinaryLocator {
/**
* Find the pdf2img binary in the plugin's node_modules directory.
* 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
* @returns Binary location info
*/
@@ -30,34 +32,28 @@ export class BinaryLocator {
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
const configDir = plugin?.app.vault.configDir || '.obsidian';
coderabbitai[bot] commented 2025-09-25 13:05:39 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Handle Windows shims in node_modules/.bin

On Windows, the executable is typically pdf2img.cmd (or .ps1). Probe platform-specific candidates before failing.

Apply this diff:

-			const pdf2imgPath = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img');
-
-			// Check if the binary exists
-			const exists = await this.validateBinaryExists(pdf2imgPath, plugin);
+			const base = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img');
+			const candidates = process.platform === 'win32'
+				? [base + '.cmd', base + '.ps1', base]
+				: [base];
+			let pdf2imgPath = candidates[0];
+			let exists = false;
+			for (const c of candidates) {
+				if (await this.validateBinaryExists(c, plugin)) {
+					pdf2imgPath = c;
+					exists = true;
+					break;
+				}
+			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const base = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img');
			const candidates = process.platform === 'win32'
				? [base + '.cmd', base + '.ps1', base]
				: [base];
			let pdf2imgPath = candidates[0];
			let exists = false;
			for (const c of candidates) {
				if (await this.validateBinaryExists(c, plugin)) {
					pdf2imgPath = c;
					exists = true;
					break;
				}
			}
🤖 Prompt for AI Agents
In src/converters/pdf/BinaryLocator.ts around lines 52 to 56, the code only
checks for the Unix-style 'node_modules/.bin/pdf2img' which fails on Windows
where shims are 'pdf2img.cmd' or 'pdf2img.ps1' (or .exe). Update the logic to
build a candidate list based on process.platform (on win32 include pdf2img.cmd,
pdf2img.ps1, pdf2img.exe and the POSIX name), iterate candidates calling
this.validateBinaryExists(plugin) for each, pick the first existing path and use
it, and only fail if none of the platform-specific candidates exist; keep
behavior unchanged for non-Windows platforms.

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Handle Windows shims in node_modules/.bin** On Windows, the executable is typically pdf2img.cmd (or .ps1). Probe platform-specific candidates before failing. Apply this diff: ```diff - const pdf2imgPath = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img'); - - // Check if the binary exists - const exists = await this.validateBinaryExists(pdf2imgPath, plugin); + const base = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img'); + const candidates = process.platform === 'win32' + ? [base + '.cmd', base + '.ps1', base] + : [base]; + let pdf2imgPath = candidates[0]; + let exists = false; + for (const c of candidates) { + if (await this.validateBinaryExists(c, plugin)) { + pdf2imgPath = c; + exists = true; + break; + } + } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const base = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img'); const candidates = process.platform === 'win32' ? [base + '.cmd', base + '.ps1', base] : [base]; let pdf2imgPath = candidates[0]; let exists = false; for (const c of candidates) { if (await this.validateBinaryExists(c, plugin)) { pdf2imgPath = c; exists = true; break; } } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/BinaryLocator.ts around lines 52 to 56, the code only checks for the Unix-style 'node_modules/.bin/pdf2img' which fails on Windows where shims are 'pdf2img.cmd' or 'pdf2img.ps1' (or .exe). Update the logic to build a candidate list based on process.platform (on win32 include pdf2img.cmd, pdf2img.ps1, pdf2img.exe and the POSIX name), iterate candidates calling this.validateBinaryExists(plugin) for each, pick the first existing path and use it, and only fail if none of the platform-specific candidates exist; keep behavior unchanged for non-Windows platforms. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
// 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 {
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 {
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}`
};
}
coderabbitai[bot] commented 2025-09-25 16:51:33 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Use manifest.id for folder name; manifest.dir may be undefined or absolute

Using manifest.dir here is risky (often undefined or absolute), which can break downstream joins. Prefer manifest.id (the plugin folder) for consistent resolution.

Apply this diff:

-			const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
+			const pluginDirName = plugin?.manifest?.id || 'typst-pdf-export';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const pluginDirName = plugin?.manifest?.id || 'typst-pdf-export';
			const configDir = plugin?.app.vault.configDir || '.obsidian';
			const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
🤖 Prompt for AI Agents
In src/converters/pdf/BinaryLocator.ts around lines 32 to 35, the code uses
plugin?.manifest?.dir for the plugin folder which can be undefined or an
absolute path and break downstream joins; change it to use plugin?.manifest?.id
(the plugin folder name) as the primary value and fall back to a safe literal
like 'typst-pdf-export' or plugin.id if manifest.id is missing; keep configDir
as plugin?.app.vault.configDir || '.obsidian' and pass the new pluginDirName
into getPossiblePluginDirs so subsequent path joins use a consistent,
non-absolute folder name.
_⚠️ Potential issue_ | _🟠 Major_ **Use manifest.id for folder name; manifest.dir may be undefined or absolute** Using `manifest.dir` here is risky (often undefined or absolute), which can break downstream joins. Prefer `manifest.id` (the plugin folder) for consistent resolution. Apply this diff: ```diff - const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export'; + const pluginDirName = plugin?.manifest?.id || 'typst-pdf-export'; ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const pluginDirName = plugin?.manifest?.id || 'typst-pdf-export'; const configDir = plugin?.app.vault.configDir || '.obsidian'; const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/BinaryLocator.ts around lines 32 to 35, the code uses plugin?.manifest?.dir for the plugin folder which can be undefined or an absolute path and break downstream joins; change it to use plugin?.manifest?.id (the plugin folder name) as the primary value and fall back to a safe literal like 'typst-pdf-export' or plugin.id if manifest.id is missing; keep configDir as plugin?.app.vault.configDir || '.obsidian' and pass the new pluginDirName into getPossiblePluginDirs so subsequent path joins use a consistent, non-absolute folder name. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
return {
binaryPath: pdf2imgPath,
exists: true
};
// Try to find the binary with platform-specific handling
const binaryLocation = await this.findBinaryWithFallbacks(pluginDir, plugin);
return binaryLocation;
} catch (error: unknown) {
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.
* @param plugin Plugin instance
@@ -83,19 +137,27 @@ export class BinaryLocator {
// Strategy 2: Assuming we're running from vault root
coderabbitai[bot] commented 2025-09-25 16:21:14 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Fix false negatives for binaries outside the vault and when plugin is undefined

validateBinaryExists returns false without trying FS when plugin is missing, and PathUtils.fileExists doesn’t reliably detect absolute Windows paths (uses “/” check). Add FS fallback so global installs (e.g., %APPDATA%\npm\pdf2img.cmd) are detected.

-	private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> {
-		try {
-			if (!plugin?.app) {
-				return false;
-			}
-			const pathUtils = new PathUtils(plugin.app);
-			return await pathUtils.fileExists(binaryPath);
-		} catch {
-			return false;
-		}
-	}
+	private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> {
+		try {
+			// Prefer vault-aware check when available
+			if (plugin?.app) {
+				const pathUtils = new PathUtils(plugin.app);
+				if (await pathUtils.fileExists(binaryPath)) {
+					return true;
+				}
+			}
+			// Fallback: direct FS check (needed for absolute paths outside the vault, especially on Windows)
+			const fs = require('fs').promises;
+			await fs.access(binaryPath);
+			return true;
+		} catch {
+			return false;
+		}
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> {
		try {
			// Prefer vault-aware check when available
			if (plugin?.app) {
				const pathUtils = new PathUtils(plugin.app);
				if (await pathUtils.fileExists(binaryPath)) {
					return true;
				}
			}
			// Fallback: direct FS check (needed for absolute paths outside the vault, especially on Windows)
			const fs = require('fs').promises;
			await fs.access(binaryPath);
			return true;
		} catch {
			return false;
		}
	}
🤖 Prompt for AI Agents
In src/converters/pdf/BinaryLocator.ts around lines 150 to 157, the
validateBinaryExists function returns false when plugin is undefined and relies
on PathUtils.fileExists which misses absolute Windows paths; update the function
to (1) if plugin is undefined or pathUtils.fileExists returns false for the
given path, attempt a filesystem fallback by normalizing the path (handle
Windows backslashes) and using fs.promises.access (or fs.existsSync) to check
the binaryPath directly, (2) detect Windows absolute paths (drive letter + :\ or
UNC \\) rather than relying on a "/" check, and (3) propagate or log errors
minimally but return true only if the fs access succeeds, false otherwise.

✅ Addressed in commits a129380 to 731a76e

_⚠️ Potential issue_ | _🟠 Major_ **Fix false negatives for binaries outside the vault and when plugin is undefined** `validateBinaryExists` returns false without trying FS when `plugin` is missing, and `PathUtils.fileExists` doesn’t reliably detect absolute Windows paths (uses “/” check). Add FS fallback so global installs (e.g., %APPDATA%\npm\pdf2img.cmd) are detected. ```diff - private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> { - try { - if (!plugin?.app) { - return false; - } - const pathUtils = new PathUtils(plugin.app); - return await pathUtils.fileExists(binaryPath); - } catch { - return false; - } - } + private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> { + try { + // Prefer vault-aware check when available + if (plugin?.app) { + const pathUtils = new PathUtils(plugin.app); + if (await pathUtils.fileExists(binaryPath)) { + return true; + } + } + // Fallback: direct FS check (needed for absolute paths outside the vault, especially on Windows) + const fs = require('fs').promises; + await fs.access(binaryPath); + return true; + } catch { + return false; + } + } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> { try { // Prefer vault-aware check when available if (plugin?.app) { const pathUtils = new PathUtils(plugin.app); if (await pathUtils.fileExists(binaryPath)) { return true; } } // Fallback: direct FS check (needed for absolute paths outside the vault, especially on Windows) const fs = require('fs').promises; await fs.access(binaryPath); return true; } catch { return false; } } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/BinaryLocator.ts around lines 150 to 157, the validateBinaryExists function returns false when plugin is undefined and relies on PathUtils.fileExists which misses absolute Windows paths; update the function to (1) if plugin is undefined or pathUtils.fileExists returns false for the given path, attempt a filesystem fallback by normalizing the path (handle Windows backslashes) and using fs.promises.access (or fs.existsSync) to check the binaryPath directly, (2) detect Windows absolute paths (drive letter + :\ or UNC \\) rather than relying on a "/" check, and (3) propagate or log errors minimally but return true only if the fs access succeeds, false otherwise. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 731a76e
path.join(configDir, 'plugins', pluginDirName),
// 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.
* @param binaryPath Full path to the binary
* @param plugin Plugin instance for PathUtils
* @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 {
const fs2 = require('fs');
return fs2.existsSync(binaryPath);
if (!plugin?.app) {
// 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 {
return false;
}
+194 -39
View File
@@ -3,8 +3,9 @@
* Handles filename pattern matching when pdf2img generates files with different names.
*/
import * as fs from 'fs/promises';
import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
export interface FileDiscoveryResult {
/** Path to the discovered file */
@@ -16,65 +17,186 @@ export interface FileDiscoveryResult {
}
coderabbitai[bot] commented 2025-09-25 16:21:15 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🔴 Critical

Vault adapter requires vault-relative paths; branch to FS for absolute outputDir

adapter.list(outputDir) will throw for absolute paths (typical for temp dirs). Convert to vault-relative when inside the vault; otherwise delegate to the FS fallback.

-			// Debug: List what files are actually in the output directory
-			const dirList = await plugin.app.vault.adapter.list(outputDir);
-			const files = dirList.files.map(f => path.basename(f));
-			const pathUtils = new PathUtils(plugin.app);
+			const pathUtils = new PathUtils(plugin.app);
+			const vaultBase = pathUtils.getVaultPath();
+
+			// Determine adapter list target (must be vault-relative). If outside vault, use FS fallback.
+			let listTarget = outputDir;
+			if (path.isAbsolute(outputDir)) {
+				if (outputDir.startsWith(vaultBase)) {
+					listTarget = outputDir.slice(vaultBase.length).replace(/^[/\\]/, '');
+				} else {
+					return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath);
+				}
+			}
+
+			// Debug: List what files are actually in the output directory
+			const dirList = await plugin.app.vault.adapter.list(listTarget);
+			const files = dirList.files.map(f => path.basename(f));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		try {
			const pathUtils = new PathUtils(plugin.app);
			const vaultBase = pathUtils.getVaultPath();

			// Determine adapter list target (must be vault-relative). If outside vault, use FS fallback.
			let listTarget = outputDir;
			if (path.isAbsolute(outputDir)) {
				if (outputDir.startsWith(vaultBase)) {
					listTarget = outputDir.slice(vaultBase.length).replace(/^[/\\]/, '');
				} else {
					return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath);
				}
			}

			// Debug: List what files are actually in the output directory
			const dirList = await plugin.app.vault.adapter.list(listTarget);
			const files = dirList.files.map(f => path.basename(f));
🤖 Prompt for AI Agents
In src/converters/pdf/FileDiscovery.ts around lines 83-88, the current call
plugin.app.vault.adapter.list(outputDir) will throw for absolute (temp) paths;
detect whether outputDir is inside the vault by comparing it to the vault root
(compute a relative path from the vault root and ensure it doesn't start with
'..' or a path separator), and if it is inside the vault call adapter.list with
that vault-relative path, otherwise skip the adapter and call the FS fallback
(use the existing FS-based listing logic) for absolute paths; ensure the code
branches cleanly so adapter.list is only invoked with vault-relative paths.

✅ Addressed in commits a129380 to 731a76e

_⚠️ Potential issue_ | _🔴 Critical_ **Vault adapter requires vault-relative paths; branch to FS for absolute outputDir** `adapter.list(outputDir)` will throw for absolute paths (typical for temp dirs). Convert to vault-relative when inside the vault; otherwise delegate to the FS fallback. ```diff - // Debug: List what files are actually in the output directory - const dirList = await plugin.app.vault.adapter.list(outputDir); - const files = dirList.files.map(f => path.basename(f)); - const pathUtils = new PathUtils(plugin.app); + const pathUtils = new PathUtils(plugin.app); + const vaultBase = pathUtils.getVaultPath(); + + // Determine adapter list target (must be vault-relative). If outside vault, use FS fallback. + let listTarget = outputDir; + if (path.isAbsolute(outputDir)) { + if (outputDir.startsWith(vaultBase)) { + listTarget = outputDir.slice(vaultBase.length).replace(/^[/\\]/, ''); + } else { + return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath); + } + } + + // Debug: List what files are actually in the output directory + const dirList = await plugin.app.vault.adapter.list(listTarget); + const files = dirList.files.map(f => path.basename(f)); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion try { const pathUtils = new PathUtils(plugin.app); const vaultBase = pathUtils.getVaultPath(); // Determine adapter list target (must be vault-relative). If outside vault, use FS fallback. let listTarget = outputDir; if (path.isAbsolute(outputDir)) { if (outputDir.startsWith(vaultBase)) { listTarget = outputDir.slice(vaultBase.length).replace(/^[/\\]/, ''); } else { return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath); } } // Debug: List what files are actually in the output directory const dirList = await plugin.app.vault.adapter.list(listTarget); const files = dirList.files.map(f => path.basename(f)); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/FileDiscovery.ts around lines 83-88, the current call plugin.app.vault.adapter.list(outputDir) will throw for absolute (temp) paths; detect whether outputDir is inside the vault by comparing it to the vault root (compute a relative path from the vault root and ensure it doesn't start with '..' or a path separator), and if it is inside the vault call adapter.list with that vault-relative path, otherwise skip the adapter and call the FS fallback (use the existing FS-based listing logic) for absolute paths; ensure the code branches cleanly so adapter.list is only invoked with vault-relative paths. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 731a76e
export class FileDiscovery {
/** Supported image extensions for PDF conversion output */
private static readonly SUPPORTED_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff'];
/**
coderabbitai[bot] commented 2025-09-25 13:05:39 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Don’t hard‑code .png when searching for generated previews

Both vault-adapter and FS fallbacks now throw away every candidate that doesn’t end in .png. As soon as we request JPEG output (which ImageOptimizer explicitly supports), candidates becomes empty and we report “file not found” even though a perfectly good .jpeg/.jpg file is sitting in the directory. That’s a regression for anyone relying on JPEG previews.

Please derive the allowed extensions from expectedFileName (and treat .jpeg/.jpg as interchangeable) before filtering, in both branches.

-			// Look for any PNG files that might match
-			const pngFiles = files.filter(f => f.endsWith('.png'));
-			if (pngFiles.length === 0) {
+			const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase();
+			const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt];
+			const candidateFiles = files.filter(f => {
+				const lower = f.toLowerCase();
+				return allowedExts.some(ext => lower.endsWith(ext));
+			});
+			if (candidateFiles.length === 0) {
 				return {
 					filePath: '',
 					found: false,
-					error: `No PNG files found in output directory: ${outputDir}`
+					error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}`
 				};
 			}
 
 			// Try to find a file that matches the pattern (with or without exact name)
 			// pdf2img might sanitize filenames differently
-			const matchingFile = this.matchFilePattern(pngFiles, expectedFileName);
+			const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName);
@@
-					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}`
+					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}`
 				};
 			}

Apply the same adjustment inside findAlternativeFileFs.

-			const pngFiles = files.filter((f: string) => f.endsWith('.png'));
-			if (pngFiles.length === 0) {
+			const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase();
+			const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt];
+			const candidateFiles = files.filter((f: string) => {
+				const lower = f.toLowerCase();
+				return allowedExts.some(ext => lower.endsWith(ext));
+			});
+			if (candidateFiles.length === 0) {
 				return {
 					filePath: '',
 					found: false,
-					error: `No PNG files found in output directory: ${outputDir}`
+					error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}`
 				};
 			}
@@
-			const matchingFile = this.matchFilePattern(pngFiles, expectedFileName);
+			const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName);
@@
-					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}`
+					error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}`
 				};

Also applies to: 154-190

🤖 Prompt for AI Agents
In src/converters/pdf/FileDiscovery.ts around lines 88-123 (and similarly update
the logic in findAlternativeFileFs at lines ~154-190), the code currently
hard-codes filtering for ".png" files; change it to derive the allowed
extensions from expectedFileName (e.g., if expectedFileName ends with .jpg or
.jpeg treat both .jpg and .jpeg as allowed), build a set of allowed extensions
(include the explicit extension plus normalized jpeg variants), filter files by
those extensions instead of ".png", then use that filtered list for
matchFilePattern and subsequent checks; replicate the same extension-derivation
+ filtering change in the findAlternativeFileFs branch so JPEG output is
discovered correctly.

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Don’t hard‑code `.png` when searching for generated previews** Both vault-adapter and FS fallbacks now throw away every candidate that doesn’t end in `.png`. As soon as we request JPEG output (which `ImageOptimizer` explicitly supports), `candidates` becomes empty and we report “file not found” even though a perfectly good `.jpeg/.jpg` file is sitting in the directory. That’s a regression for anyone relying on JPEG previews. Please derive the allowed extensions from `expectedFileName` (and treat `.jpeg`/`.jpg` as interchangeable) before filtering, in both branches. ```diff - // Look for any PNG files that might match - const pngFiles = files.filter(f => f.endsWith('.png')); - if (pngFiles.length === 0) { + const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase(); + const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt]; + const candidateFiles = files.filter(f => { + const lower = f.toLowerCase(); + return allowedExts.some(ext => lower.endsWith(ext)); + }); + if (candidateFiles.length === 0) { return { filePath: '', found: false, - error: `No PNG files found in output directory: ${outputDir}` + error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}` }; } // Try to find a file that matches the pattern (with or without exact name) // pdf2img might sanitize filenames differently - const matchingFile = this.matchFilePattern(pngFiles, expectedFileName); + const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName); @@ - error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}` + error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}` }; } ``` Apply the same adjustment inside `findAlternativeFileFs`. ```diff - const pngFiles = files.filter((f: string) => f.endsWith('.png')); - if (pngFiles.length === 0) { + const expectedExt = (path.extname(expectedFileName) || '.png').toLowerCase(); + const allowedExts = expectedExt === '.jpeg' ? ['.jpeg', '.jpg'] : [expectedExt]; + const candidateFiles = files.filter((f: string) => { + const lower = f.toLowerCase(); + return allowedExts.some(ext => lower.endsWith(ext)); + }); + if (candidateFiles.length === 0) { return { filePath: '', found: false, - error: `No PNG files found in output directory: ${outputDir}` + error: `No ${allowedExts.join('/')} files found in output directory: ${outputDir}` }; } @@ - const matchingFile = this.matchFilePattern(pngFiles, expectedFileName); + const matchingFile = this.matchFilePattern(candidateFiles, expectedFileName); @@ - error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}` + error: `Generated image file not found: ${expectedOutputPath}. Available files: ${candidateFiles.join(', ')}` }; ``` Also applies to: 154-190 <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/FileDiscovery.ts around lines 88-123 (and similarly update the logic in findAlternativeFileFs at lines ~154-190), the code currently hard-codes filtering for ".png" files; change it to derive the allowed extensions from expectedFileName (e.g., if expectedFileName ends with .jpg or .jpeg treat both .jpg and .jpeg as allowed), build a set of allowed extensions (include the explicit extension plus normalized jpeg variants), filter files by those extensions instead of ".png", then use that filtered list for matchFilePattern and subsequent checks; replicate the same extension-derivation + filtering change in the findAlternativeFileFs branch so JPEG output is discovered correctly. ``` </details> <!-- fingerprinting:phantom:medusa:sabertoothed --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
* Find the generated image file in the output directory.
* Handles cases where pdf2img sanitizes filenames differently than expected.
* @param outputDir Directory where files were generated
* @param expectedFileName Expected output filename
* @param plugin Plugin instance for PathUtils
* @returns Discovery result with actual file path
*/
public static async findGeneratedFile(
outputDir: string,
expectedFileName: string
expectedFileName: string,
plugin?: obsidianTypstPDFExport
): 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
try {
await fs.access(expectedOutputPath);
return {
filePath: expectedOutputPath,
found: true
};
if (await pathUtils.fileExists(expectedOutputPath)) {
return {
filePath: expectedOutputPath,
found: true
};
}
} catch {
// File not found with expected name, try to find alternatives
return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath);
// Continue to alternative search
}
// 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 expectedFileName Expected filename for pattern matching
* @param expectedOutputPath Full expected output path
* @param plugin Plugin instance for vault access
* @returns Discovery result with alternative file if found
*/
private static async findAlternativeFile(
outputDir: string,
expectedFileName: string,
expectedOutputPath: string
expectedOutputPath: string,
plugin: obsidianTypstPDFExport
): Promise<FileDiscoveryResult> {
try {
// Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir);
// Look for any PNG files that might match
const pngFiles = files.filter(f => f.endsWith('.png'));
if (pngFiles.length === 0) {
const pathUtils = new PathUtils(plugin.app);
// Check if outputDir is inside the vault
const vaultPath = plugin.app.vault.adapter.basePath || '';
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 {
filePath: '',
found: false,
coderabbitai[bot] commented 2025-09-25 16:51:33 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Compute vault-relative path without path.relative; normalize separators

Using path.relative(base, outputDir) is fragile across platforms and separator styles. Use PathUtils.getVaultPath() and strip the prefix instead, ensuring forward slashes for adapter.list.

-			// Check if outputDir is inside the vault
-			const vaultPath = plugin.app.vault.adapter.basePath || '';
-			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;
-				}
-			}
+			// Check if outputDir is inside the vault using PathUtils
+			const vaultPath = pathUtils.getVaultPath();
+			let isVaultRelative = false;
+			let vaultRelativeDir = outputDir;
+			if (outputDir.startsWith(vaultPath)) {
+				vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, '');
+				isVaultRelative = true;
+			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			// Check if outputDir is inside the vault using PathUtils
			const vaultPath = pathUtils.getVaultPath();
			let isVaultRelative = false;
			let vaultRelativeDir = outputDir;
			if (outputDir.startsWith(vaultPath)) {
				vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, '');
				isVaultRelative = true;
			}
🤖 Prompt for AI Agents
In src/converters/pdf/FileDiscovery.ts around lines 87 to 99, replace the
path.relative-based vault detection with a prefix-strip approach: obtain the
vault root via PathUtils.getVaultPath(), normalize both vault root and outputDir
to use forward slashes and no trailing slash, check if outputDir starts with the
vault root + '/' to set isVaultRelative, and if so set vaultRelativeDir to the
substring after the vault root (ensuring it uses forward slashes) so
adapter.list receives a vault-relative path; otherwise keep vaultRelativeDir as
the original outputDir.
_⚠️ Potential issue_ | _🟠 Major_ **Compute vault-relative path without path.relative; normalize separators** Using `path.relative(base, outputDir)` is fragile across platforms and separator styles. Use `PathUtils.getVaultPath()` and strip the prefix instead, ensuring forward slashes for adapter.list. ```diff - // Check if outputDir is inside the vault - const vaultPath = plugin.app.vault.adapter.basePath || ''; - 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; - } - } + // Check if outputDir is inside the vault using PathUtils + const vaultPath = pathUtils.getVaultPath(); + let isVaultRelative = false; + let vaultRelativeDir = outputDir; + if (outputDir.startsWith(vaultPath)) { + vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, ''); + isVaultRelative = true; + } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // Check if outputDir is inside the vault using PathUtils const vaultPath = pathUtils.getVaultPath(); let isVaultRelative = false; let vaultRelativeDir = outputDir; if (outputDir.startsWith(vaultPath)) { vaultRelativeDir = outputDir.substring(vaultPath.length).replace(/^[/\\]+/, ''); isVaultRelative = true; } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/FileDiscovery.ts around lines 87 to 99, replace the path.relative-based vault detection with a prefix-strip approach: obtain the vault root via PathUtils.getVaultPath(), normalize both vault root and outputDir to use forward slashes and no trailing slash, check if outputDir starts with the vault root + '/' to set isVaultRelative, and if so set vaultRelativeDir to the substring after the vault root (ensuring it uses forward slashes) so adapter.list receives a vault-relative path; otherwise keep vaultRelativeDir as the original outputDir. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
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)
// 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) {
const actualOutputPath = path.join(outputDir, matchingFile);
// Final check if we found an alternative file
try {
await fs.access(actualOutputPath);
@@ -93,7 +215,7 @@ export class FileDiscovery {
return {
filePath: '',
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 +231,55 @@ export class FileDiscovery {
}
/**
* Match files against expected filename patterns.
* Handles filename sanitization that pdf2img might apply.
* Match files against expected filename patterns using multiple strategies.
* Handles filename sanitization that pdf2img might apply and supports multiple image formats.
* @param files Array of available filenames
* @param expectedFileName Expected filename pattern
* @returns Matching filename or null if no match found
*/
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);
if (exactMatch) {
return exactMatch;
}
// Try partial match by removing special characters
const simplifiedExpected = this.sanitizeFilename(expectedFileName);
const matchingFile = files.find(f => {
const simplifiedActual = this.sanitizeFilename(f);
return simplifiedActual === simplifiedExpected;
// Strategy 2: Base name match with any supported extension
const baseNameMatch = files.find(f => {
const fileBase = path.basename(f, path.extname(f));
return fileBase === expectedBase;
});
if (matchingFile) {
return matchingFile;
if (baseNameMatch) {
return baseNameMatch;
}
// 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;
}
@@ -148,10 +294,10 @@ export class FileDiscovery {
/**
* 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 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
*/
public static generateExpectedFilename(
@@ -159,6 +305,15 @@ export class FileDiscovery {
pageNumber: number = 1,
format: string = 'png'
): 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.
*/
import * as fs from 'fs/promises';
import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
export interface ImageOptimizationOptions {
/** Output format (default: 'png') */
@@ -183,7 +184,8 @@ export class ImageOptimizer {
inputImagePath: string,
outputDir: string,
baseFileName: string,
options: ImageOptimizationOptions = {}
options: ImageOptimizationOptions = {},
plugin?: obsidianTypstPDFExport
): Promise<ImageOptimizationResult> {
try {
const opts = {
@@ -193,7 +195,13 @@ export class ImageOptimizer {
// Generate final output path
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;
@@ -209,7 +217,25 @@ export class ImageOptimizer {
if (conversionResult.success) {
// Clean up the original PNG if conversion succeeded
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) {
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}`);
// Just rename the file to PNG format
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;
}
} else {
// 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;
}
1
+125
View File
@@ -0,0 +1,125 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
coderabbitai[bot] commented 2025-09-25 13:05:40 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Windows absolute paths are not detected in fileExists

The heuristic path.includes('/') && !path.startsWith('.') misses Windows absolute paths (e.g., C:\foo\bar). Use path.isAbsolute instead.

Apply this diff:

-		// For paths outside vault, use fs fallback (needed for external file processing)
-		if (path.includes('/') && !path.startsWith('.')) {
-			try {
-				const fs = require('fs').promises;
-				await fs.access(path);
-				return true;
-			} catch {
-				return false;
-			}
-		}
+		// For paths outside vault, use fs fallback (needed for external file processing)
+		try {
+			const nodePath = require('path') as typeof import('path');
+			if (nodePath.isAbsolute(path)) {
+				const fs = require('fs').promises as typeof import('fs').promises;
+				await fs.access(path);
+				return true;
+			}
+		} catch {
+			// ignore
+		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        // For paths outside vault, use fs fallback (needed for external file processing)
        try {
            const nodePath = require('path') as typeof import('path');
            if (nodePath.isAbsolute(path)) {
                const fs = require('fs').promises as typeof import('fs').promises;
                await fs.access(path);
                return true;
            }
        } catch {
            // ignore
        }

        return false;
🤖 Prompt for AI Agents
In src/core/PathUtils.ts around lines 108-119, the current heuristic using
path.includes('/') && !path.startsWith('.') misses Windows absolute paths;
replace that check with a proper absolute-path test using Node's
path.isAbsolute. Import or require the Node path module without shadowing the
function parameter (e.g., const nodePath = require('path') or import * as
nodePath from 'path') and use nodePath.isAbsolute(path) in the conditional so
both Unix and Windows absolute paths are detected; keep the existing
fs.promises.access fallback and preserve the try/catch behavior.

✅ Addressed in commit ff8e9f9

_⚠️ Potential issue_ | _🟠 Major_ **Windows absolute paths are not detected in fileExists** The heuristic `path.includes('/') && !path.startsWith('.')` misses Windows absolute paths (e.g., C:\foo\bar). Use path.isAbsolute instead. Apply this diff: ```diff - // For paths outside vault, use fs fallback (needed for external file processing) - if (path.includes('/') && !path.startsWith('.')) { - try { - const fs = require('fs').promises; - await fs.access(path); - return true; - } catch { - return false; - } - } + // For paths outside vault, use fs fallback (needed for external file processing) + try { + const nodePath = require('path') as typeof import('path'); + if (nodePath.isAbsolute(path)) { + const fs = require('fs').promises as typeof import('fs').promises; + await fs.access(path); + return true; + } + } catch { + // ignore + } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // For paths outside vault, use fs fallback (needed for external file processing) try { const nodePath = require('path') as typeof import('path'); if (nodePath.isAbsolute(path)) { const fs = require('fs').promises as typeof import('fs').promises; await fs.access(path); return true; } } catch { // ignore } return false; ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/core/PathUtils.ts around lines 108-119, the current heuristic using path.includes('/') && !path.startsWith('.') misses Windows absolute paths; replace that check with a proper absolute-path test using Node's path.isAbsolute. Import or require the Node path module without shadowing the function parameter (e.g., const nodePath = require('path') or import * as nodePath from 'path') and use nodePath.isAbsolute(path) in the conditional so both Unix and Windows absolute paths are detected; keep the existing fs.promises.access fallback and preserve the try/catch behavior. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit ff8e9f9 <!-- This is an auto-generated comment by CodeRabbit -->
AlexKucera commented 2025-09-25 16:27:04 +02:00 (Migrated from github.com)
Review

@coderabbitai we are trying to stay away from using path and sticking to Obsidian API calls.

@coderabbitai we are trying to stay away from using path and sticking to Obsidian API calls.
coderabbitai[bot] commented 2025-09-25 16:27:33 +02:00 (Migrated from github.com)
Review

@AlexKucera I understand your preference to stick with Obsidian APIs. Here's an alternative approach that improves Windows absolute path detection without using the Node.js path module:

// 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;
    }
}

This pattern-based approach detects:

  • Unix absolute paths starting with /
  • Windows drive letter paths like C:\ or C:/
  • Windows UNC paths like \\server\share

This keeps the code aligned with your goal of avoiding Node.js path utilities while fixing the Windows compatibility issue.


✏️ Learnings added
Learnt from: AlexKucera
PR: AlexKucera/obsidian-typst-pdf-export#5
File: src/core/PathUtils.ts:108-119
Timestamp: 2025-09-25T14:27:31.819Z
Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@AlexKucera I understand your preference to stick with Obsidian APIs. Here's an alternative approach that improves Windows absolute path detection without using the Node.js path module: ```typescript // 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; } } ``` This pattern-based approach detects: - Unix absolute paths starting with `/` - Windows drive letter paths like `C:\` or `C:/` - Windows UNC paths like `\\server\share` This keeps the code aligned with your goal of avoiding Node.js path utilities while fixing the Windows compatibility issue. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera PR: AlexKucera/obsidian-typst-pdf-export#5 File: src/core/PathUtils.ts:108-119 Timestamp: 2025-09-25T14:27:31.819Z Learning: The obsidian-typst-pdf-export plugin prefers to avoid Node.js built-in modules like 'path' and instead stick to Obsidian API calls for path operations. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> <!-- This is an auto-generated reply by CodeRabbit -->
// 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;
}
}
+37 -31
View File
@@ -1,8 +1,9 @@
/**
* Manages temporary directories for export operations
*/
// ABOUTME: Manages temporary directories for export operations
// ABOUTME: Uses normalizePath for cross-platform path operations
import { PLUGIN_DIRS } from './constants';
import { normalizePath } from 'obsidian';
import type { App } from 'obsidian';
export interface TempDirectoryOptions {
/** Base path for the vault */
@@ -11,26 +12,28 @@ export interface TempDirectoryOptions {
configDir: string;
/** Plugin directory name (defaults to 'typst-pdf-export') */
pluginName?: string;
/** App instance for vault.adapter operations */
app: App;
}
export class TempDirectoryManager {
private readonly fs = require('fs');
private readonly path = require('path');
private readonly vaultPath: string;
private readonly configDir: string;
private readonly pluginName: string;
private readonly app: App;
constructor(options: TempDirectoryOptions) {
this.vaultPath = options.vaultPath;
this.configDir = options.configDir;
this.pluginName = options.pluginName || 'typst-pdf-export';
this.app = options.app;
}
/**
* Get the plugin directory path
*/
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,59 +41,60 @@ export class TempDirectoryManager {
*/
public getTempDir(type: 'images' | 'pandoc'): string {
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
*/
public ensureTempDir(type: 'images' | 'pandoc'): string {
public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
const tempDir = this.getTempDir(type);
if (!this.fs.existsSync(tempDir)) {
this.fs.mkdirSync(tempDir, { recursive: true });
const exists = await this.app.vault.adapter.exists(tempDir);
if (!exists) {
await this.app.vault.adapter.mkdir(tempDir);
}
return tempDir;
}
/**
* 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);
try {
if (this.fs.existsSync(tempDir)) {
const files = this.fs.readdirSync(tempDir);
for (const file of files) {
this.fs.unlinkSync(this.path.join(tempDir, file));
const exists = await this.app.vault.adapter.exists(tempDir);
if (exists) {
const list = await this.app.vault.adapter.list(tempDir);
// 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) {
coderabbitai[bot] commented 2025-09-25 16:51:34 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🔴 Critical

adapter.exists/mkdir need vault-relative path (don’t pass absolute tempDir)

tempDir is absolute; convert to vault-relative before calling adapter methods to avoid path mismatches.

  public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
    const tempDir = this.getTempDir(type);
-
-    const exists = await this.app.vault.adapter.exists(tempDir);
-    if (!exists) {
-      await this.app.vault.adapter.mkdir(tempDir);
-    }
+    const rel = tempDir.startsWith(this.vaultPath)
+      ? tempDir.substring(this.vaultPath.length).replace(/^[/\\]+/, '')
+      : tempDir;
+    const exists = await this.app.vault.adapter.exists(rel);
+    if (!exists) {
+      await this.app.vault.adapter.mkdir(rel);
+    }
 
    return tempDir;
  }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/core/TempDirectoryManager.ts around lines 50 to 56, the code calls
this.app.vault.adapter.exists/mkdir with an absolute tempDir which the adapter
expects as a vault-relative path; convert the absolute tempDir to a
vault-relative path first (e.g., strip the vault root / compute relative path)
and use that relative path when calling adapter.exists and adapter.mkdir,
assigning the relative path to a variable and passing that variable to both
adapter calls.
_⚠️ Potential issue_ | _🔴 Critical_ **adapter.exists/mkdir need vault-relative path (don’t pass absolute tempDir)** `tempDir` is absolute; convert to vault-relative before calling adapter methods to avoid path mismatches. ```diff public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> { const tempDir = this.getTempDir(type); - - const exists = await this.app.vault.adapter.exists(tempDir); - if (!exists) { - await this.app.vault.adapter.mkdir(tempDir); - } + const rel = tempDir.startsWith(this.vaultPath) + ? tempDir.substring(this.vaultPath.length).replace(/^[/\\]+/, '') + : tempDir; + const exists = await this.app.vault.adapter.exists(rel); + if (!exists) { + await this.app.vault.adapter.mkdir(rel); + } return tempDir; } ``` > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/core/TempDirectoryManager.ts around lines 50 to 56, the code calls this.app.vault.adapter.exists/mkdir with an absolute tempDir which the adapter expects as a vault-relative path; convert the absolute tempDir to a vault-relative path first (e.g., strip the vault root / compute relative path) and use that relative path when calling adapter.exists and adapter.mkdir, assigning the relative path to a variable and passing that variable to both adapter calls. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
console.warn(`Export: Failed to clean up ${type === 'images' ? 'temp-images' : 'temp-pandoc'} directory:`, error);
return false;
}
return true;
}
/**
* Clean up all temp directories
*/
public cleanupAllTempDirs(): { images: boolean; pandoc: boolean } {
public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> {
return {
images: this.cleanupTempDir('images'),
pandoc: this.cleanupTempDir('pandoc')
images: await this.cleanupTempDir('images'),
pandoc: await this.cleanupTempDir('pandoc')
};
}
/**
* Static helper to create manager from vault path and configDir
*/
public static create(vaultPath: string, configDir: string, pluginName?: string): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, configDir, pluginName });
public static create(vaultPath: string, configDir: string, pluginName: string | undefined, app: App): TempDirectoryManager {
return new TempDirectoryManager({ vaultPath, configDir, pluginName, app });
}
/**
@@ -98,10 +102,12 @@ export class TempDirectoryManager {
*/
public isPluginTempDir(dirPath: string): boolean {
const pluginDir = this.getPluginDir();
const normalizedPath = this.path.resolve(dirPath);
const normalizedPluginDir = this.path.resolve(pluginDir);
return normalizedPath.startsWith(normalizedPluginDir) &&
(dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC));
const normalizedDirPath = normalizePath(dirPath);
coderabbitai[bot] commented 2025-09-25 16:51:34 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🔴 Critical

adapter.list/remove must use vault-relative too

Same issue during cleanup; operate with vault-relative path to list and remove files correctly.

-      const exists = await this.app.vault.adapter.exists(tempDir);
-      if (exists) {
-        const list = await this.app.vault.adapter.list(tempDir);
+      const rel = tempDir.startsWith(this.vaultPath)
+        ? tempDir.substring(this.vaultPath.length).replace(/^[/\\]+/, '')
+        : tempDir;
+      const exists = await this.app.vault.adapter.exists(rel);
+      if (exists) {
+        const list = await this.app.vault.adapter.list(rel);
         // Remove only files, not subdirectories (matching current pattern)
         for (const file of list.files) {
           await this.app.vault.adapter.remove(file);
         }
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const rel = tempDir.startsWith(this.vaultPath)
				? tempDir.substring(this.vaultPath.length).replace(/^[/\\]+/, '')
				: tempDir;
			const exists = await this.app.vault.adapter.exists(rel);
			if (exists) {
				const list = await this.app.vault.adapter.list(rel);
				// Remove only files, not subdirectories (matching current pattern)
				for (const file of list.files) {
					await this.app.vault.adapter.remove(file);
				}
			}
			return true;
🤖 Prompt for AI Agents
In src/core/TempDirectoryManager.ts around lines 68-76, the cleanup currently
calls adapter.list and adapter.remove with paths that may be absolute; change
both calls to use vault-relative paths: pass a vault-relative tempDir into
adapter.list, then when iterating list.files map each entry to its
vault-relative path before calling adapter.remove so the adapter operates on
vault-relative paths consistently (i.e., compute/normalize vault-relative paths
for list and remove and use those).
_⚠️ Potential issue_ | _🔴 Critical_ **adapter.list/remove must use vault-relative too** Same issue during cleanup; operate with vault-relative path to list and remove files correctly. ```diff - const exists = await this.app.vault.adapter.exists(tempDir); - if (exists) { - const list = await this.app.vault.adapter.list(tempDir); + const rel = tempDir.startsWith(this.vaultPath) + ? tempDir.substring(this.vaultPath.length).replace(/^[/\\]+/, '') + : tempDir; + const exists = await this.app.vault.adapter.exists(rel); + if (exists) { + const list = await this.app.vault.adapter.list(rel); // Remove only files, not subdirectories (matching current pattern) for (const file of list.files) { await this.app.vault.adapter.remove(file); } } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const rel = tempDir.startsWith(this.vaultPath) ? tempDir.substring(this.vaultPath.length).replace(/^[/\\]+/, '') : tempDir; const exists = await this.app.vault.adapter.exists(rel); if (exists) { const list = await this.app.vault.adapter.list(rel); // Remove only files, not subdirectories (matching current pattern) for (const file of list.files) { await this.app.vault.adapter.remove(file); } } return true; ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/core/TempDirectoryManager.ts around lines 68-76, the cleanup currently calls adapter.list and adapter.remove with paths that may be absolute; change both calls to use vault-relative paths: pass a vault-relative tempDir into adapter.list, then when iterating list.files map each entry to its vault-relative path before calling adapter.remove so the adapter operates on vault-relative paths consistently (i.e., compute/normalize vault-relative paths for list and remove and use those). ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
const normalizedPluginDir = normalizePath(pluginDir);
const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/'));
const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/'));
return normalizedDirPath.startsWith(tempImagesDir) ||
normalizedDirPath.startsWith(tempPandocDir);
}
}
+47 -30
View File
@@ -7,11 +7,15 @@ import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main';
import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
import { ExportErrorHandler } from '../core/ExportErrorHandler';
import { PathUtils } from '../core/PathUtils';
import * as path from 'path';
import * as fs from 'fs';
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
@@ -126,9 +130,11 @@ export class EmbedProcessor {
// Try each possible path until we find one that exists
for (const possiblePath of possiblePaths) {
try {
await fs.promises.access(possiblePath);
fullImagePath = possiblePath;
break;
const exists = await this.pathUtils.fileExists(possiblePath);
if (exists) {
fullImagePath = possiblePath;
break;
}
} catch {
// File doesn't exist, continue to next path
}
@@ -150,10 +156,10 @@ export class EmbedProcessor {
// Convert WebP to PNG using ImageMagick
const originalImageName = path.basename(fullImagePath);
const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
const vaultTempImagesDir = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images');
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true });
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultTempImagesDir);
const convertedImagePath = path.join(vaultTempImagesDir, pngFileName);
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
const { exec } = require('child_process');
const util = require('util');
@@ -291,20 +297,22 @@ export class EmbedProcessor {
private async resolvePdfPath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise<string | null> {
// Decode the URL-encoded sanitized path back to normal characters
const decodedPath = decodeURIComponent(sanitizedPath);
// Strategy 1: Use Obsidian's link resolution API (primary strategy)
if (currentFile) {
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest(
decodedPath,
decodedPath,
currentFile.path
);
if (resolvedFile && resolvedFile instanceof TFile) {
// Convert to full filesystem path
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try {
await fs.promises.access(fullPath);
return fullPath;
const exists = await this.pathUtils.fileExists(fullPath);
if (exists) {
return fullPath;
}
} catch {
// 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
for (const possiblePath of possiblePaths) {
try {
await fs.promises.access(possiblePath);
return possiblePath;
const exists = await this.pathUtils.fileExists(possiblePath);
if (exists) {
return possiblePath;
}
} catch {
// File doesn't exist, continue to next path
}
@@ -338,20 +348,22 @@ export class EmbedProcessor {
private async resolveFilePath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise<string | null> {
// Decode the URL-encoded sanitized path back to normal characters
const decodedPath = decodeURIComponent(sanitizedPath);
// Strategy 1: Use Obsidian's link resolution API (primary strategy)
if (currentFile) {
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest(
decodedPath,
decodedPath,
currentFile.path
);
if (resolvedFile && resolvedFile instanceof TFile) {
// Convert to full filesystem path
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
try {
await fs.promises.access(fullPath);
return fullPath;
const exists = await this.pathUtils.fileExists(fullPath);
if (exists) {
return fullPath;
}
} catch {
// 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
for (const possiblePath of possiblePaths) {
try {
await fs.promises.access(possiblePath);
return possiblePath;
const exists = await this.pathUtils.fileExists(possiblePath);
if (exists) {
return possiblePath;
}
} catch {
// File doesn't exist, continue to next path
}
@@ -396,23 +410,26 @@ export class EmbedProcessor {
vaultBasePath: string
): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
// Copy image to vault temp directory for access
const vaultTempImagesDir = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images');
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true });
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultTempImagesDir);
// Sanitize the basename for use in filename - replace problematic characters
const sanitizedBaseName = baseName
.replace(/[^a-zA-Z0-9\-_]/g, '_') // Replace non-alphanumeric chars with underscore
.replace(/_{2,}/g, '_') // Collapse multiple underscores
.replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores
const imageFileName = `${sanitizedBaseName}_preview.png`;
const vaultImagePath = path.join(vaultTempImagesDir, imageFileName);
await fs.promises.copyFile(imagePath, vaultImagePath);
const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName);
// 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
const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
const relativePdfPath = path.relative(vaultBasePath, pdfPath);
return { relativeImagePath, relativePdfPath };
}
+17 -8
View File
@@ -11,10 +11,14 @@ import { ModalSettingsHelper } from '../core/ModalSettingsHelper';
import { MarkdownPreprocessor } from '../converters/MarkdownPreprocessor';
import { TempDirectoryManager } from '../core/TempDirectoryManager';
import { ExportErrorHandler } from '../core/ExportErrorHandler';
import * as path from 'path';
import { PathUtils } from '../core/PathUtils';
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
@@ -132,16 +136,21 @@ export class ExportOrchestrator {
* Export a file with specific configuration
coderabbitai[bot] commented 2025-09-25 13:05:40 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Pass plugin name to TempDirectoryManager (avoid default mismatch).

The default 'typst-pdf-export' may not match this plugin’s folder, causing temp dirs to be created under the wrong path.

-      const tempManager = new TempDirectoryManager({ vaultPath: vaultPath, configDir: this.plugin.app.vault.configDir, app: this.plugin.app });
+      const tempManager = new TempDirectoryManager({
+        vaultPath,
+        configDir: this.plugin.app.vault.configDir,
+        pluginName: this.plugin.manifest.id,
+        app: this.plugin.app
+      });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      const tempManager = new TempDirectoryManager({
        vaultPath,
        configDir: this.plugin.app.vault.configDir,
        pluginName: this.plugin.manifest.id,
        app: this.plugin.app
      });
      const tempDir = await tempManager.ensureTempDir('pandoc');
🤖 Prompt for AI Agents
In src/plugin/ExportOrchestrator.ts around lines 147 to 149, the
TempDirectoryManager is being constructed without the plugin name, which causes
it to default to 'typst-pdf-export' and create temp dirs in the wrong path;
update the constructor call to pass this plugin's actual name (e.g. use
this.plugin.manifest.name or a safe fallback like this.plugin.manifest.name ||
'<your-plugin-folder-name>') so TempDirectoryManager uses the correct folder for
temp directories.

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Pass plugin name to TempDirectoryManager (avoid default mismatch).** The default `'typst-pdf-export'` may not match this plugin’s folder, causing temp dirs to be created under the wrong path. ```diff - const tempManager = new TempDirectoryManager({ vaultPath: vaultPath, configDir: this.plugin.app.vault.configDir, app: this.plugin.app }); + const tempManager = new TempDirectoryManager({ + vaultPath, + configDir: this.plugin.app.vault.configDir, + pluginName: this.plugin.manifest.id, + app: this.plugin.app + }); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const tempManager = new TempDirectoryManager({ vaultPath, configDir: this.plugin.app.vault.configDir, pluginName: this.plugin.manifest.id, app: this.plugin.app }); const tempDir = await tempManager.ensureTempDir('pandoc'); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/ExportOrchestrator.ts around lines 147 to 149, the TempDirectoryManager is being constructed without the plugin name, which causes it to default to 'typst-pdf-export' and create temp dirs in the wrong path; update the constructor call to pass this plugin's actual name (e.g. use this.plugin.manifest.name or a safe fallback like this.plugin.manifest.name || '<your-plugin-folder-name>') so TempDirectoryManager uses the correct folder for temp directories. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
*/
async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!);
const vaultPath = this.pathUtils.getVaultPath();
const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
// Create controller for this export (allows cancellation)
this.plugin.currentExportController = new AbortController();
try {
// Create temp directory for conversion
const tempManager = new TempDirectoryManager({ vaultPath: vaultPath, configDir: this.plugin.app.vault.configDir });
const tempDir = tempManager.ensureTempDir('pandoc');
const tempManager = new TempDirectoryManager({
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
const content = await this.plugin.app.vault.read(file);
1
@@ -245,8 +254,8 @@ export class ExportOrchestrator {
// Clean up temporary directories
try {
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir);
cleanupManager.cleanupAllTempDirs();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, this.plugin.manifest.id, this.plugin.app);
await cleanupManager.cleanupAllTempDirs();
} catch (cleanupError) {
console.warn('Export: Failed to clean up temporary directories:', cleanupError);
}
+146 -27
View File
@@ -6,7 +6,7 @@
import type { obsidianTypstPDFExport } from '../../main';
import { ExportErrorHandler } from '../core/ExportErrorHandler';
import { FALLBACK_FONTS } from '../core/constants';
import * as path from 'path';
import { PathUtils } from '../core/PathUtils';
export class FontManager {
constructor(private plugin: obsidianTypstPDFExport) {}
@@ -22,12 +22,17 @@ export class FontManager {
// Use spawn instead of exec for security - arguments passed separately
const stdout = await new Promise<string>((resolve, reject) => {
const typstProcess = spawn(typstPath, ['fonts'], {
// Build platform-specific environment with enhanced PATH
const pathValue = this.buildPlatformSpecificPATH();
const enhancedEnv = {
...process.env,
PATH: pathValue,
Path: pathValue
};
const typstProcess = spawn(typstPath, ['fonts'], {
stdio: ['pipe', 'pipe', 'pipe'],
env: {
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
}
env: enhancedEnv
});
let output = '';
1
@@ -64,11 +69,15 @@ export class FontManager {
const cacheData = {
fonts: fonts,
timestamp: Date.now(),
typstPath: typstPath
typstPath: typstPath,
platform: process.platform
};
const fontsCachePath = path.join(this.plugin.manifest.dir!, 'fonts-cache.json');
await this.plugin.app.vault.adapter.write(fontsCachePath,
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,
JSON.stringify(cacheData, null, 2));
} catch (error) {
console.error('Failed to cache fonts from typst:', error);
@@ -78,45 +87,80 @@ export class FontManager {
// Create fallback cache file
const fallbackFonts = FALLBACK_FONTS;
const cacheData = {
fonts: fallbackFonts,
timestamp: Date.now(),
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,
coderabbitai[bot] commented 2025-09-25 13:05:41 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Read cache via vault-relative path too.

-      const pathUtils = new PathUtils(this.plugin.app);
-      const vaultPath = pathUtils.getVaultPath();
-      const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
-      const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
+      const pathUtils = new PathUtils(this.plugin.app);
+      const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
+      const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const pathUtils = new PathUtils(this.plugin.app);
			const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
			const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
			const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);
			const cacheData = JSON.parse(cacheContent);
🤖 Prompt for AI Agents
In src/plugin/FontManager.ts around lines 106 to 111, the code builds an
absolute vaultPath and passes it to app.vault.adapter.read, but adapter.read
expects a vault-relative path; change the read call to use the vault-relative
path (e.g., join pluginDir and 'fonts-cache.json' or use a PathUtils helper that
returns a vault-relative path) instead of including the full vaultPath, and add
a try/catch or existence check before parsing to handle missing or unreadable
cache files.

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Read cache via vault-relative path too.** ```diff - const pathUtils = new PathUtils(this.plugin.app); - const vaultPath = pathUtils.getVaultPath(); - const pluginDir = pathUtils.getPluginDir(this.plugin.manifest); - const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json'); + const pathUtils = new PathUtils(this.plugin.app); + const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest); + const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json'); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const pathUtils = new PathUtils(this.plugin.app); const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest); const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json'); const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath); const cacheData = JSON.parse(cacheContent); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/FontManager.ts around lines 106 to 111, the code builds an absolute vaultPath and passes it to app.vault.adapter.read, but adapter.read expects a vault-relative path; change the read call to use the vault-relative path (e.g., join pluginDir and 'fonts-cache.json' or use a PathUtils helper that returns a vault-relative path) instead of including the full vaultPath, and add a try/catch or existence check before parsing to handle missing or unreadable cache files. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
JSON.stringify(cacheData, null, 2));
}
}
/**
* Get cached fonts list
* Get cached fonts list with improved validation and error recovery
*/
async getCachedFonts(): Promise<string[]> {
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
coderabbitai[bot] commented 2025-09-25 13:05:40 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Use vault-relative paths for vault.adapter I/O (avoid absolute paths).

Passing absolute paths to vault.adapter.write is brittle across adapters/OSes. Use the plugin-dir path relative to the vault instead.

Apply this diff:

-      const pathUtils = new PathUtils(this.plugin.app);
-      const vaultPath = pathUtils.getVaultPath();
-      const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
-      const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
-      await this.plugin.app.vault.adapter.write(fontsCachePath,
+      const pathUtils = new PathUtils(this.plugin.app);
+      const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
+      const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
+      await this.plugin.app.vault.adapter.write(fontsCachePath,
         JSON.stringify(cacheData, null, 2));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      const pathUtils = new PathUtils(this.plugin.app);
      const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
      const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
      await this.plugin.app.vault.adapter.write(fontsCachePath,
        JSON.stringify(cacheData, null, 2));
🤖 Prompt for AI Agents
In src/plugin/FontManager.ts around lines 70 to 75, the code builds an absolute
path using the vault root and passes it to vault.adapter.write, which is
brittle; change it to use a vault-relative path instead by joining the pluginDir
with 'fonts-cache.json' (e.g. use pathUtils.joinPath(pluginDir,
'fonts-cache.json')) and pass that relative path to
this.plugin.app.vault.adapter.write (ensure no leading slash so the adapter
treats it as vault-relative).

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Use vault-relative paths for vault.adapter I/O (avoid absolute paths).** Passing absolute paths to `vault.adapter.write` is brittle across adapters/OSes. Use the plugin-dir path relative to the vault instead. Apply this diff: ```diff - const pathUtils = new PathUtils(this.plugin.app); - const vaultPath = pathUtils.getVaultPath(); - const pluginDir = pathUtils.getPluginDir(this.plugin.manifest); - const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json'); - await this.plugin.app.vault.adapter.write(fontsCachePath, + const pathUtils = new PathUtils(this.plugin.app); + const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest); + const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json'); + await this.plugin.app.vault.adapter.write(fontsCachePath, JSON.stringify(cacheData, null, 2)); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const pathUtils = new PathUtils(this.plugin.app); const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest); const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json'); await this.plugin.app.vault.adapter.write(fontsCachePath, JSON.stringify(cacheData, null, 2)); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/FontManager.ts around lines 70 to 75, the code builds an absolute path using the vault root and passes it to vault.adapter.write, which is brittle; change it to use a vault-relative path instead by joining the pluginDir with 'fonts-cache.json' (e.g. use pathUtils.joinPath(pluginDir, 'fonts-cache.json')) and pass that relative path to this.plugin.app.vault.adapter.write (ensure no leading slash so the adapter treats it as vault-relative). ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
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
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000;
let cacheData;
try {
cacheData = JSON.parse(cacheContent);
} catch (parseError) {
console.error('Corrupted fonts cache file, regenerating:', parseError);
// Remove corrupted cache and regenerate
await this.plugin.app.vault.adapter.remove(fontsCachePath);
await this.cacheAvailableFonts();
return [...FALLBACK_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;
if (isStale || pathChanged) {
const platformChanged = cacheData.platform !== process.platform;
if (isStale || pathChanged || platformChanged) {
// Refresh cache in background
this.cacheAvailableFonts();
this.cacheAvailableFonts().catch(error => {
console.error('Background font cache refresh failed:', error);
});
}
return cacheData.fonts || [];
// 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) {
console.error('Failed to read fonts cache:', error);
// Try to recreate cache
await this.cacheAvailableFonts();
this.cacheAvailableFonts().catch(cacheError => {
console.error('Failed to recreate fonts cache:', cacheError);
});
coderabbitai[bot] commented 2025-09-25 13:05:40 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Same fix in fallback branch: write using vault-relative plugin path.

-      const pathUtils = new PathUtils(this.plugin.app);
-      const vaultPath = pathUtils.getVaultPath();
-      const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
-      const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json');
+      const pathUtils = new PathUtils(this.plugin.app);
+      const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
+      const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
       await this.plugin.app.vault.adapter.write(fontsCachePath,
         JSON.stringify(cacheData, null, 2));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const pathUtils = new PathUtils(this.plugin.app);
			const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest);
			const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json');
			await this.plugin.app.vault.adapter.write(fontsCachePath,
				JSON.stringify(cacheData, null, 2));
🤖 Prompt for AI Agents
In src/plugin/FontManager.ts around lines 92 to 97, the fallback branch
currently writes fonts-cache.json using an incorrect path; update the fallback
write to use the vault-relative plugin path like the primary branch: construct
fontsCachePath with pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json')
and call this.plugin.app.vault.adapter.write(fontsCachePath,
JSON.stringify(cacheData, null, 2)) so both branches write to the same
vault-relative location.

✅ Addressed in commits 24a169d to 2cdc9c3

_⚠️ Potential issue_ | _🟠 Major_ **Same fix in fallback branch: write using vault-relative plugin path.** ```diff - const pathUtils = new PathUtils(this.plugin.app); - const vaultPath = pathUtils.getVaultPath(); - const pluginDir = pathUtils.getPluginDir(this.plugin.manifest); - const fontsCachePath = pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json'); + const pathUtils = new PathUtils(this.plugin.app); + const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest); + const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json'); await this.plugin.app.vault.adapter.write(fontsCachePath, JSON.stringify(cacheData, null, 2)); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const pathUtils = new PathUtils(this.plugin.app); const pluginRelDir = pathUtils.getPluginDir(this.plugin.manifest); const fontsCachePath = pathUtils.joinPath(pluginRelDir, 'fonts-cache.json'); await this.plugin.app.vault.adapter.write(fontsCachePath, JSON.stringify(cacheData, null, 2)); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/FontManager.ts around lines 92 to 97, the fallback branch currently writes fonts-cache.json using an incorrect path; update the fallback write to use the vault-relative plugin path like the primary branch: construct fontsCachePath with pathUtils.joinPath(vaultPath, pluginDir, 'fonts-cache.json') and call this.plugin.app.vault.adapter.write(fontsCachePath, JSON.stringify(cacheData, null, 2)) so both branches write to the same vault-relative location. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 24a169d to 2cdc9c3
// Return fallback fonts
return [...FALLBACK_FONTS];
}
@@ -128,4 +172,79 @@ export class FontManager {
async getAvailableFonts(): Promise<string[]> {
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);
}
}
+17 -31
View File
@@ -6,11 +6,15 @@
import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main';
import { SecurityUtils } from '../core/SecurityUtils';
import { PathUtils } from '../core/PathUtils';
import * as path from 'path';
import * as fs from 'fs';
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
@@ -56,46 +60,28 @@ export class PathResolver {
if (!SecurityUtils.validateOutputPath(outputFolder)) {
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 outputDir = path.join(vaultPath, outputFolder);
const vaultPath = this.pathUtils.getVaultPath();
const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder);
// Create output directory if it doesn't exist
try {
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}`);
}
}
await this.pathUtils.ensureDir(outputDir);
// Preserve folder structure if configured
let relativePath = '';
if (this.plugin.settings.behavior.preserveFolderStructure) {
const folderPath = path.dirname(file.path);
if (folderPath !== '.') {
relativePath = folderPath;
const fullOutputDir = path.join(outputDir, relativePath);
try {
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}`);
}
}
const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath);
await this.pathUtils.ensureDir(fullOutputDir);
}
}
// Generate output filename (just use the note name without timestamp)
const baseName = file.basename;
const outputFileName = `${baseName}.pdf`;
return path.join(outputDir, relativePath, outputFileName);
return this.pathUtils.joinPath(outputDir, relativePath, outputFileName);
}
}
+35 -26
View File
@@ -9,10 +9,14 @@ import { PandocTypstConverter } from '../converters/PandocTypstConverter';
import { TemplateManager } from '../templates/TemplateManager';
import { EmbeddedTemplateManager } from '../templates/embeddedTemplates';
import { TempDirectoryManager } from '../core/TempDirectoryManager';
import * as path from 'path';
import { PathUtils } from '../core/PathUtils';
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
@@ -22,13 +26,13 @@ export class PluginLifecycle {
await this.plugin.loadSettings();
// Initialize embedded template manager
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const pluginDir = path.join(vaultPath, this.plugin.manifest.dir!);
this.plugin.embeddedTemplateManager = new EmbeddedTemplateManager(pluginDir);
const vaultPath = this.pathUtils.getVaultPath();
const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
this.plugin.embeddedTemplateManager = new EmbeddedTemplateManager(pluginDir, this.plugin.app);
// Extract any missing templates from embedded data
try {
const extractionResult = this.plugin.embeddedTemplateManager.extractAllMissingTemplates();
const extractionResult = await this.plugin.embeddedTemplateManager.extractAllMissingTemplates();
if (extractionResult.failed.length > 0) {
console.warn(`Failed to extract ${extractionResult.failed.length} templates:`, extractionResult.failed);
ExportErrorHandler.showTemplateError(`Failed to extract some templates. Plugin may not work correctly.`);
@@ -64,31 +68,36 @@ export class PluginLifecycle {
this.plugin.currentExportController.abort();
}
// Clean up temp directories on plugin unload
try {
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir);
cleanupManager.cleanupAllTempDirs();
} catch (error) {
console.warn('Export: Failed to clean up temp directories during unload:', error);
}
// Clean up temp directories on plugin unload (fire-and-forget async)
(async () => {
try {
const vaultPath = this.pathUtils.getVaultPath();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
await cleanupManager.cleanupAllTempDirs();
} catch (error) {
console.warn('Export: Failed to clean up temp directories during unload:', error);
}
})();
}
/**
* Clean up leftover temp directories from previous sessions
*/
private cleanupStartupTempDirectories(): void {
try {
const vaultPath = (this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath;
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir);
const _result = cleanupManager.cleanupAllTempDirs();
if (this.plugin.settings.behavior.debugMode) {
// Debug logging was here but empty in original
// Clean up temp directories (fire-and-forget async)
(async () => {
try {
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) {
// 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
}
})();
}
}
+31 -20
View File
@@ -4,19 +4,21 @@
*/
import { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils';
import * as path from 'path';
import * as fs from 'fs';
export class TemplateManager {
private plugin: obsidianTypstPDFExport;
private templatesPath: string;
private pathUtils: PathUtils;
constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin;
this.pathUtils = new PathUtils(plugin.app);
// Templates are stored in the plugin directory
this.templatesPath = path.join(
(this.plugin.app.vault.adapter as unknown as { basePath: string }).basePath,
this.plugin.manifest.dir!,
this.templatesPath = this.pathUtils.joinPath(
this.pathUtils.getVaultPath(),
this.pathUtils.getPluginDir(this.plugin.manifest),
'templates'
);
}
@@ -27,24 +29,36 @@ export class TemplateManager {
async getAvailableTemplates(): Promise<string[]> {
coderabbitai[bot] commented 2025-09-25 13:05:41 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

List templates using a vault-relative path (adapter.list).

adapter.list works most reliably with vault-relative paths.

-      const list = await this.plugin.app.vault.adapter.list(this.templatesPath);
+      const templatesRelDir = this.pathUtils.joinPath(
+        this.pathUtils.getPluginDir(this.plugin.manifest),
+        'templates'
+      );
+      const list = await this.plugin.app.vault.adapter.list(templatesRelDir);
       const files = list.files.map(filePath => path.basename(filePath));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			const templatesRelDir = this.pathUtils.joinPath(
				this.pathUtils.getPluginDir(this.plugin.manifest),
				'templates'
			);
			const list = await this.plugin.app.vault.adapter.list(templatesRelDir);
			const files = list.files.map(filePath => path.basename(filePath));
🤖 Prompt for AI Agents
In src/templates/TemplateManager.ts around lines 39-41, adapter.list is being
called with this.templatesPath which may not be vault-relative; change the call
to pass a vault-relative path (e.g. compute const vaultPath =
this.plugin.app.vault.getRelativePath?.(this.templatesPath) ??
this.templatesPath.replace(/^\/+/, '') or otherwise strip any
absolute/vault-root prefix) and then call await
this.plugin.app.vault.adapter.list(vaultPath); ensure you use the vault-relative
path variable in the subsequent map call.

✅ Addressed in commits a129380 to 731a76e

_⚠️ Potential issue_ | _🟠 Major_ **List templates using a vault-relative path (adapter.list).** `adapter.list` works most reliably with vault-relative paths. ```diff - const list = await this.plugin.app.vault.adapter.list(this.templatesPath); + const templatesRelDir = this.pathUtils.joinPath( + this.pathUtils.getPluginDir(this.plugin.manifest), + 'templates' + ); + const list = await this.plugin.app.vault.adapter.list(templatesRelDir); const files = list.files.map(filePath => path.basename(filePath)); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const templatesRelDir = this.pathUtils.joinPath( this.pathUtils.getPluginDir(this.plugin.manifest), 'templates' ); const list = await this.plugin.app.vault.adapter.list(templatesRelDir); const files = list.files.map(filePath => path.basename(filePath)); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/templates/TemplateManager.ts around lines 39-41, adapter.list is being called with this.templatesPath which may not be vault-relative; change the call to pass a vault-relative path (e.g. compute const vaultPath = this.plugin.app.vault.getRelativePath?.(this.templatesPath) ?? this.templatesPath.replace(/^\/+/, '') or otherwise strip any absolute/vault-root prefix) and then call await this.plugin.app.vault.adapter.list(vaultPath); ensure you use the vault-relative path variable in the subsequent map call. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 731a76e
try {
// 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);
return ['default.typ'];
}
// Read directory contents
const files = fs.readdirSync(this.templatesPath);
// Read directory contents - convert absolute path to vault-relative
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
const templates = files.filter(file => {
return file.endsWith('.typ') || file.endsWith('.pandoc.typ');
});
// Always include default if not present
if (!templates.includes('default.typ')) {
templates.unshift('default.typ');
}
return templates;
} catch (error) {
console.error('Error loading templates:', error);
@@ -56,7 +70,7 @@ export class TemplateManager {
* Get the full path to a template file
*/
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> {
const templatePath = this.getTemplatePath(templateName);
try {
return fs.existsSync(templatePath);
} catch {
return false;
}
return await this.pathUtils.fileExists(templatePath);
}
/**
@@ -77,8 +87,9 @@ export class TemplateManager {
async loadTemplate(templateName: string): Promise<string | null> {
const templatePath = this.getTemplatePath(templateName);
try {
if (fs.existsSync(templatePath)) {
return fs.readFileSync(templatePath, 'utf-8');
const exists = await this.pathUtils.fileExists(templatePath);
if (exists) {
return await this.plugin.app.vault.adapter.read(templatePath);
}
} catch (error) {
console.error('Error loading template:', error);
+33 -33
View File
@@ -1,6 +1,6 @@
import { extractTemplate, getAllTemplateNames } from 'template-embed:templates';
import * as fs from 'fs';
import * as path from 'path';
import { PathUtils } from '../core/PathUtils';
import type { App } from 'obsidian';
export interface TemplateInfo {
name: string;
@@ -14,23 +14,27 @@ export interface TemplateInfo {
export class EmbeddedTemplateManager {
private pluginDir: string;
private templatesDir: string;
private pathUtils: PathUtils;
private app: App;
constructor(pluginDir: string) {
constructor(pluginDir: string, app: App) {
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
*/
getTemplateInfo(): TemplateInfo[] {
async getTemplateInfo(): Promise<TemplateInfo[]> {
const embeddedNames = getAllTemplateNames();
const templateInfo: TemplateInfo[] = [];
for (const name of embeddedNames) {
const filePath = path.join(this.templatesDir, name);
const exists = fs.existsSync(filePath);
const filePath = this.pathUtils.joinPath(this.templatesDir, name);
const exists = await this.pathUtils.fileExists(filePath);
templateInfo.push({
name,
exists,
@@ -44,26 +48,24 @@ export class EmbeddedTemplateManager {
/**
* Extract a single template if it doesn't exist
*/
extractTemplateIfNeeded(templateName: string): boolean {
const filePath = path.join(this.templatesDir, templateName);
async extractTemplateIfNeeded(templateName: string): Promise<boolean> {
const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
// Check if template already exists
if (fs.existsSync(filePath)) {
if (await this.pathUtils.fileExists(filePath)) {
return false; // No extraction needed
}
try {
// Ensure templates directory exists
if (!fs.existsSync(this.templatesDir)) {
fs.mkdirSync(this.templatesDir, { recursive: true });
}
await this.pathUtils.ensureDir(this.templatesDir);
// Extract template content
const content = extractTemplate(templateName, filePath);
// Write template to disk
fs.writeFileSync(filePath, content, 'utf8');
// Write template to disk using vault.adapter
await this.app.vault.adapter.write(filePath, content);
return true; // Extraction successful
} catch (error) {
console.error(`Failed to extract template ${templateName}:`, error);
@@ -74,15 +76,15 @@ export class EmbeddedTemplateManager {
/**
* Extract all missing templates
*/
extractAllMissingTemplates(): { extracted: string[], failed: string[] } {
async extractAllMissingTemplates(): Promise<{ extracted: string[], failed: string[] }> {
const extracted: string[] = [];
const failed: string[] = [];
const templateInfo = this.getTemplateInfo();
const templateInfo = await this.getTemplateInfo();
for (const info of templateInfo) {
if (info.needsExtraction) {
const success = this.extractTemplateIfNeeded(info.name);
const success = await this.extractTemplateIfNeeded(info.name);
if (success) {
extracted.push(info.name);
} else {
@@ -97,23 +99,21 @@ export class EmbeddedTemplateManager {
/**
* Force extract all templates (overwrites existing ones)
*/
forceExtractAllTemplates(): { extracted: string[], failed: string[] } {
async forceExtractAllTemplates(): Promise<{ extracted: string[], failed: string[] }> {
const extracted: string[] = [];
const failed: string[] = [];
const embeddedNames = getAllTemplateNames();
// Ensure templates directory exists
if (!fs.existsSync(this.templatesDir)) {
fs.mkdirSync(this.templatesDir, { recursive: true });
}
await this.pathUtils.ensureDir(this.templatesDir);
for (const templateName of embeddedNames) {
try {
const filePath = path.join(this.templatesDir, templateName);
const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
const content = extractTemplate(templateName, filePath);
fs.writeFileSync(filePath, content, 'utf8');
await this.app.vault.adapter.write(filePath, content);
extracted.push(templateName);
} catch (error) {
console.error(`Failed to force extract template ${templateName}:`, error);