Fixes path handling and adds remote image support
Addresses issues with path construction on Windows by using `path.isAbsolute()` to correctly handle absolute paths. Improves cross-platform compatibility in temp directory management and binary location. Adds support for downloading and embedding remote images (http/https URLs) in markdown, enhancing content integration. Provides fallback mechanism with placeholder text upon download failure.
This commit is contained in:
6 files changed
+263
-37
No files matched your search
+7
-4
@@ -5,9 +5,10 @@ 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
|
||||
## [Unreleased] - 2025-09-25
|
||||
|
||||
### Added
|
||||
- **Remote Image Download**: Automatic download and embedding of remote images (http:// and https:// URLs) during export. Works with both wikilink-style embeds `![[https://...]]` and standard markdown images ``. Falls back to placeholder text if download fails (10-second timeout). Images are downloaded to temp directory and cleaned up after export
|
||||
- **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
|
||||
@@ -15,6 +16,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- **Improved Plugin Isolation**: TempDirectoryManager now uses proper plugin namespacing to prevent conflicts
|
||||
|
||||
### Fixed
|
||||
- **Windows Absolute Path Handling**: Fixed ENOENT errors on Windows caused by improper path joining when combining vault paths with plugin directories. PathUtils.joinPath() now properly detects and handles absolute paths using path.isAbsolute() to prevent invalid path construction like `C:\MyVault\C:\MyVault\...`
|
||||
- **Remote URL Image Handling**: Fixed ENOENT errors when markdown contains remote image URLs. Remote images are now automatically downloaded and embedded, with graceful fallback to placeholder text if download fails
|
||||
- **Cross-Platform Binary Discovery**: BinaryLocator now includes comprehensive fallback paths for different installation methods
|
||||
- **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
|
||||
@@ -31,7 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- **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
|
||||
## [1.3.0] - 2025-09-25
|
||||
|
||||
### Added
|
||||
- PathUtils helper class for centralized path operations and safe Obsidian API usage
|
||||
@@ -52,7 +55,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Enhanced error handling and path validation across all modules
|
||||
- Updated all 16 core files with consistent, safe path handling practices
|
||||
|
||||
## [1.2.1] - 2025-01-10
|
||||
## [1.2.1] - 2025-09-10
|
||||
|
||||
### Fixed
|
||||
- **Horizontal Rule Processing**: Resolved YAML parsing conflicts when documents contain horizontal rules (`---`)
|
||||
@@ -69,7 +72,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Improved type safety throughout the codebase
|
||||
- Enhanced code maintainability with proper type assertions
|
||||
|
||||
## [1.2.0] - 2025-01-10
|
||||
## [1.2.0] - 2025-09-10
|
||||
|
||||
### Changed
|
||||
- **Major Refactoring**: Complete modularization of codebase for improved maintainability
|
||||
|
||||
@@ -9,6 +9,7 @@ import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProce
|
||||
import { CalloutProcessor } from './preprocessors/CalloutProcessor';
|
||||
import { MetadataExtractor } from './preprocessors/MetadataExtractor';
|
||||
import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor';
|
||||
import * as path from 'path';
|
||||
|
||||
export interface PreprocessorOptions {
|
||||
/** Preserve existing frontmatter */
|
||||
@@ -141,7 +142,10 @@ export class MarkdownPreprocessor {
|
||||
|
||||
// Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
|
||||
result.content = this.embedProcessor.processEmbeds(result.content, result);
|
||||
|
||||
|
||||
// Step 5.5: Handle standard markdown images with remote URLs
|
||||
result.content = this.processStandardMarkdownImages(result.content, result);
|
||||
|
||||
// Step 6: Convert wikilinks (after embeds are processed)
|
||||
result.content = this.wikilinkProcessor.processWikilinks(result.content, result);
|
||||
|
||||
@@ -159,7 +163,59 @@ export class MarkdownPreprocessor {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Process standard markdown images and track remote URLs for download
|
||||
* Remote images are marked for later download and embedding
|
||||
*/
|
||||
private processStandardMarkdownImages(content: string, result: PreprocessingResult): string {
|
||||
// Pattern to match standard markdown images: 
|
||||
const markdownImagePattern = /!\[([^\]]*)\]\(([^)]+)\)/g;
|
||||
|
||||
return content.replace(markdownImagePattern, (match, alt, url) => {
|
||||
// Check if this is a remote URL (http:// or https://)
|
||||
const isRemoteUrl = /^https?:\/\//i.test(url.trim());
|
||||
|
||||
if (isRemoteUrl) {
|
||||
const cleanUrl = url.trim();
|
||||
|
||||
// Extract filename from URL for tracking
|
||||
let fileName = 'remote-image.png';
|
||||
try {
|
||||
const urlObj = new URL(cleanUrl);
|
||||
fileName = path.basename(urlObj.pathname) || fileName;
|
||||
} catch {
|
||||
// Use default if URL parsing fails
|
||||
}
|
||||
|
||||
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||
|
||||
// Create a marker that the export process can detect and replace
|
||||
const marker = `IMAGE_EMBED_MARKER:${cleanUrl}:${baseName}:${alt || ''}`;
|
||||
|
||||
// Add to processing queue for later download and embedding
|
||||
if (!result.metadata.imageEmbeds) {
|
||||
result.metadata.imageEmbeds = [];
|
||||
}
|
||||
result.metadata.imageEmbeds.push({
|
||||
originalPath: cleanUrl,
|
||||
sanitizedPath: cleanUrl, // For remote URLs, sanitized = original
|
||||
fileName: fileName,
|
||||
baseName: baseName,
|
||||
sizeOrAlt: alt,
|
||||
marker: marker
|
||||
});
|
||||
|
||||
result.warnings.push(`Remote URL image queued for download: ${cleanUrl}`);
|
||||
|
||||
return marker;
|
||||
}
|
||||
|
||||
// Keep local images as-is for normal processing
|
||||
return match;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update configuration
|
||||
*/
|
||||
|
||||
@@ -131,13 +131,16 @@ export class BinaryLocator {
|
||||
* @returns Array of possible plugin directory paths
|
||||
*/
|
||||
private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] {
|
||||
const pathUtils = plugin ? new PathUtils(plugin.app) : null;
|
||||
|
||||
return [
|
||||
// Strategy 1: From process.cwd() if it's in the vault
|
||||
path.join(process.cwd(), configDir, 'plugins', pluginDirName),
|
||||
// Strategy 2: Assuming we're running from vault root
|
||||
path.join(configDir, 'plugins', pluginDirName),
|
||||
// Strategy 3: From vault base path if plugin is available
|
||||
...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : [])
|
||||
// Use PathUtils.joinPath to handle absolute paths correctly on Windows
|
||||
...(pathUtils ? [pathUtils.joinPath(pathUtils.getVaultPath(), plugin!.manifest.dir!)] : [])
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+27
-2
@@ -3,6 +3,7 @@
|
||||
|
||||
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
|
||||
import type { App, PluginManifest } from 'obsidian';
|
||||
import * as path from 'path';
|
||||
|
||||
export class PathUtils {
|
||||
constructor(private app: App) {}
|
||||
@@ -28,12 +29,36 @@ export class PathUtils {
|
||||
|
||||
/**
|
||||
* Join path segments with normalizePath
|
||||
* Handles absolute paths correctly by using the last absolute path found
|
||||
*/
|
||||
joinPath(...segments: string[]): string {
|
||||
// Filter out empty segments
|
||||
const filtered = segments.filter(s => s);
|
||||
const joined = filtered.join('/');
|
||||
return normalizePath(joined);
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Find the last absolute path in the segments
|
||||
// If a segment is absolute, it becomes the new base and we ignore previous segments
|
||||
let result = '';
|
||||
for (const segment of filtered) {
|
||||
if (path.isAbsolute(segment)) {
|
||||
// This segment is absolute, use it as the new base
|
||||
result = segment;
|
||||
} else if (result) {
|
||||
// Join with the current result
|
||||
result = path.join(result, segment);
|
||||
} else {
|
||||
// First relative segment
|
||||
result = segment;
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize the final path using path.normalize for cross-platform compatibility
|
||||
// then use Obsidian's normalizePath for vault-relative paths
|
||||
const normalized = path.normalize(result);
|
||||
return normalizePath(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import { PLUGIN_DIRS } from './constants';
|
||||
import { normalizePath } from 'obsidian';
|
||||
import type { App } from 'obsidian';
|
||||
import * as path from 'path';
|
||||
|
||||
export interface TempDirectoryOptions {
|
||||
/** Base path for the vault */
|
||||
@@ -31,17 +32,45 @@ export class TempDirectoryManager {
|
||||
|
||||
/**
|
||||
* Get the plugin directory path
|
||||
* Handles absolute paths correctly on Windows
|
||||
*/
|
||||
private getPluginDir(): string {
|
||||
return normalizePath([this.vaultPath, this.configDir, 'plugins', this.pluginName].join('/'));
|
||||
// Use path.join to properly handle absolute paths
|
||||
const segments = [this.vaultPath, this.configDir, 'plugins', this.pluginName];
|
||||
let result = '';
|
||||
|
||||
for (const segment of segments) {
|
||||
if (!segment) continue;
|
||||
|
||||
if (path.isAbsolute(segment)) {
|
||||
// This segment is absolute, use it as the new base
|
||||
result = segment;
|
||||
} else if (result) {
|
||||
// Join with the current result
|
||||
result = path.join(result, segment);
|
||||
} else {
|
||||
// First relative segment
|
||||
result = segment;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizePath(path.normalize(result));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path for a specific temp directory
|
||||
* Handles absolute paths correctly on Windows
|
||||
*/
|
||||
public getTempDir(type: 'images' | 'pandoc'): string {
|
||||
const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC;
|
||||
return normalizePath([this.getPluginDir(), dirName].join('/'));
|
||||
const pluginDir = this.getPluginDir();
|
||||
|
||||
// Use path.join to properly handle absolute paths
|
||||
const result = path.isAbsolute(pluginDir)
|
||||
? path.join(pluginDir, dirName)
|
||||
: path.join(pluginDir, dirName);
|
||||
|
||||
return normalizePath(path.normalize(result));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -99,13 +128,16 @@ export class TempDirectoryManager {
|
||||
|
||||
/**
|
||||
* Check if a path is within the plugin's temp directories
|
||||
* Handles absolute paths correctly on Windows
|
||||
*/
|
||||
public isPluginTempDir(dirPath: string): boolean {
|
||||
const pluginDir = this.getPluginDir();
|
||||
const normalizedDirPath = normalizePath(dirPath);
|
||||
const normalizedPluginDir = normalizePath(pluginDir);
|
||||
const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/'));
|
||||
const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/'));
|
||||
|
||||
// Use path.join to properly handle absolute paths
|
||||
const tempImagesDir = normalizePath(path.normalize(path.join(normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES)));
|
||||
const tempPandocDir = normalizePath(path.normalize(path.join(normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC)));
|
||||
|
||||
return normalizedDirPath.startsWith(tempImagesDir) ||
|
||||
normalizedDirPath.startsWith(tempPandocDir);
|
||||
|
||||
+131
-24
@@ -9,6 +9,9 @@ import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
|
||||
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||
import { PathUtils } from '../core/PathUtils';
|
||||
import * as path from 'path';
|
||||
import * as https from 'https';
|
||||
import * as http from 'http';
|
||||
import * as fs from 'fs';
|
||||
|
||||
export class EmbedProcessor {
|
||||
private readonly pathUtils: PathUtils;
|
||||
@@ -16,6 +19,89 @@ export class EmbedProcessor {
|
||||
constructor(private plugin: obsidianTypstPDFExport) {
|
||||
this.pathUtils = new PathUtils(plugin.app);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a remote image to the temp directory
|
||||
* Returns the local path if successful, null if failed
|
||||
*/
|
||||
private async downloadRemoteImage(imageUrl: string, tempDir: string): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
// Parse URL to get filename
|
||||
const urlObj = new URL(imageUrl);
|
||||
const urlPath = urlObj.pathname;
|
||||
const fileName = path.basename(urlPath) || `remote-image-${Date.now()}.png`;
|
||||
|
||||
// Ensure we have a valid file extension
|
||||
const ext = path.extname(fileName).toLowerCase();
|
||||
const validExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.tiff'];
|
||||
const finalFileName = validExtensions.includes(ext)
|
||||
? fileName
|
||||
: `${fileName}.png`;
|
||||
|
||||
const outputPath = path.join(tempDir, finalFileName);
|
||||
|
||||
// Select appropriate protocol
|
||||
const protocol = imageUrl.startsWith('https') ? https : http;
|
||||
|
||||
console.log(`Export: Downloading remote image: ${imageUrl}`);
|
||||
|
||||
const request = protocol.get(imageUrl, (response) => {
|
||||
// Handle redirects
|
||||
if (response.statusCode === 301 || response.statusCode === 302) {
|
||||
const redirectUrl = response.headers.location;
|
||||
if (redirectUrl) {
|
||||
console.log(`Export: Following redirect to: ${redirectUrl}`);
|
||||
// Recursively follow redirect
|
||||
this.downloadRemoteImage(redirectUrl, tempDir).then(resolve);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for successful response
|
||||
if (response.statusCode !== 200) {
|
||||
console.warn(`Export: Failed to download image, status code: ${response.statusCode}`);
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create write stream
|
||||
const fileStream = fs.createWriteStream(outputPath);
|
||||
|
||||
// Pipe response to file
|
||||
response.pipe(fileStream);
|
||||
|
||||
fileStream.on('finish', () => {
|
||||
fileStream.close();
|
||||
console.log(`Export: Successfully downloaded image to: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
});
|
||||
|
||||
fileStream.on('error', (err) => {
|
||||
console.error(`Export: Error writing image file: ${err.message}`);
|
||||
fs.unlink(outputPath, () => {}); // Clean up partial file
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
request.on('error', (err) => {
|
||||
console.error(`Export: Error downloading image: ${err.message}`);
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
// Set timeout
|
||||
request.setTimeout(10000, () => {
|
||||
request.destroy();
|
||||
console.warn(`Export: Image download timeout: ${imageUrl}`);
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error(`Export: Error in downloadRemoteImage: ${error.message}`);
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Process PDF embeds - convert PDF pages to images for inclusion
|
||||
@@ -109,37 +195,58 @@ export class EmbedProcessor {
|
||||
*/
|
||||
async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise<void> {
|
||||
let updatedContent = processedResult.content;
|
||||
|
||||
|
||||
for (const imageEmbed of processedResult.metadata?.imageEmbeds || []) {
|
||||
try {
|
||||
// Decode the URL-encoded sanitized path back to normal characters
|
||||
const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath);
|
||||
|
||||
// Try multiple path resolution strategies
|
||||
const possiblePaths = [
|
||||
// Strategy 1: Relative to vault root (standard Obsidian behavior)
|
||||
path.resolve(vaultBasePath, decodedPath),
|
||||
// Strategy 2: Relative to current file's directory (for local attachments)
|
||||
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
|
||||
// Strategy 3: Check in attachments folder (common pattern)
|
||||
path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath))
|
||||
].filter((p): p is string => p !== null);
|
||||
|
||||
let fullImagePath = null;
|
||||
|
||||
// Try each possible path until we find one that exists
|
||||
for (const possiblePath of possiblePaths) {
|
||||
try {
|
||||
const exists = await this.pathUtils.fileExists(possiblePath);
|
||||
if (exists) {
|
||||
fullImagePath = possiblePath;
|
||||
break;
|
||||
|
||||
let fullImagePath: string | null = null;
|
||||
|
||||
// Check if this is a remote URL (http:// or https://)
|
||||
const isRemoteUrl = /^https?:\/\//i.test(decodedPath);
|
||||
|
||||
if (isRemoteUrl) {
|
||||
// Try to download the remote image
|
||||
console.log(`Export: Attempting to download remote image: ${decodedPath}`);
|
||||
const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir);
|
||||
|
||||
if (downloadedPath) {
|
||||
// Successfully downloaded, use it as a local image
|
||||
fullImagePath = downloadedPath;
|
||||
console.log(`Export: Successfully downloaded and will embed remote image`);
|
||||
} else {
|
||||
// Download failed, use placeholder
|
||||
console.warn(`Export: Failed to download remote image: ${decodedPath}`);
|
||||
const fallbackOutput = `[🌐 **Remote image download failed:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`;
|
||||
updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// Try multiple path resolution strategies for local files
|
||||
const possiblePaths = [
|
||||
// Strategy 1: Relative to vault root (standard Obsidian behavior)
|
||||
path.resolve(vaultBasePath, decodedPath),
|
||||
// Strategy 2: Relative to current file's directory (for local attachments)
|
||||
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
|
||||
// Strategy 3: Check in attachments folder (common pattern)
|
||||
path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath))
|
||||
].filter((p): p is string => p !== null);
|
||||
|
||||
// Try each possible path until we find one that exists
|
||||
for (const possiblePath of possiblePaths) {
|
||||
try {
|
||||
const exists = await this.pathUtils.fileExists(possiblePath);
|
||||
if (exists) {
|
||||
fullImagePath = possiblePath;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist, continue to next path
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist, continue to next path
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!fullImagePath) {
|
||||
console.warn(`Export: Image file not found: ${decodedPath}`);
|
||||
// Keep the original marker or replace with placeholder
|
||||
|
||||
Reference in new issue
Block a user