Update ESLint rules and resolve bot review feedback #8

Merged
AlexKucera merged 24 commits from obsidian-bot-review into master 2025-11-09 12:06:31 +01:00
15 changed files with 202 additions and 52 deletions
Showing only changes of commit 87f3894bf1 - Show all commits

No files matched your search

+1 -1
View File
1
@@ -63,7 +63,7 @@ export default tseslint.config(
'obsidianmd/sample-names': 'error',
'obsidianmd/validate-manifest': 'error',
'obsidianmd/validate-license': 'error',
'obsidianmd/ui/sentence-case': ['error', { enforceCamelCaseLower: true }],
'obsidianmd/ui/sentence-case': ['warn', { enforceCamelCaseLower: true }],
// General ESLint rules from Obsidian recommended
'no-unused-vars': 'off',
+5 -2
View File
@@ -18,6 +18,7 @@ import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from
import type { obsidianTypstPDFExport } from '../../main';
import { TempDirectoryManager } from '../core/TempDirectoryManager';
import { PathUtils } from '../core/PathUtils';
import { promises as fs } from 'fs';
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor';
@@ -254,7 +255,8 @@ export class PandocTypstConverter {
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);
// Use fs.writeFile for temp files since external tools (Pandoc) need absolute paths
await fs.writeFile(tempInputPath, content, 'utf-8');
// Merge options
this.pandocOptions = { ...this.pandocOptions, ...options };
@@ -264,7 +266,8 @@ export class PandocTypstConverter {
// Cleanup temp file
try {
await this.plugin.app.vault.adapter.remove(tempInputPath);
// Use fs.unlink for temp files since they're in external temp directories
await fs.unlink(tempInputPath);
} catch (error) {
console.warn('Failed to cleanup temp file:', error);
}
1
+11 -2
View File
@@ -413,10 +413,19 @@ export class PdfToImageConverter {
};
coderabbitai[bot] commented 2025-11-05 19:26:58 +01:00 (Migrated from github.com)
Review

🛠️ Refactor suggestion | 🟠 Major

Extract duplicated path conversion logic to PathUtils helper.

This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability.

See the detailed suggestion in the review comment for src/converters/pdf/ImageOptimizer.ts lines 247-304. The same pathUtils.toVaultRelative() helper would simplify this code:

 if (this.plugin?.app) {
   const pathUtils = new PathUtils(this.plugin.app);
-  const vaultPath = pathUtils.getVaultPath();
-  // Convert absolute path to vault-relative
-  let relativeOutputDir = outputDir;
-  if (outputDir.startsWith(vaultPath)) {
-    relativeOutputDir = outputDir.substring(vaultPath.length);
-    if (relativeOutputDir.startsWith('/') || relativeOutputDir.startsWith('\\')) {
-      relativeOutputDir = relativeOutputDir.substring(1);
-    }
-  }
+  const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
   await pathUtils.ensureDir(relativeOutputDir);
 }

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

🤖 Prompt for AI Agents
In src/converters/PdfToImageConverter.ts around lines 416 to 428, the
vault-relative path conversion logic is duplicated and should be moved into
PathUtils; add a PathUtils.toVaultRelative(outputDir) (or similar) method that
returns the vault-relative path (trimming leading separators when needed) and
replace the inline conversion here with: const relativeOutputDir =
pathUtils.toVaultRelative(outputDir); then call await
pathUtils.ensureDir(relativeOutputDir); ensuring behavior matches existing
trimming and only converts when outputDir starts with the vault path.

✅ Addressed in commits f0daebc to c1c02ee

_🛠️ Refactor suggestion_ | _🟠 Major_ **Extract duplicated path conversion logic to PathUtils helper.** This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability. See the detailed suggestion in the review comment for `src/converters/pdf/ImageOptimizer.ts` lines 247-304. The same `pathUtils.toVaultRelative()` helper would simplify this code: ```diff if (this.plugin?.app) { const pathUtils = new PathUtils(this.plugin.app); - const vaultPath = pathUtils.getVaultPath(); - // Convert absolute path to vault-relative - let relativeOutputDir = outputDir; - if (outputDir.startsWith(vaultPath)) { - relativeOutputDir = outputDir.substring(vaultPath.length); - if (relativeOutputDir.startsWith('/') || relativeOutputDir.startsWith('\\')) { - relativeOutputDir = relativeOutputDir.substring(1); - } - } + const relativeOutputDir = pathUtils.toVaultRelative(outputDir); await pathUtils.ensureDir(relativeOutputDir); } ``` > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/PdfToImageConverter.ts around lines 416 to 428, the vault-relative path conversion logic is duplicated and should be moved into PathUtils; add a PathUtils.toVaultRelative(outputDir) (or similar) method that returns the vault-relative path (trimming leading separators when needed) and replace the inline conversion here with: const relativeOutputDir = pathUtils.toVaultRelative(outputDir); then call await pathUtils.ensureDir(relativeOutputDir); ensuring behavior matches existing trimming and only converts when outputDir starts with the vault path. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee
}
// Ensure output directory exists
// Ensure output directory exists (convert absolute path to vault-relative for vault.adapter)
if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app);
await pathUtils.ensureDir(outputDir);
const vaultPath = pathUtils.getVaultPath();
// Convert absolute path to vault-relative
let relativeOutputDir = outputDir;
if (outputDir.startsWith(vaultPath)) {
relativeOutputDir = outputDir.substring(vaultPath.length);
if (relativeOutputDir.startsWith('/') || relativeOutputDir.startsWith('\\')) {
relativeOutputDir = relativeOutputDir.substring(1);
}
}
await pathUtils.ensureDir(relativeOutputDir);
}
// Generate expected output file name for the first page
@@ -201,10 +201,6 @@ export class PandocCommandBuilder {
// Enable standalone mode (required for PDF output)
args.push('--standalone');
// Disable citeproc to prevent automatic bibliography processing
// This prevents "document does not contain a bibliography" errors when
// Pandoc detects citation-like patterns but no bibliography file is provided
args.push('--no-citeproc');
// Embed resources (images, etc.) directly into the output
args.push('--embed-resources');
+3 -1
View File
@@ -30,7 +30,9 @@ export class BinaryLocator {
// Get the plugin directory - need to handle Obsidian's environment
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
// Try multiple strategies to find the plugin directory
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
// Extract just the plugin folder name from manifest.dir (e.g., "typst-pdf-export" from ".obsidian/plugins/typst-pdf-export")
const fullManifestDir = plugin?.manifest?.dir || 'typst-pdf-export';
const pluginDirName = path.basename(fullManifestDir);
const configDir = plugin?.app.vault.configDir;
if (!configDir) {
throw new Error('Unable to determine Obsidian configuration directory');
+50 -6
View File
@@ -244,9 +244,31 @@ export class ImageOptimizer {
// Just rename the file to PNG format
coderabbitai[bot] commented 2025-11-05 19:26:58 +01:00 (Migrated from github.com)
Review

🛠️ Refactor suggestion | 🟠 Major

Extract duplicated path conversion logic to PathUtils helper.

The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies.

Consider adding a helper method to PathUtils:

// In PathUtils.ts
public toVaultRelative(absolutePath: string): string {
  const vaultBasePath = this.getVaultPath();
  if (!absolutePath.startsWith(vaultBasePath)) {
    return absolutePath;
  }
  let relativePath = absolutePath.substring(vaultBasePath.length);
  if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
    relativePath = relativePath.substring(1);
  }
  return relativePath;
}

Then replace the duplicated blocks:

 if (plugin?.app) {
-  // Convert absolute paths to vault-relative paths for adapter operations
   const pathUtils = new PathUtils(plugin.app);
-  const vaultBasePath = pathUtils.getVaultPath();
-
-  let relativeInputPath = inputImagePath;
-  if (inputImagePath.startsWith(vaultBasePath)) {
-    // Remove vault base path and leading separator
-    relativeInputPath = inputImagePath.substring(vaultBasePath.length);
-    if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) {
-      relativeInputPath = relativeInputPath.substring(1);
-    }
-  }
-
-  let relativePngPath = pngFinalPath;
-  if (pngFinalPath.startsWith(vaultBasePath)) {
-    // Remove vault base path and leading separator
-    relativePngPath = pngFinalPath.substring(vaultBasePath.length);
-    if (relativePngPath.startsWith('/') || relativePngPath.startsWith('\\')) {
-      relativePngPath = relativePngPath.substring(1);
-    }
-  }
+  const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
+  const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);

   const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
🤖 Prompt for AI Agents
In src/converters/pdf/ImageOptimizer.ts around lines 247-304 (and also the
similar occurrences at ~220-234 and ~280-304), duplicate logic strips the vault
base path and leading separators; extract this into PathUtils.toVaultRelative
and replace the three duplicated blocks with calls to that helper. Add a public
toVaultRelative(absolutePath: string) method on PathUtils that returns the
original path if it does not start with getVaultPath(), otherwise removes the
vault base prefix and any leading '/' or '\' and returns the result; then in
ImageOptimizer create a PathUtils(plugin.app) instance and call toVaultRelative
for inputImagePath, pngFinalPath and finalOutputPath before passing them to
plugin.app.vault.adapter.readBinary/writeBinary/remove, removing the inline
substring/startsWith logic so behavior remains identical.

✅ Addressed in commits f0daebc to c1c02ee

_🛠️ Refactor suggestion_ | _🟠 Major_ **Extract duplicated path conversion logic to PathUtils helper.** The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies. Consider adding a helper method to PathUtils: ```typescript // In PathUtils.ts public toVaultRelative(absolutePath: string): string { const vaultBasePath = this.getVaultPath(); if (!absolutePath.startsWith(vaultBasePath)) { return absolutePath; } let relativePath = absolutePath.substring(vaultBasePath.length); if (relativePath.startsWith('/') || relativePath.startsWith('\\')) { relativePath = relativePath.substring(1); } return relativePath; } ``` Then replace the duplicated blocks: ```diff if (plugin?.app) { - // Convert absolute paths to vault-relative paths for adapter operations const pathUtils = new PathUtils(plugin.app); - const vaultBasePath = pathUtils.getVaultPath(); - - let relativeInputPath = inputImagePath; - if (inputImagePath.startsWith(vaultBasePath)) { - // Remove vault base path and leading separator - relativeInputPath = inputImagePath.substring(vaultBasePath.length); - if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) { - relativeInputPath = relativeInputPath.substring(1); - } - } - - let relativePngPath = pngFinalPath; - if (pngFinalPath.startsWith(vaultBasePath)) { - // Remove vault base path and leading separator - relativePngPath = pngFinalPath.substring(vaultBasePath.length); - if (relativePngPath.startsWith('/') || relativePngPath.startsWith('\\')) { - relativePngPath = relativePngPath.substring(1); - } - } + const relativeInputPath = pathUtils.toVaultRelative(inputImagePath); + const relativePngPath = pathUtils.toVaultRelative(pngFinalPath); const content = await plugin.app.vault.adapter.readBinary(relativeInputPath); ``` <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/ImageOptimizer.ts around lines 247-304 (and also the similar occurrences at ~220-234 and ~280-304), duplicate logic strips the vault base path and leading separators; extract this into PathUtils.toVaultRelative and replace the three duplicated blocks with calls to that helper. Add a public toVaultRelative(absolutePath: string) method on PathUtils that returns the original path if it does not start with getVaultPath(), otherwise removes the vault base prefix and any leading '/' or '\' and returns the result; then in ImageOptimizer create a PathUtils(plugin.app) instance and call toVaultRelative for inputImagePath, pngFinalPath and finalOutputPath before passing them to plugin.app.vault.adapter.readBinary/writeBinary/remove, removing the inline substring/startsWith logic so behavior remains identical. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee
const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png');
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);
// Convert absolute paths to vault-relative paths for adapter operations
const pathUtils = new PathUtils(plugin.app);
const vaultBasePath = pathUtils.getVaultPath();
let relativeInputPath = inputImagePath;
if (inputImagePath.startsWith(vaultBasePath)) {
// Remove vault base path and leading separator
relativeInputPath = inputImagePath.substring(vaultBasePath.length);
if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) {
relativeInputPath = relativeInputPath.substring(1);
}
}
let relativePngPath = pngFinalPath;
if (pngFinalPath.startsWith(vaultBasePath)) {
// Remove vault base path and leading separator
relativePngPath = pngFinalPath.substring(vaultBasePath.length);
if (relativePngPath.startsWith('/') || relativePngPath.startsWith('\\')) {
relativePngPath = relativePngPath.substring(1);
}
}
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
await plugin.app.vault.adapter.writeBinary(relativePngPath, content);
await plugin.app.vault.adapter.remove(relativeInputPath);
} else {
await fs.rename(inputImagePath, pngFinalPath);
}
@@ -255,9 +277,31 @@ export class ImageOptimizer {
} else {
// Keep as PNG, just rename to final location
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);
// Convert absolute paths to vault-relative paths for adapter operations
const pathUtils = new PathUtils(plugin.app);
const vaultBasePath = pathUtils.getVaultPath();
let relativeInputPath = inputImagePath;
if (inputImagePath.startsWith(vaultBasePath)) {
// Remove vault base path and leading separator
relativeInputPath = inputImagePath.substring(vaultBasePath.length);
if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) {
relativeInputPath = relativeInputPath.substring(1);
}
}
let relativeFinalPath = finalOutputPath;
if (finalOutputPath.startsWith(vaultBasePath)) {
// Remove vault base path and leading separator
relativeFinalPath = finalOutputPath.substring(vaultBasePath.length);
if (relativeFinalPath.startsWith('/') || relativeFinalPath.startsWith('\\')) {
relativeFinalPath = relativeFinalPath.substring(1);
}
}
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
await plugin.app.vault.adapter.writeBinary(relativeFinalPath, content);
await plugin.app.vault.adapter.remove(relativeInputPath);
} else {
await fs.rename(inputImagePath, finalOutputPath);
}
1
@@ -94,9 +94,10 @@ export class FrontmatterProcessor {
}
// Handle frontmatter preservation and display options
const finalFrontmatter = this.noteTitle ?
{ ...parsed.data, title: this.noteTitle } :
parsed.data;
const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
const finalFrontmatter = this.noteTitle ?
{ ...sanitizedFrontmatter, title: this.noteTitle } :
sanitizedFrontmatter;
if (this.preserveFrontmatter) {
// Keep the frontmatter in the content, but reconstruct it with the modified title
1
@@ -236,6 +237,20 @@ export class FrontmatterProcessor {
}
}
/**
* Strip citation-related fields from frontmatter to prevent Pandoc bibliography processing
*/
private stripCitationFields(frontmatter: Record<string, unknown>): Record<string, unknown> {
const citationFields = ['bibliography', 'references', 'csl', 'citation-style', 'nocite', 'link-citations', 'reference-section-title'];
const sanitized = { ...frontmatter };
for (const field of citationFields) {
delete sanitized[field];
}
return sanitized;
}
/**
* Format frontmatter as a readable display block
*/
+9 -2
View File
@@ -106,6 +106,11 @@ export class PathUtils {
return '';
}
const result = path.join(...filtered);
// Don't use normalizePath on absolute paths as it strips the leading slash
// Only normalize vault-relative paths
if (path.isAbsolute(result)) {
return result;
}
return normalizePath(result);
}
@@ -133,8 +138,10 @@ export class PathUtils {
await this.app.vault.adapter.mkdir(normalizedPath);
}
} catch (error) {
new Notice(`Failed to create directory: ${normalizedPath}`);
throw error;
const errorMessage = error instanceof Error ? error.message : String(error);
const userMessage = `Failed to create output directory "${normalizedPath}". ${errorMessage.includes('parent') || errorMessage.includes('ENOENT') ? 'The parent directory may not exist or you may not have write permissions.' : 'You may not have write permissions or the path is invalid.'}`;
new Notice(userMessage);
throw new Error(userMessage);
}
}
+22 -9
View File
@@ -24,6 +24,7 @@ import { PLUGIN_DIRS } from './constants';
import { normalizePath } from 'obsidian';
import type { App } from 'obsidian';
import * as path from 'path';
import { promises as fs } from 'fs';
/**
* Configuration options for TempDirectoryManager initialization.
@@ -167,7 +168,8 @@ export class TempDirectoryManager {
private getPluginDir(): string {
// path.join automatically handles absolute paths correctly
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
return normalizePath(result);
// Don't normalize absolute paths as normalizePath strips the leading slash
return path.isAbsolute(result) ? result : normalizePath(result);
}
/**
@@ -207,7 +209,8 @@ export class TempDirectoryManager {
// Use path.join to properly handle absolute paths
const result = path.join(pluginDir, dirName);
return normalizePath(result);
// Don't normalize absolute paths as normalizePath strips the leading slash
return path.isAbsolute(result) ? result : normalizePath(result);
}
/**
@@ -253,9 +256,13 @@ export class TempDirectoryManager {
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);
// Use fs.mkdir for temp directories since external tools (pdf2img, ImageMagick)
// need to write to them directly with absolute paths
try {
await fs.access(tempDir);
} catch {
// Directory doesn't exist, create it with recursive option
await fs.mkdir(tempDir, { recursive: true });
}
return tempDir;
@@ -302,13 +309,19 @@ export class TempDirectoryManager {
public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
const tempDir = this.getTempDir(type);
// Use fs for temp directory cleanup since these directories contain
// files created by external tools
try {
const exists = await this.app.vault.adapter.exists(tempDir);
const exists = await fs.access(tempDir).then(() => true).catch(() => false);
if (exists) {
const list = await this.app.vault.adapter.list(tempDir);
const files = await fs.readdir(tempDir);
// Remove only files, not subdirectories (matching current pattern)
for (const file of list.files) {
await this.app.vault.adapter.remove(file);
for (const file of files) {
const filePath = path.join(tempDir, file);
const stat = await fs.stat(filePath);
if (stat.isFile()) {
await fs.unlink(filePath);
}
}
}
return true;
+42 -8
View File
@@ -158,7 +158,18 @@ export class EmbedProcessor {
const buffer = Buffer.concat(chunks);
// Convert Buffer to ArrayBuffer for vault adapter
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
await this.plugin.app.vault.adapter.writeBinary(outputPath, arrayBuffer);
// Convert absolute path to vault-relative for adapter operations
const vaultBasePath = this.pathUtils.getVaultPath();
let relativeOutputPath = outputPath;
if (outputPath.startsWith(vaultBasePath)) {
relativeOutputPath = outputPath.substring(vaultBasePath.length);
if (relativeOutputPath.startsWith('/') || relativeOutputPath.startsWith('\\')) {
relativeOutputPath = relativeOutputPath.substring(1);
}
}
await this.plugin.app.vault.adapter.writeBinary(relativeOutputPath, arrayBuffer);
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
resolve(outputPath);
@@ -342,9 +353,12 @@ export class EmbedProcessor {
// Convert WebP to PNG using ImageMagick
const originalImageName = path.basename(fullImagePath);
const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultTempImagesDir);
// Use vault-relative path for ensureDir (it uses vault.adapter)
const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultRelativeTempDir);
// But use absolute path for ImageMagick
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
const execAsync = util.promisify(exec);
@@ -525,8 +539,11 @@ export class EmbedProcessor {
vaultBasePath: string
): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
// Copy image to vault temp directory for access
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultTempImagesDir);
// Use vault-relative path for ensureDir (it uses vault.adapter)
const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
await this.pathUtils.ensureDir(vaultRelativeTempDir);
// But use absolute path for file operations
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
// Sanitize the basename for use in filename - replace problematic characters
const sanitizedBaseName = baseName
@@ -538,8 +555,25 @@ export class EmbedProcessor {
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);
// Convert absolute paths to vault-relative paths for adapter operations
let relativeSourcePath = imagePath;
if (imagePath.startsWith(vaultBasePath)) {
relativeSourcePath = imagePath.substring(vaultBasePath.length);
if (relativeSourcePath.startsWith('/') || relativeSourcePath.startsWith('\\')) {
relativeSourcePath = relativeSourcePath.substring(1);
}
}
let relativeVaultImagePath = vaultImagePath;
if (vaultImagePath.startsWith(vaultBasePath)) {
relativeVaultImagePath = vaultImagePath.substring(vaultBasePath.length);
if (relativeVaultImagePath.startsWith('/') || relativeVaultImagePath.startsWith('\\')) {
relativeVaultImagePath = relativeVaultImagePath.substring(1);
}
}
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSourcePath);
await this.plugin.app.vault.adapter.writeBinary(relativeVaultImagePath, sourceBuffer);
// Get relative paths from vault base
const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
+4 -3
View File
@@ -143,7 +143,7 @@ export class ExportOrchestrator {
this.plugin.currentExportController = new AbortController();
try {
// Create temp directory for conversion
// Create temp directories for conversion
const tempManager = new TempDirectoryManager({
vaultPath: vaultPath,
configDir: this.plugin.app.vault.configDir,
@@ -151,6 +151,7 @@ export class ExportOrchestrator {
pluginName: this.plugin.manifest.id
});
const tempDir = await tempManager.ensureTempDir('pandoc');
const tempImagesDir = await tempManager.ensureTempDir('images');
// Load file content
const content = await this.plugin.app.vault.read(file);
@@ -191,12 +192,12 @@ export class ExportOrchestrator {
// Process PDF embeds if any were found
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles;
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles);
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempImagesDir, file, embedPdfFiles);
}
// Process image embeds if any were found
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempDir, file);
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempImagesDir, file);
}
// Process file embeds if any were found
+11 -5
View File
@@ -59,16 +59,21 @@ export class PathResolver {
* Prepare the output path for a file
*/
async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> {
// Check if output folder is set
if (!outputFolder || outputFolder.trim() === '') {
throw new Error('Output folder is not set. Please configure the output folder in plugin settings.');
}
// Validate output folder for security
if (!SecurityUtils.validateOutputPath(outputFolder)) {
throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`);
throw new Error(`Invalid output folder path: "${outputFolder}". Path contains invalid characters or traversal attempts.`);
}
const vaultPath = this.pathUtils.getVaultPath();
const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder);
// Create output directory if it doesn't exist
await this.pathUtils.ensureDir(outputDir);
// Create output directory if it doesn't exist (use vault-relative path for vault adapter)
await this.pathUtils.ensureDir(outputFolder);
// Preserve folder structure if configured
let relativePath = '';
@@ -76,8 +81,9 @@ export class PathResolver {
const folderPath = path.dirname(file.path);
if (folderPath !== '.') {
relativePath = folderPath;
const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath);
await this.pathUtils.ensureDir(fullOutputDir);
// Use vault-relative path for vault adapter
const vaultRelativeOutputDir = this.pathUtils.joinPath(outputFolder, relativePath);
await this.pathUtils.ensureDir(vaultRelativeOutputDir);
}
}
+3 -1
View File
@@ -9,6 +9,7 @@ import {
Setting,
normalizePath
} from 'obsidian';
import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../main';
import { ExportFormat } from '../core/settings';
import { SecurityUtils } from '../core/SecurityUtils';
@@ -184,7 +185,8 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
.setPlaceholder('Exports')
.setValue(this.plugin.settings.outputFolder)
.onChange(async (value) => {
const normalizedValue = normalizePath(value);
// Don't normalize absolute paths as normalizePath strips the leading slash
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue));
return;
1
+20 -4
View File
@@ -57,8 +57,16 @@ export class EmbeddedTemplateManager {
}
coderabbitai[bot] commented 2025-11-05 19:26:59 +01:00 (Migrated from github.com)
Review

🛠️ Refactor suggestion | 🟠 Major

Extract duplicated path conversion logic to PathUtils helper.

The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts.

Add a toVaultRelative() helper to PathUtils (see detailed suggestion in ImageOptimizer.ts review), then simplify both locations:

 try {
-  // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
-  const vaultPath = this.pathUtils.getVaultPath();
-  let relativeTemplatesDir = this.templatesDir;
-  if (this.templatesDir.startsWith(vaultPath)) {
-    relativeTemplatesDir = this.templatesDir.substring(vaultPath.length);
-    if (relativeTemplatesDir.startsWith('/') || relativeTemplatesDir.startsWith('\\')) {
-      relativeTemplatesDir = relativeTemplatesDir.substring(1);
-    }
-  }
+  const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
   await this.pathUtils.ensureDir(relativeTemplatesDir);

Also applies to: 116-125

✅ Addressed in commits f0daebc to c1c02ee

_🛠️ Refactor suggestion_ | _🟠 Major_ **Extract duplicated path conversion logic to PathUtils helper.** The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts. Add a `toVaultRelative()` helper to PathUtils (see detailed suggestion in ImageOptimizer.ts review), then simplify both locations: ```diff try { - // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter) - const vaultPath = this.pathUtils.getVaultPath(); - let relativeTemplatesDir = this.templatesDir; - if (this.templatesDir.startsWith(vaultPath)) { - relativeTemplatesDir = this.templatesDir.substring(vaultPath.length); - if (relativeTemplatesDir.startsWith('/') || relativeTemplatesDir.startsWith('\\')) { - relativeTemplatesDir = relativeTemplatesDir.substring(1); - } - } + const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir); await this.pathUtils.ensureDir(relativeTemplatesDir); ``` Also applies to: 116-125 <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee
try {
// Ensure templates directory exists
await this.pathUtils.ensureDir(this.templatesDir);
// Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
const vaultPath = this.pathUtils.getVaultPath();
let relativeTemplatesDir = this.templatesDir;
if (this.templatesDir.startsWith(vaultPath)) {
relativeTemplatesDir = this.templatesDir.substring(vaultPath.length);
if (relativeTemplatesDir.startsWith('/') || relativeTemplatesDir.startsWith('\\')) {
relativeTemplatesDir = relativeTemplatesDir.substring(1);
}
}
await this.pathUtils.ensureDir(relativeTemplatesDir);
// Extract template content
const content = extractTemplate(templateName, filePath);
@@ -105,8 +113,16 @@ export class EmbeddedTemplateManager {
const embeddedNames = getAllTemplateNames();
// Ensure templates directory exists
await this.pathUtils.ensureDir(this.templatesDir);
// Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
const vaultPath = this.pathUtils.getVaultPath();
let relativeTemplatesDir = this.templatesDir;
if (this.templatesDir.startsWith(vaultPath)) {
relativeTemplatesDir = this.templatesDir.substring(vaultPath.length);
if (relativeTemplatesDir.startsWith('/') || relativeTemplatesDir.startsWith('\\')) {
relativeTemplatesDir = relativeTemplatesDir.substring(1);
}
}
await this.pathUtils.ensureDir(relativeTemplatesDir);
for (const templateName of embeddedNames) {
try {
+3 -1
View File
@@ -4,6 +4,7 @@
*/
import { Setting, App, normalizePath, DropdownComponent } from 'obsidian';
import * as path from 'path';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { ExportFormat } from '../../../core/settings';
import { FolderSuggest } from '../../components/FolderSuggest';
1
@@ -80,7 +81,8 @@ export class GeneralSection implements ModalSection {
.setPlaceholder('PDF exports')
.setValue(state.settings.outputFolder || 'exports')
.onChange(value => {
const normalizedValue = normalizePath(value);
// Don't normalize absolute paths as normalizePath strips the leading slash
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
state.updateSettings({ outputFolder: normalizedValue });
});
this.outputFolderInput = input.inputEl;
1