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
AlexKucera commented 2025-09-25 12:48:11 +02:00 (Migrated from github.com)

Improves file handling by migrating from Node.js fs/path to Obsidian's vault.adapter API, centralizing path operations, and enhancing error reporting.

  • Introduces PathUtils for centralized and safe path manipulations within the Obsidian vault.
  • Fixes embedded file path resolution issues, preventing "File not found" errors for PDFs, images, and documents.
  • Updates all core files with consistent and secure path handling practices.

Summary by CodeRabbit

  • New Features
    • Centralized path/temp utilities, plugin-aware temp management, embedded Typst templates, and improved cross-platform font discovery.
  • Bug Fixes
    • Better Windows compatibility, dynamic image format support, improved pattern matching, more robust binary discovery, and resilient font-cache handling.
  • Refactor
    • IO flows made vault-aware and asynchronous for more reliable cross-platform file handling.
  • Documentation
    • Added changelog entries (1.3.0, 1.3.1), README badge, and a cross-platform implementation plan.
  • Chores
    • Bumped package and manifest versions to 1.3.0.
Improves file handling by migrating from Node.js fs/path to Obsidian's vault.adapter API, centralizing path operations, and enhancing error reporting. - Introduces PathUtils for centralized and safe path manipulations within the Obsidian vault. - Fixes embedded file path resolution issues, preventing "File not found" errors for PDFs, images, and documents. - Updates all core files with consistent and secure path handling practices. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - New Features - Centralized path/temp utilities, plugin-aware temp management, embedded Typst templates, and improved cross-platform font discovery. - Bug Fixes - Better Windows compatibility, dynamic image format support, improved pattern matching, more robust binary discovery, and resilient font-cache handling. - Refactor - IO flows made vault-aware and asynchronous for more reliable cross-platform file handling. - Documentation - Added changelog entries (1.3.0, 1.3.1), README badge, and a cross-platform implementation plan. - Chores - Bumped package and manifest versions to 1.3.0. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
coderabbitai[bot] commented 2025-09-25 12:48:18 +02:00 (Migrated from github.com)

Caution

Review failed

The pull request is closed.

Walkthrough

Replaces direct Node fs/path usage with a vault-aware PathUtils and app-aware TempDirectoryManager; converts many sync filesystem ops to async vault.adapter calls; threads plugin/app context through converters, discovery, and template extraction; bumps package/manifest to 1.3.0 and adds changelog/docs.

Changes

Cohort / File(s) Summary
Versioning & Docs
CHANGELOG.md, manifest.json, package.json, README.md, plan-coderabbit.md
Bumped versions to 1.3.0, added changelog/plan/docs and a README badge; documentation and metadata updates only.
Core utilities
src/core/PathUtils.ts, src/core/TempDirectoryManager.ts
Added PathUtils (vault-aware join/fileExists/ensureDir/cleanup/getVaultPath/getPluginDir) and made TempDirectoryManager app-aware and async (ensure/cleanup return Promises; use vault.adapter and normalizePath).
Pandoc / resource resolution
src/converters/PandocTypstConverter.ts, src/converters/pandoc/PandocCommandBuilder.ts, src/converters/pandoc/ResourcePathResolver.ts
Replaced fs/path with PathUtils and vault.adapter; ResourcePathResolver now accepts plugin/app, scans vault asynchronously, adds caching and new signatures/params.
PDF → Image & binary discovery
src/converters/PdfToImageConverter.ts, src/converters/pdf/FileDiscovery.ts, src/converters/pdf/ImageOptimizer.ts, src/converters/pdf/BinaryLocator.ts
Made discovery, optimization, and binary lookup plugin-aware; introduced PathUtils usage and vault.adapter ops; updated signatures: findGeneratedFile, optimizeImage, and file/binary lookup flows accept optional plugin/app context.
Templates
src/templates/TemplateManager.ts, src/templates/embeddedTemplates.ts
Switched template discovery, reads/writes, and extraction to PathUtils + vault.adapter; EmbeddedTemplateManager now requires app and several APIs became async (getTemplateInfo, extractTemplateIfNeeded, extractAllMissingTemplates, forceExtractAllTemplates).
Plugin orchestration & embedding
src/plugin/ExportOrchestrator.ts, src/plugin/PluginLifecycle.ts, src/plugin/PathResolver.ts, src/plugin/EmbedProcessor.ts, src/plugin/FontManager.ts
Initialized/used PathUtils; updated TempDirectoryManager usage to include app and async flows; replaced fs/path ops with PathUtils/vault.adapter across embedding, path resolution, font cache handling, and lifecycle cleanup.
Misc converters & propagation
src/converters/*, src/converters/pandoc/*
Propagated PathUtils/plugin/app parameters across converter internals; replaced synchronous fs calls with vault-aware async operations; no public API removals.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant EO as ExportOrchestrator
  participant PU as PathUtils
  participant TDM as TempDirectoryManager
  participant PTC as PandocTypstConverter
  participant RPR as ResourcePathResolver
  participant PIC as PdfToImageConverter
  participant FD as FileDiscovery
  participant IO as ImageOptimizer
  participant VA as vault.adapter

  U->>EO: export()
  EO->>PU: getVaultPath(), joinPath()
  EO->>TDM: ensureTempDir(type) (await)
  EO->>PTC: convert(...)
  PTC->>PU: joinPath(), fileExists()
  PTC->>VA: write/remove temp files
  PTC->>RPR: getResourcePaths()
  RPR->>VA: list(vault root) / list(folder)
  RPR->>PU: joinPath()
  EO->>PIC: pdfToImage(...)
  PIC->>PU: ensureDir(output)
  PIC->>FD: findGeneratedFile(..., plugin)
  FD->>VA: list(...) or fileExists(...)
  PIC->>IO: optimizeImage(..., plugin)
  IO->>VA: read/write/remove/rename
  EO->>TDM: cleanupAllTempDirs() (await)
  EO-->>U: result
sequenceDiagram
  autonumber
  participant PCB as PandocCommandBuilder
  participant RPR as ResourcePathResolver
  participant PU as PathUtils
  participant VA as vault.adapter

  PCB->>RPR: getResourcePaths()
  alt cache valid
    RPR-->>PCB: return cached paths
  else recalc
    RPR->>PU: getVaultPath()
    RPR->>VA: list(vault root)
    loop for each folder
      RPR->>VA: list(folder)
      RPR-->>RPR: detect image directories
    end
    RPR-->>PCB: computed paths
  end

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60–90 minutes

Possibly related PRs

  • AlexKucera/obsidian-typst-pdf-export#5 — Introduces the same PathUtils/vault.adapter refactor and many overlapping changes (PathUtils, TempDirectoryManager, ResourcePathResolver, FileDiscovery, ImageOptimizer, BinaryLocator), likely the same workstream or duplicate patch.

Poem

I hop through vaults where paths now gleam,
Async burrows tidy every stream.
Templates planted, temp carrots aligned,
Bumped the version — exports all refined. 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title concisely and accurately reflects the primary focus of the changeset, which centers on improving path handling and file resolution by introducing PathUtils, replacing Node fs/path calls, and updating file operations across modules.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 21ed9e122f and ff8e9f9ea3.

📒 Files selected for processing (1)
  • src/core/PathUtils.ts (1 hunks)

Comment @coderabbitai help to get the list of available commands and usage tips.

<!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- This is an auto-generated comment: failure by coderabbit.ai --> > [!CAUTION] > ## Review failed > > The pull request is closed. <!-- end of auto-generated comment: failure by coderabbit.ai --> <!-- walkthrough_start --> ## Walkthrough Replaces direct Node fs/path usage with a vault-aware PathUtils and app-aware TempDirectoryManager; converts many sync filesystem ops to async vault.adapter calls; threads plugin/app context through converters, discovery, and template extraction; bumps package/manifest to 1.3.0 and adds changelog/docs. ## Changes | Cohort / File(s) | Summary | |---|---| | **Versioning & Docs**<br>`CHANGELOG.md`, `manifest.json`, `package.json`, `README.md`, `plan-coderabbit.md` | Bumped versions to 1.3.0, added changelog/plan/docs and a README badge; documentation and metadata updates only. | | **Core utilities**<br>`src/core/PathUtils.ts`, `src/core/TempDirectoryManager.ts` | Added `PathUtils` (vault-aware join/fileExists/ensureDir/cleanup/getVaultPath/getPluginDir) and made `TempDirectoryManager` app-aware and async (ensure/cleanup return Promises; use vault.adapter and normalizePath). | | **Pandoc / resource resolution**<br>`src/converters/PandocTypstConverter.ts`, `src/converters/pandoc/PandocCommandBuilder.ts`, `src/converters/pandoc/ResourcePathResolver.ts` | Replaced fs/path with `PathUtils` and vault.adapter; ResourcePathResolver now accepts plugin/app, scans vault asynchronously, adds caching and new signatures/params. | | **PDF → Image & binary discovery**<br>`src/converters/PdfToImageConverter.ts`, `src/converters/pdf/FileDiscovery.ts`, `src/converters/pdf/ImageOptimizer.ts`, `src/converters/pdf/BinaryLocator.ts` | Made discovery, optimization, and binary lookup plugin-aware; introduced `PathUtils` usage and vault.adapter ops; updated signatures: `findGeneratedFile`, `optimizeImage`, and file/binary lookup flows accept optional plugin/app context. | | **Templates**<br>`src/templates/TemplateManager.ts`, `src/templates/embeddedTemplates.ts` | Switched template discovery, reads/writes, and extraction to `PathUtils` + vault.adapter; `EmbeddedTemplateManager` now requires `app` and several APIs became async (getTemplateInfo, extractTemplateIfNeeded, extractAllMissingTemplates, forceExtractAllTemplates). | | **Plugin orchestration & embedding**<br>`src/plugin/ExportOrchestrator.ts`, `src/plugin/PluginLifecycle.ts`, `src/plugin/PathResolver.ts`, `src/plugin/EmbedProcessor.ts`, `src/plugin/FontManager.ts` | Initialized/used `PathUtils`; updated TempDirectoryManager usage to include app and async flows; replaced fs/path ops with PathUtils/vault.adapter across embedding, path resolution, font cache handling, and lifecycle cleanup. | | **Misc converters & propagation**<br>`src/converters/*`, `src/converters/pandoc/*` | Propagated PathUtils/plugin/app parameters across converter internals; replaced synchronous fs calls with vault-aware async operations; no public API removals. | ## Sequence Diagram(s) ```mermaid sequenceDiagram autonumber participant U as User participant EO as ExportOrchestrator participant PU as PathUtils participant TDM as TempDirectoryManager participant PTC as PandocTypstConverter participant RPR as ResourcePathResolver participant PIC as PdfToImageConverter participant FD as FileDiscovery participant IO as ImageOptimizer participant VA as vault.adapter U->>EO: export() EO->>PU: getVaultPath(), joinPath() EO->>TDM: ensureTempDir(type) (await) EO->>PTC: convert(...) PTC->>PU: joinPath(), fileExists() PTC->>VA: write/remove temp files PTC->>RPR: getResourcePaths() RPR->>VA: list(vault root) / list(folder) RPR->>PU: joinPath() EO->>PIC: pdfToImage(...) PIC->>PU: ensureDir(output) PIC->>FD: findGeneratedFile(..., plugin) FD->>VA: list(...) or fileExists(...) PIC->>IO: optimizeImage(..., plugin) IO->>VA: read/write/remove/rename EO->>TDM: cleanupAllTempDirs() (await) EO-->>U: result ``` ```mermaid sequenceDiagram autonumber participant PCB as PandocCommandBuilder participant RPR as ResourcePathResolver participant PU as PathUtils participant VA as vault.adapter PCB->>RPR: getResourcePaths() alt cache valid RPR-->>PCB: return cached paths else recalc RPR->>PU: getVaultPath() RPR->>VA: list(vault root) loop for each folder RPR->>VA: list(folder) RPR-->>RPR: detect image directories end RPR-->>PCB: computed paths end ``` ## Estimated code review effort 🎯 4 (Complex) | ⏱️ ~60–90 minutes ## Possibly related PRs - AlexKucera/obsidian-typst-pdf-export#5 — Introduces the same PathUtils/vault.adapter refactor and many overlapping changes (PathUtils, TempDirectoryManager, ResourcePathResolver, FileDiscovery, ImageOptimizer, BinaryLocator), likely the same workstream or duplicate patch. ## Poem > I hop through vaults where paths now gleam, > Async burrows tidy every stream. > Templates planted, temp carrots aligned, > Bumped the version — exports all refined. 🥕 <!-- walkthrough_end --> <!-- pre_merge_checks_walkthrough_start --> ## Pre-merge checks and finishing touches <details> <summary>✅ Passed checks (3 passed)</summary> | Check name | Status | Explanation | | :----------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. | | Title Check | ✅ Passed | The pull request title concisely and accurately reflects the primary focus of the changeset, which centers on improving path handling and file resolution by introducing PathUtils, replacing Node fs/path calls, and updating file operations across modules. | | Docstring Coverage | ✅ Passed | No functions found in the changes. Docstring coverage check skipped. | </details> <!-- pre_merge_checks_walkthrough_end --> --- <details> <summary>📜 Recent review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 21ed9e122f6a727cf3aaa2e543a3a1308fd72500 and ff8e9f9ea3c24b1f806d07300c2dd9d1c62d4ebe. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/core/PathUtils.ts` (1 hunks) </details> </details> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands and usage tips.</sub> <!-- tips_end --> <!-- internal state start --> <!-- DwQg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xImHCiadSmDp0VotGE28SXLUGWgYAC8msgsFXNB/guMBK2FEuLBonbQoIQhmcgKJYmjfRenBx0rAL+ExBltMACyw7x8AYIEC5bMbykpwJEZ/F+kErYMCUBgCJ6gO9Y3eRROdlQ071VDLnY4ku9YwW53rdmfECIGs2fFtxBkQoMyEYQ9+PAFshidbmOpBLKEdwKprIzCKMhtAXQGCgDAK2JUh1AMYQWBEAMYQZo6AMYXG9EQcSG9jJIRgGZAAAdiBAGAZkDpAggZkFoAY4kgG5AygUEAAA2BgCBBVAGkCBA0ARIAhBeQIEFoAaQBgCziM4mOKzjaACEDDBTIKOPLj643kAYBi4tACcsygLOJzjEgbkGZBQQVuIEAgQWON5BuQGkDVAygAQDKBeQWgFLje46GEbiIAWkAYBaABOIYBQQWONriaQWgGZA0AUEESAygEgF3jK42gFBAaQAuKziygRIFBAygCEC9BjEGOOeBF4qAALi6AZkBIAFoGkESAs4tABjiaQGOLbjQQNAGASaQEgDKBuQIBKASgQUEBLjEgVOIZAIQKEAjifYmiD9iA4oOMeVzQEOOkhPYvQCAA= --> <!-- internal state end -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-09-25 13:05:42 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 14

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/converters/pandoc/PandocCommandBuilder.ts (2)

68-70: Avoid global process.chdir; set cwd on the child process instead.

Changing the process CWD can affect the whole app. Set cwd in the PandocExecutor spawn options.

-    if (pandocOptions.vaultBasePath) {
-      process.chdir(pandocOptions.vaultBasePath);
-    }
+    // Set cwd via PandocExecutor spawn options instead of chdir here.

In PandocExecutor (not shown), pass { cwd: pandocOptions.vaultBasePath } to spawn.


116-124: Normalize template path to POSIX for Typst and cross‑platform robustness.

On Windows, path.relative yields backslashes which may break Typst import.

       let templatePathForTypst = pandocOptions.template;
       if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) {
         // Make template path relative to vault for Typst import
-        templatePathForTypst = path.relative(pandocOptions.vaultBasePath, templatePathForTypst);
+        templatePathForTypst = path
+          .relative(pandocOptions.vaultBasePath, templatePathForTypst)
+          .split(path.sep).join('/');
       }
src/plugin/EmbedProcessor.ts (1)

191-197: Normalize relative paths to POSIX (‘/’) before embedding and linking.

Ensure paths work on Windows and Typst by converting backslashes.

Apply these diffs:

-    const relativeImagePath = path.relative(vaultBasePath, finalImagePath);
+    const relativeImagePath = path.relative(vaultBasePath, finalImagePath).split(path.sep).join('/');
-    const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
-    const relativePdfPath = path.relative(vaultBasePath, pdfPath);
+    const relativeImagePath = path.relative(vaultBasePath, vaultImagePath).split(path.sep).join('/');
+    const relativePdfPath = path.relative(vaultBasePath, pdfPath).split(path.sep).join('/');
-    const relativeFilePath = path.relative(vaultBasePath, fullFilePath);
+    const relativeFilePath = path.relative(vaultBasePath, fullFilePath).split(path.sep).join('/');
-    const relativePdfPath = path.relative(vaultBasePath, pdfEmbed.originalPath);
+    const relativePdfPath = path.relative(vaultBasePath, pdfEmbed.originalPath).split(path.sep).join('/');
-    const relativeFilePath = path.relative(vaultBasePath, fileEmbed.originalPath);
+    const relativeFilePath = path.relative(vaultBasePath, fileEmbed.originalPath).split(path.sep).join('/');

Also applies to: 430-433, 256-273, 78-86, 91-99

🧹 Nitpick comments (21)
CHANGELOG.md (1)

8-28: Changelog date/order inconsistency

1.3.0 is dated 2024-12-25 but appears above 1.2.1 dated 2025-01-10. Adjust dates or ordering to keep newest at top and dates ascending chronologically.

src/core/PathUtils.ts (1)

25-27: Type safety: PluginManifest doesn’t declare 'dir'

Accessing manifest.dir will fail under strict TS. Use a narrowed type or index access.

Apply this diff:

-	getPluginDir(pluginManifest: PluginManifest): string {
-		return normalizePath(pluginManifest.dir || '');
-	}
+	getPluginDir(pluginManifest: PluginManifest): string {
+		const anyManifest = pluginManifest as unknown as { dir?: string };
+		return normalizePath(anyManifest.dir ?? '');
+	}
src/converters/pdf/BinaryLocator.ts (2)

87-96: Derive plugin directory robustly via PathUtils.getPluginDir with safe fallbacks

Using manifest.dir directly can be inconsistent. Prefer PathUtils.getPluginDir, and fall back to configDir/plugins/{manifest.id}.

Apply this diff:

-	private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] {
-		return [
+	private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] {
+		const dirs: string[] = [
 			// 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!)] : [])
-		];
+		];
+		if (plugin) {
+			const pu = new PathUtils(plugin.app);
+			const manifestDir = pu.getPluginDir(plugin.manifest);
+			if (manifestDir) {
+				// If manifest.dir is vault-relative (common), make absolute
+				dirs.push(path.join(pu.getVaultPath(), manifestDir));
+			}
+			// Fallback: configDir/plugins/{id}
+			dirs.push(path.join(pu.getVaultPath(), plugin.app.vault.configDir, 'plugins', plugin.manifest.id));
+		}
+		return dirs;
 	}

36-50: Graceful fallback when plugin is undefined

The existence check is skipped if plugin?.app is falsy, but you still proceed with a default path. Either allow fs-based checks here or require plugin explicitly.

Apply this diff:

-			for (const dir of possiblePluginDirs) {
+			for (const dir of possiblePluginDirs) {
 				try {
 					const nodeModulesPath = path.join(dir, 'node_modules');
-					if (plugin?.app) {
-						const pathUtils = new PathUtils(plugin.app);
-						if (await pathUtils.fileExists(nodeModulesPath)) {
-							pluginDir = dir;
-							break;
-						}
-					}
+					if (plugin?.app) {
+						const pathUtils = new PathUtils(plugin.app);
+						if (await pathUtils.fileExists(nodeModulesPath)) {
+							pluginDir = dir;
+							break;
+						}
+					} else {
+						const fs = require('fs').promises as typeof import('fs').promises;
+						await fs.access(nodeModulesPath);
+						pluginDir = dir;
+						break;
+					}
 				} catch {
 					continue;
 				}
 			}
src/plugin/FontManager.ts (1)

70-75: DRY: factor cache path building into a private helper.

Avoid repeating path assembly.

Example (outside selected ranges):

private getFontsCacheVaultPath(): string {
  const pathUtils = new PathUtils(this.plugin.app);
  return pathUtils.joinPath(pathUtils.getPluginDir(this.plugin.manifest), 'fonts-cache.json');
}

Then replace local constructions with this.getFontsCacheVaultPath().

Also applies to: 92-97, 106-111

src/plugin/PathResolver.ts (1)

28-40: Use ‘where’ on Windows; ‘which’ isn’t available there.

Current approach silently falls back, degrading UX on Windows.

-    const { spawnSync } = require('child_process');
+    const { spawnSync } = require('child_process');
     try {
       const augmentedEnv = {
         ...process.env,
         PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
       };
-      
-      const result = spawnSync('which', [defaultName], {
+      const whichCmd = process.platform === 'win32' ? 'where' : 'which';
+      const result = spawnSync(whichCmd, [defaultName], {
         encoding: 'utf8',
         env: augmentedEnv
       });
src/templates/TemplateManager.ts (1)

19-23: Optional: keep both absolute and vault-relative template paths.

Store absolute for external consumers, and vault-relative for adapter calls.

Example:

private templatesPathAbs: string;
private templatesPathRel: string;

this.templatesPathRel = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'templates');
this.templatesPathAbs = this.pathUtils.joinPath(this.pathUtils.getVaultPath(), this.templatesPathRel);
src/converters/PandocTypstConverter.ts (1)

105-110: Prefer vault-relative paths for adapter.write.

Avoid writing with absolute tempInputPath. Convert to vault-relative before write.

-    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);
+    const pathUtils = new PathUtils(this.plugin.app);
+    const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
+    const vaultBase = pathUtils.getVaultPath();
+    const relTempInputPath = tempInputPath.startsWith(vaultBase)
+      ? tempInputPath.substring(vaultBase.length + (tempInputPath[vaultBase.length] === '/' ? 1 : 0))
+      : tempInputPath;
+    await this.plugin.app.vault.adapter.write(relTempInputPath, content);
src/plugin/EmbedProcessor.ts (2)

455-460: Escape quotes in Typst strings to avoid syntax errors.

File names/descriptions with " will break pdf.embed.

-    const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
+    const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
+    const safeDescription = description.replace(/"/g, '\\"');
+    const safePdfPath = relativePdfPath.split(path.sep).join('/').replace(/"/g, '\\"');
...
-    content.push(`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`);
+    content.push(`#pdf.embed("${safePdfPath}", description: "${safeDescription}", mime-type: "application/pdf")`);
-    const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
+    const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
+    const safeDescription = description.replace(/"/g, '\\"');
+    const safeFilePath = relativeFilePath.split(path.sep).join('/').replace(/"/g, '\\"');
...
-    content.push(`#pdf.embed("${relativeFilePath}", description: "${description}", mime-type: "${mimeType}")`);
+    content.push(`#pdf.embed("${safeFilePath}", description: "${safeDescription}", mime-type: "${mimeType}")`);

Also applies to: 481-486


426-428: Read via vault-relative source path when using adapter.readBinary.

Safer and adapter-portable.

-    const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath);
+    const relativeSource = path.relative(vaultBasePath, imagePath).split(path.sep).join('/');
+    const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSource);
src/converters/pandoc/ResourcePathResolver.ts (5)

9-17: Constructor/plugin wiring is fine, but consider making plugin required.
Avoid silent no-op code paths; this class isn’t useful without a plugin.


25-27: Avoid silent empty result when plugin/app is missing.
Log a warning to aid diagnostics instead of returning [] silently.

Apply this diff:

-		if (!vaultBasePath || !this.plugin?.app) {
-			return [];
-		}
+		if (!vaultBasePath || !this.plugin?.app) {
+			console.warn('ResourcePathResolver: missing vaultBasePath or plugin.app; returning no resource paths.');
+			return [];
+		}

54-55: Deduplicate resource paths before returning.
Prevents repeated directories (e.g., overlap between common and scanned paths).

Apply this diff:

-		return resourcePaths;
+		return Array.from(new Set(resourcePaths));

63-71: Include user-configured attachment folder.
Respect Obsidian’s “Default location for new attachments” when set.

Apply this diff:

-	private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] {
-		return [
-			pathUtils.joinPath(vaultBasePath, 'attachments'),
-			pathUtils.joinPath(vaultBasePath, 'assets'),
-			pathUtils.joinPath(vaultBasePath, 'files'),
-			pathUtils.joinPath(vaultBasePath, 'images'),
-			pathUtils.joinPath(vaultBasePath, '.attachments')
-		];
-	}
+	private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] {
+		const paths = [
+			pathUtils.joinPath(vaultBasePath, 'attachments'),
+			pathUtils.joinPath(vaultBasePath, 'assets'),
+			pathUtils.joinPath(vaultBasePath, 'files'),
+			pathUtils.joinPath(vaultBasePath, 'images'),
+			pathUtils.joinPath(vaultBasePath, '.attachments'),
+		];
+		// Obsidian setting: Default location for new attachments (if set to a fixed folder)
+		const userAttach = this.plugin?.app?.vault?.getConfig?.('attachmentFolderPath');
+		if (typeof userAttach === 'string' && userAttach.trim()) {
+			paths.push(pathUtils.joinPath(vaultBasePath, userAttach));
+		}
+		return paths;
+	}

108-110: Broaden detection to include PDFs and common document types (optional).
Embeds often include PDFs and office docs; include them in scan.

Apply this diff:

-						const hasImages = dirContents.files.some((file: string) =>
-							/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
-						);
+						const hasImages = dirContents.files.some((file: string) =>
+							/\.(png|jpe?g|gif|svg|webp|bmp|ico|tiff?|pdf|docx?|xlsx?|pptx?|odt|ods|odp)$/i.test(file)
+						);
src/plugin/PluginLifecycle.ts (1)

72-81: Consider awaiting the cleanup or documenting the fire-and-forget nature.

The async IIFE pattern is used here without awaiting the result, which means cleanup happens asynchronously during unload. This could potentially leave temp files if the plugin unloads quickly. Consider either:

  1. Making the cleanup() method async and awaiting this operation
  2. Adding a comment explaining why fire-and-forget is acceptable here
  /**
   * Clean up resources during onunload
+  * Note: Temp directory cleanup is fire-and-forget to avoid blocking plugin unload
   */
  cleanup(): void {
src/templates/embeddedTemplates.ts (1)

102-125: Consider parallel extraction for better performance.

The templates are extracted sequentially in the loop. Since template extractions are independent operations, consider using Promise.all() for parallel processing to improve performance.

-        for (const templateName of embeddedNames) {
-            try {
-                const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
-                const content = extractTemplate(templateName, filePath);
-
-                await this.app.vault.adapter.write(filePath, content);
-                extracted.push(templateName);
-            } catch (error) {
-                console.error(`Failed to force extract template ${templateName}:`, error);
-                failed.push(templateName);
-            }
-        }
+        const extractionPromises = embeddedNames.map(async (templateName) => {
+            try {
+                const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
+                const content = extractTemplate(templateName, filePath);
+                await this.app.vault.adapter.write(filePath, content);
+                return { name: templateName, success: true };
+            } catch (error) {
+                console.error(`Failed to force extract template ${templateName}:`, error);
+                return { name: templateName, success: false };
+            }
+        });
+        
+        const results = await Promise.all(extractionPromises);
+        for (const result of results) {
+            if (result.success) {
+                extracted.push(result.name);
+            } else {
+                failed.push(result.name);
+            }
+        }
src/converters/pdf/ImageOptimizer.ts (1)

234-242: Consider extracting duplicated file operation logic.

The pattern of reading binary, writing to new location, and removing the original is repeated multiple times (lines 235-237, 247-249). Consider extracting this into a helper method.

+    private static async moveFile(
+        sourcePath: string,
+        destPath: string,
+        plugin?: obsidianTypstPDFExport
+    ): Promise<void> {
+        if (plugin?.app) {
+            const content = await plugin.app.vault.adapter.readBinary(sourcePath);
+            await plugin.app.vault.adapter.writeBinary(destPath, content);
+            await plugin.app.vault.adapter.remove(sourcePath);
+        } else {
+            const fs = require('fs').promises;
+            await fs.rename(sourcePath, destPath);
+        }
+    }

     // Then use it in multiple places:
-    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);
-    }
+    await this.moveFile(inputImagePath, pngFinalPath, plugin);
src/core/TempDirectoryManager.ts (3)

1-2: Fix typo in ABOUTME comment.

Minor typo: "ABOUTME" should likely be "ABOUT" or removed entirely as it's non-standard.

-// ABOUTME: Manages temporary directories for export operations
-// ABOUTME: Uses normalizePath for cross-platform path operations
+// Manages temporary directories for export operations
+// Uses normalizePath for cross-platform path operations

35-37: Consider using PathUtils.joinPath for consistency.

Since PathUtils is available in the codebase and provides a joinPath method that handles normalization, consider using it here for consistency with other modules.

-    return normalizePath([this.vaultPath, this.configDir, 'plugins', this.pluginName].join('/'));
+    const pathUtils = new PathUtils(this.app);
+    return pathUtils.joinPath(this.vaultPath, this.configDir, 'plugins', this.pluginName);

86-91: Consider using Promise.allSettled for independent operations.

Since cleaning up images and pandoc directories are independent operations, using Promise.allSettled would ensure both attempts are made even if one fails early.

  public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> {
-    return {
-      images: await this.cleanupTempDir('images'),
-      pandoc: await this.cleanupTempDir('pandoc')
-    };
+    const [imagesResult, pandocResult] = await Promise.allSettled([
+      this.cleanupTempDir('images'),
+      this.cleanupTempDir('pandoc')
+    ]);
+    return {
+      images: imagesResult.status === 'fulfilled' && imagesResult.value,
+      pandoc: pandocResult.status === 'fulfilled' && pandocResult.value
+    };
  }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e320238a79 and c971c920ce.

📒 Files selected for processing (19)
  • CHANGELOG.md (1 hunks)
  • manifest.json (1 hunks)
  • package.json (1 hunks)
  • src/converters/PandocTypstConverter.ts (5 hunks)
  • src/converters/PdfToImageConverter.ts (4 hunks)
  • src/converters/pandoc/PandocCommandBuilder.ts (3 hunks)
  • src/converters/pandoc/ResourcePathResolver.ts (4 hunks)
  • src/converters/pdf/BinaryLocator.ts (3 hunks)
  • src/converters/pdf/FileDiscovery.ts (2 hunks)
  • src/converters/pdf/ImageOptimizer.ts (5 hunks)
  • src/core/PathUtils.ts (1 hunks)
  • src/core/TempDirectoryManager.ts (2 hunks)
  • src/plugin/EmbedProcessor.ts (8 hunks)
  • src/plugin/ExportOrchestrator.ts (3 hunks)
  • src/plugin/FontManager.ts (4 hunks)
  • src/plugin/PathResolver.ts (2 hunks)
  • src/plugin/PluginLifecycle.ts (3 hunks)
  • src/templates/TemplateManager.ts (4 hunks)
  • src/templates/embeddedTemplates.ts (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (15)
src/plugin/ExportOrchestrator.ts (3)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/TempDirectoryManager.ts (1)
  • TempDirectoryManager (19-109)
src/converters/PdfToImageConverter.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pdf/FileDiscovery.ts (1)
  • FileDiscovery (19-256)
src/templates/TemplateManager.ts (1)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pandoc/ResourcePathResolver.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/core/TempDirectoryManager.ts (1)
src/core/constants.ts (1)
  • PLUGIN_DIRS (25-29)
src/plugin/EmbedProcessor.ts (1)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/PandocTypstConverter.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/core/TempDirectoryManager.ts (1)
  • TempDirectoryManager (19-109)
src/plugin/FontManager.ts (1)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/templates/embeddedTemplates.ts (1)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pandoc/PandocCommandBuilder.ts (2)
src/converters/pandoc/ResourcePathResolver.ts (1)
  • ResourcePathResolver (8-139)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pdf/ImageOptimizer.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/plugin/PathResolver.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/converters/pdf/FileDiscovery.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pdf/BinaryLocator.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/plugin/PluginLifecycle.ts (3)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/templates/embeddedTemplates.ts (1)
  • EmbeddedTemplateManager (14-141)
src/core/TempDirectoryManager.ts (1)
  • TempDirectoryManager (19-109)
🔇 Additional comments (19)
package.json (1)

3-3: Version bump looks good

Version updated to 1.3.0; consistent with the rest of the PR.

src/plugin/ExportOrchestrator.ts (1)

139-141: Guard against absolute pluginDir returned by manifest.

If manifest.dir is absolute, prepending vaultPath will duplicate the vault segment.

Suggested pattern:

-    const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
+    const manifestDir = this.pathUtils.getPluginDir(this.plugin.manifest);
+    const pluginDir = manifestDir.startsWith(vaultPath)
+      ? manifestDir
+      : this.pathUtils.joinPath(vaultPath, manifestDir);

Please confirm what plugin.manifest.dir returns at runtime (absolute vs vault-relative). If absolute, the above is required. If vault-relative, current code is fine.

src/converters/PandocTypstConverter.ts (1)

164-166: Cleanup: ensure adapter operations target vault-relative paths.

cleanupDir handles this internally, but if other adapter operations are added, prefer vault-relative paths for consistency.

src/converters/PdfToImageConverter.ts (2)

96-99: Ensure output dir via PathUtils across both code paths.

Looks good when plugin/app exists. If running without plugin (fallback), ensure the CLI creates the directory or add an fs fallback.


126-136: Nice: plugin-aware discovery and optimization wiring.

Passing plugin into FileDiscovery and ImageOptimizer aligns with the new PathUtils/vault adapter design.

Also applies to: 139-148

src/converters/pandoc/ResourcePathResolver.ts (2)

1-2: Imports look good.


79-83: Cache validation logic LGTM.
Time‑based and vault‑path scoped.

src/plugin/PluginLifecycle.ts (3)

14-19: LGTM! Clean dependency injection pattern.

The addition of PathUtils as a class member and its initialization in the constructor follows good object-oriented design practices.


87-102: LGTM! Consistent async cleanup pattern.

The fire-and-forget pattern is consistently applied here for startup cleanup, with appropriate error handling that doesn't block plugin initialization.


29-31: Ignore path composition concern. getPluginDir returns the plugin’s directory relative to the vault root (from manifest.dir), so joinPath(vaultPath, pluginDir) correctly yields the absolute plugin path.

Likely an incorrect or invalid review comment.

src/templates/embeddedTemplates.ts (4)

14-25: LGTM! Clean constructor update with App dependency.

The constructor signature change to accept the App instance enables proper integration with Obsidian's vault adapter API.


51-74: LGTM! Proper async conversion with vault adapter usage.

The method correctly uses PathUtils for path operations and the vault adapter for file writing, maintaining consistency with Obsidian's API.


79-97: LGTM! Clean async iteration pattern.

The method properly awaits each template extraction in sequence, collecting results appropriately.


30-46: No additional error handling needed for fileExists calls. PathUtils.fileExists catches all internal errors and always resolves to a boolean, so getTemplateInfo can safely rely on its result.

src/converters/pdf/ImageOptimizer.ts (2)

183-189: LGTM! Good optional parameter addition.

The optional plugin parameter maintains backward compatibility while enabling vault-aware operations when available.


197-205: LGTM! Proper conditional path handling.

The code correctly uses PathUtils when a plugin is available, falling back to Node.js path.join otherwise.

src/core/TempDirectoryManager.ts (3)

15-17: LGTM! Clean App integration.

The addition of the App instance to the options enables proper vault adapter usage throughout the class.


50-59: LGTM! Proper async conversion.

The method correctly uses async/await with vault adapter for directory operations.


64-81: LGTM! Consistent error handling.

The cleanup method properly handles errors and returns a boolean status, maintaining the expected API contract.

**Actionable comments posted: 14** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to platform limitations. > > > > <details> > <summary>⚠️ Outside diff range comments (3)</summary><blockquote> > > <details> > <summary>src/converters/pandoc/PandocCommandBuilder.ts (2)</summary><blockquote> > > `68-70`: **Avoid global process.chdir; set cwd on the child process instead.** > > Changing the process CWD can affect the whole app. Set `cwd` in the PandocExecutor spawn options. > > > ```diff > - if (pandocOptions.vaultBasePath) { > - process.chdir(pandocOptions.vaultBasePath); > - } > + // Set cwd via PandocExecutor spawn options instead of chdir here. > ``` > > In PandocExecutor (not shown), pass `{ cwd: pandocOptions.vaultBasePath }` to `spawn`. > > --- > > `116-124`: **Normalize template path to POSIX for Typst and cross‑platform robustness.** > > On Windows, `path.relative` yields backslashes which may break Typst import. > > > ```diff > let templatePathForTypst = pandocOptions.template; > if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) { > // Make template path relative to vault for Typst import > - templatePathForTypst = path.relative(pandocOptions.vaultBasePath, templatePathForTypst); > + templatePathForTypst = path > + .relative(pandocOptions.vaultBasePath, templatePathForTypst) > + .split(path.sep).join('/'); > } > ``` > > </blockquote></details> > <details> > <summary>src/plugin/EmbedProcessor.ts (1)</summary><blockquote> > > `191-197`: **Normalize relative paths to POSIX (‘/’) before embedding and linking.** > > Ensure paths work on Windows and Typst by converting backslashes. > > > Apply these diffs: > > ```diff > - const relativeImagePath = path.relative(vaultBasePath, finalImagePath); > + const relativeImagePath = path.relative(vaultBasePath, finalImagePath).split(path.sep).join('/'); > ``` > > ```diff > - const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); > - const relativePdfPath = path.relative(vaultBasePath, pdfPath); > + const relativeImagePath = path.relative(vaultBasePath, vaultImagePath).split(path.sep).join('/'); > + const relativePdfPath = path.relative(vaultBasePath, pdfPath).split(path.sep).join('/'); > ``` > > ```diff > - const relativeFilePath = path.relative(vaultBasePath, fullFilePath); > + const relativeFilePath = path.relative(vaultBasePath, fullFilePath).split(path.sep).join('/'); > ``` > > ```diff > - const relativePdfPath = path.relative(vaultBasePath, pdfEmbed.originalPath); > + const relativePdfPath = path.relative(vaultBasePath, pdfEmbed.originalPath).split(path.sep).join('/'); > ``` > > ```diff > - const relativeFilePath = path.relative(vaultBasePath, fileEmbed.originalPath); > + const relativeFilePath = path.relative(vaultBasePath, fileEmbed.originalPath).split(path.sep).join('/'); > ``` > > > Also applies to: 430-433, 256-273, 78-86, 91-99 > > </blockquote></details> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (21)</summary><blockquote> <details> <summary>CHANGELOG.md (1)</summary><blockquote> `8-28`: **Changelog date/order inconsistency** 1.3.0 is dated 2024-12-25 but appears above 1.2.1 dated 2025-01-10. Adjust dates or ordering to keep newest at top and dates ascending chronologically. </blockquote></details> <details> <summary>src/core/PathUtils.ts (1)</summary><blockquote> `25-27`: **Type safety: PluginManifest doesn’t declare 'dir'** Accessing manifest.dir will fail under strict TS. Use a narrowed type or index access. Apply this diff: ```diff - getPluginDir(pluginManifest: PluginManifest): string { - return normalizePath(pluginManifest.dir || ''); - } + getPluginDir(pluginManifest: PluginManifest): string { + const anyManifest = pluginManifest as unknown as { dir?: string }; + return normalizePath(anyManifest.dir ?? ''); + } ``` </blockquote></details> <details> <summary>src/converters/pdf/BinaryLocator.ts (2)</summary><blockquote> `87-96`: **Derive plugin directory robustly via PathUtils.getPluginDir with safe fallbacks** Using manifest.dir directly can be inconsistent. Prefer PathUtils.getPluginDir, and fall back to configDir/plugins/{manifest.id}. Apply this diff: ```diff - private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] { - return [ + private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] { + const dirs: string[] = [ // 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!)] : []) - ]; + ]; + if (plugin) { + const pu = new PathUtils(plugin.app); + const manifestDir = pu.getPluginDir(plugin.manifest); + if (manifestDir) { + // If manifest.dir is vault-relative (common), make absolute + dirs.push(path.join(pu.getVaultPath(), manifestDir)); + } + // Fallback: configDir/plugins/{id} + dirs.push(path.join(pu.getVaultPath(), plugin.app.vault.configDir, 'plugins', plugin.manifest.id)); + } + return dirs; } ``` --- `36-50`: **Graceful fallback when plugin is undefined** The existence check is skipped if plugin?.app is falsy, but you still proceed with a default path. Either allow fs-based checks here or require plugin explicitly. Apply this diff: ```diff - for (const dir of possiblePluginDirs) { + for (const dir of possiblePluginDirs) { try { const nodeModulesPath = path.join(dir, 'node_modules'); - if (plugin?.app) { - const pathUtils = new PathUtils(plugin.app); - if (await pathUtils.fileExists(nodeModulesPath)) { - pluginDir = dir; - break; - } - } + if (plugin?.app) { + const pathUtils = new PathUtils(plugin.app); + if (await pathUtils.fileExists(nodeModulesPath)) { + pluginDir = dir; + break; + } + } else { + const fs = require('fs').promises as typeof import('fs').promises; + await fs.access(nodeModulesPath); + pluginDir = dir; + break; + } } catch { continue; } } ``` </blockquote></details> <details> <summary>src/plugin/FontManager.ts (1)</summary><blockquote> `70-75`: **DRY: factor cache path building into a private helper.** Avoid repeating path assembly. Example (outside selected ranges): ```ts private getFontsCacheVaultPath(): string { const pathUtils = new PathUtils(this.plugin.app); return pathUtils.joinPath(pathUtils.getPluginDir(this.plugin.manifest), 'fonts-cache.json'); } ``` Then replace local constructions with `this.getFontsCacheVaultPath()`. Also applies to: 92-97, 106-111 </blockquote></details> <details> <summary>src/plugin/PathResolver.ts (1)</summary><blockquote> `28-40`: **Use ‘where’ on Windows; ‘which’ isn’t available there.** Current approach silently falls back, degrading UX on Windows. ```diff - const { spawnSync } = require('child_process'); + const { spawnSync } = require('child_process'); try { const augmentedEnv = { ...process.env, PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}` }; - - const result = spawnSync('which', [defaultName], { + const whichCmd = process.platform === 'win32' ? 'where' : 'which'; + const result = spawnSync(whichCmd, [defaultName], { encoding: 'utf8', env: augmentedEnv }); ``` </blockquote></details> <details> <summary>src/templates/TemplateManager.ts (1)</summary><blockquote> `19-23`: **Optional: keep both absolute and vault-relative template paths.** Store absolute for external consumers, and vault-relative for adapter calls. Example: ```ts private templatesPathAbs: string; private templatesPathRel: string; this.templatesPathRel = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'templates'); this.templatesPathAbs = this.pathUtils.joinPath(this.pathUtils.getVaultPath(), this.templatesPathRel); ``` </blockquote></details> <details> <summary>src/converters/PandocTypstConverter.ts (1)</summary><blockquote> `105-110`: **Prefer vault-relative paths for adapter.write.** Avoid writing with absolute `tempInputPath`. Convert to vault-relative before `write`. ```diff - 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); + const pathUtils = new PathUtils(this.plugin.app); + const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`); + const vaultBase = pathUtils.getVaultPath(); + const relTempInputPath = tempInputPath.startsWith(vaultBase) + ? tempInputPath.substring(vaultBase.length + (tempInputPath[vaultBase.length] === '/' ? 1 : 0)) + : tempInputPath; + await this.plugin.app.vault.adapter.write(relTempInputPath, content); ``` </blockquote></details> <details> <summary>src/plugin/EmbedProcessor.ts (2)</summary><blockquote> `455-460`: **Escape quotes in Typst strings to avoid syntax errors.** File names/descriptions with `"` will break `pdf.embed`. ```diff - const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; + const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; + const safeDescription = description.replace(/"/g, '\\"'); + const safePdfPath = relativePdfPath.split(path.sep).join('/').replace(/"/g, '\\"'); ... - content.push(`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`); + content.push(`#pdf.embed("${safePdfPath}", description: "${safeDescription}", mime-type: "application/pdf")`); ``` ```diff - const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; + const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; + const safeDescription = description.replace(/"/g, '\\"'); + const safeFilePath = relativeFilePath.split(path.sep).join('/').replace(/"/g, '\\"'); ... - content.push(`#pdf.embed("${relativeFilePath}", description: "${description}", mime-type: "${mimeType}")`); + content.push(`#pdf.embed("${safeFilePath}", description: "${safeDescription}", mime-type: "${mimeType}")`); ``` Also applies to: 481-486 --- `426-428`: **Read via vault-relative source path when using adapter.readBinary.** Safer and adapter-portable. ```diff - const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath); + const relativeSource = path.relative(vaultBasePath, imagePath).split(path.sep).join('/'); + const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSource); ``` </blockquote></details> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (5)</summary><blockquote> `9-17`: **Constructor/plugin wiring is fine, but consider making plugin required.** Avoid silent no-op code paths; this class isn’t useful without a plugin. --- `25-27`: **Avoid silent empty result when plugin/app is missing.** Log a warning to aid diagnostics instead of returning [] silently. Apply this diff: ```diff - if (!vaultBasePath || !this.plugin?.app) { - return []; - } + if (!vaultBasePath || !this.plugin?.app) { + console.warn('ResourcePathResolver: missing vaultBasePath or plugin.app; returning no resource paths.'); + return []; + } ``` --- `54-55`: **Deduplicate resource paths before returning.** Prevents repeated directories (e.g., overlap between common and scanned paths). Apply this diff: ```diff - return resourcePaths; + return Array.from(new Set(resourcePaths)); ``` --- `63-71`: **Include user-configured attachment folder.** Respect Obsidian’s “Default location for new attachments” when set. Apply this diff: ```diff - private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] { - return [ - pathUtils.joinPath(vaultBasePath, 'attachments'), - pathUtils.joinPath(vaultBasePath, 'assets'), - pathUtils.joinPath(vaultBasePath, 'files'), - pathUtils.joinPath(vaultBasePath, 'images'), - pathUtils.joinPath(vaultBasePath, '.attachments') - ]; - } + private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] { + const paths = [ + pathUtils.joinPath(vaultBasePath, 'attachments'), + pathUtils.joinPath(vaultBasePath, 'assets'), + pathUtils.joinPath(vaultBasePath, 'files'), + pathUtils.joinPath(vaultBasePath, 'images'), + pathUtils.joinPath(vaultBasePath, '.attachments'), + ]; + // Obsidian setting: Default location for new attachments (if set to a fixed folder) + const userAttach = this.plugin?.app?.vault?.getConfig?.('attachmentFolderPath'); + if (typeof userAttach === 'string' && userAttach.trim()) { + paths.push(pathUtils.joinPath(vaultBasePath, userAttach)); + } + return paths; + } ``` --- `108-110`: **Broaden detection to include PDFs and common document types (optional).** Embeds often include PDFs and office docs; include them in scan. Apply this diff: ```diff - const hasImages = dirContents.files.some((file: string) => - /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) - ); + const hasImages = dirContents.files.some((file: string) => + /\.(png|jpe?g|gif|svg|webp|bmp|ico|tiff?|pdf|docx?|xlsx?|pptx?|odt|ods|odp)$/i.test(file) + ); ``` </blockquote></details> <details> <summary>src/plugin/PluginLifecycle.ts (1)</summary><blockquote> `72-81`: **Consider awaiting the cleanup or documenting the fire-and-forget nature.** The async IIFE pattern is used here without awaiting the result, which means cleanup happens asynchronously during unload. This could potentially leave temp files if the plugin unloads quickly. Consider either: 1. Making the cleanup() method async and awaiting this operation 2. Adding a comment explaining why fire-and-forget is acceptable here ```diff /** * Clean up resources during onunload + * Note: Temp directory cleanup is fire-and-forget to avoid blocking plugin unload */ cleanup(): void { ``` </blockquote></details> <details> <summary>src/templates/embeddedTemplates.ts (1)</summary><blockquote> `102-125`: **Consider parallel extraction for better performance.** The templates are extracted sequentially in the loop. Since template extractions are independent operations, consider using `Promise.all()` for parallel processing to improve performance. ```diff - for (const templateName of embeddedNames) { - try { - const filePath = this.pathUtils.joinPath(this.templatesDir, templateName); - const content = extractTemplate(templateName, filePath); - - await this.app.vault.adapter.write(filePath, content); - extracted.push(templateName); - } catch (error) { - console.error(`Failed to force extract template ${templateName}:`, error); - failed.push(templateName); - } - } + const extractionPromises = embeddedNames.map(async (templateName) => { + try { + const filePath = this.pathUtils.joinPath(this.templatesDir, templateName); + const content = extractTemplate(templateName, filePath); + await this.app.vault.adapter.write(filePath, content); + return { name: templateName, success: true }; + } catch (error) { + console.error(`Failed to force extract template ${templateName}:`, error); + return { name: templateName, success: false }; + } + }); + + const results = await Promise.all(extractionPromises); + for (const result of results) { + if (result.success) { + extracted.push(result.name); + } else { + failed.push(result.name); + } + } ``` </blockquote></details> <details> <summary>src/converters/pdf/ImageOptimizer.ts (1)</summary><blockquote> `234-242`: **Consider extracting duplicated file operation logic.** The pattern of reading binary, writing to new location, and removing the original is repeated multiple times (lines 235-237, 247-249). Consider extracting this into a helper method. ```diff + private static async moveFile( + sourcePath: string, + destPath: string, + plugin?: obsidianTypstPDFExport + ): Promise<void> { + if (plugin?.app) { + const content = await plugin.app.vault.adapter.readBinary(sourcePath); + await plugin.app.vault.adapter.writeBinary(destPath, content); + await plugin.app.vault.adapter.remove(sourcePath); + } else { + const fs = require('fs').promises; + await fs.rename(sourcePath, destPath); + } + } // Then use it in multiple places: - 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); - } + await this.moveFile(inputImagePath, pngFinalPath, plugin); ``` </blockquote></details> <details> <summary>src/core/TempDirectoryManager.ts (3)</summary><blockquote> `1-2`: **Fix typo in ABOUTME comment.** Minor typo: "ABOUTME" should likely be "ABOUT" or removed entirely as it's non-standard. ```diff -// ABOUTME: Manages temporary directories for export operations -// ABOUTME: Uses normalizePath for cross-platform path operations +// Manages temporary directories for export operations +// Uses normalizePath for cross-platform path operations ``` --- `35-37`: **Consider using PathUtils.joinPath for consistency.** Since PathUtils is available in the codebase and provides a `joinPath` method that handles normalization, consider using it here for consistency with other modules. ```diff - return normalizePath([this.vaultPath, this.configDir, 'plugins', this.pluginName].join('/')); + const pathUtils = new PathUtils(this.app); + return pathUtils.joinPath(this.vaultPath, this.configDir, 'plugins', this.pluginName); ``` --- `86-91`: **Consider using Promise.allSettled for independent operations.** Since cleaning up images and pandoc directories are independent operations, using `Promise.allSettled` would ensure both attempts are made even if one fails early. ```diff public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> { - return { - images: await this.cleanupTempDir('images'), - pandoc: await this.cleanupTempDir('pandoc') - }; + const [imagesResult, pandocResult] = await Promise.allSettled([ + this.cleanupTempDir('images'), + this.cleanupTempDir('pandoc') + ]); + return { + images: imagesResult.status === 'fulfilled' && imagesResult.value, + pandoc: pandocResult.status === 'fulfilled' && pandocResult.value + }; } ``` </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e320238a79af579a617c50d86fe0e9ee798d19e4 and c971c920ce9d7e4536c1bb21af081d2c64576d0e. </details> <details> <summary>📒 Files selected for processing (19)</summary> * `CHANGELOG.md` (1 hunks) * `manifest.json` (1 hunks) * `package.json` (1 hunks) * `src/converters/PandocTypstConverter.ts` (5 hunks) * `src/converters/PdfToImageConverter.ts` (4 hunks) * `src/converters/pandoc/PandocCommandBuilder.ts` (3 hunks) * `src/converters/pandoc/ResourcePathResolver.ts` (4 hunks) * `src/converters/pdf/BinaryLocator.ts` (3 hunks) * `src/converters/pdf/FileDiscovery.ts` (2 hunks) * `src/converters/pdf/ImageOptimizer.ts` (5 hunks) * `src/core/PathUtils.ts` (1 hunks) * `src/core/TempDirectoryManager.ts` (2 hunks) * `src/plugin/EmbedProcessor.ts` (8 hunks) * `src/plugin/ExportOrchestrator.ts` (3 hunks) * `src/plugin/FontManager.ts` (4 hunks) * `src/plugin/PathResolver.ts` (2 hunks) * `src/plugin/PluginLifecycle.ts` (3 hunks) * `src/templates/TemplateManager.ts` (4 hunks) * `src/templates/embeddedTemplates.ts` (5 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🧬 Code graph analysis (15)</summary> <details> <summary>src/plugin/ExportOrchestrator.ts (3)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary> * `TempDirectoryManager` (19-109) </details> </blockquote></details> <details> <summary>src/converters/PdfToImageConverter.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>src/converters/pdf/FileDiscovery.ts (1)</summary> * `FileDiscovery` (19-256) </details> </blockquote></details> <details> <summary>src/templates/TemplateManager.ts (1)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary><blockquote> <details> <summary>src/core/constants.ts (1)</summary> * `PLUGIN_DIRS` (25-29) </details> </blockquote></details> <details> <summary>src/plugin/EmbedProcessor.ts (1)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/PandocTypstConverter.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary> * `TempDirectoryManager` (19-109) </details> </blockquote></details> <details> <summary>src/plugin/FontManager.ts (1)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/templates/embeddedTemplates.ts (1)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/pandoc/PandocCommandBuilder.ts (2)</summary><blockquote> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (1)</summary> * `ResourcePathResolver` (8-139) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/pdf/ImageOptimizer.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/plugin/PathResolver.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/pdf/BinaryLocator.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> </blockquote></details> <details> <summary>src/plugin/PluginLifecycle.ts (3)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>src/templates/embeddedTemplates.ts (1)</summary> * `EmbeddedTemplateManager` (14-141) </details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary> * `TempDirectoryManager` (19-109) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (19)</summary><blockquote> <details> <summary>package.json (1)</summary><blockquote> `3-3`: **Version bump looks good** Version updated to 1.3.0; consistent with the rest of the PR. </blockquote></details> <details> <summary>src/plugin/ExportOrchestrator.ts (1)</summary><blockquote> `139-141`: **Guard against absolute pluginDir returned by manifest.** If `manifest.dir` is absolute, prepending `vaultPath` will duplicate the vault segment. Suggested pattern: ```diff - const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest)); + const manifestDir = this.pathUtils.getPluginDir(this.plugin.manifest); + const pluginDir = manifestDir.startsWith(vaultPath) + ? manifestDir + : this.pathUtils.joinPath(vaultPath, manifestDir); ``` Please confirm what `plugin.manifest.dir` returns at runtime (absolute vs vault-relative). If absolute, the above is required. If vault-relative, current code is fine. </blockquote></details> <details> <summary>src/converters/PandocTypstConverter.ts (1)</summary><blockquote> `164-166`: **Cleanup: ensure adapter operations target vault-relative paths.** `cleanupDir` handles this internally, but if other adapter operations are added, prefer vault-relative paths for consistency. </blockquote></details> <details> <summary>src/converters/PdfToImageConverter.ts (2)</summary><blockquote> `96-99`: **Ensure output dir via PathUtils across both code paths.** Looks good when plugin/app exists. If running without plugin (fallback), ensure the CLI creates the directory or add an fs fallback. --- `126-136`: **Nice: plugin-aware discovery and optimization wiring.** Passing `plugin` into FileDiscovery and ImageOptimizer aligns with the new PathUtils/vault adapter design. Also applies to: 139-148 </blockquote></details> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (2)</summary><blockquote> `1-2`: **Imports look good.** --- `79-83`: **Cache validation logic LGTM.** Time‑based and vault‑path scoped. </blockquote></details> <details> <summary>src/plugin/PluginLifecycle.ts (3)</summary><blockquote> `14-19`: **LGTM! Clean dependency injection pattern.** The addition of PathUtils as a class member and its initialization in the constructor follows good object-oriented design practices. --- `87-102`: **LGTM! Consistent async cleanup pattern.** The fire-and-forget pattern is consistently applied here for startup cleanup, with appropriate error handling that doesn't block plugin initialization. --- `29-31`: **Ignore path composition concern.** `getPluginDir` returns the plugin’s directory relative to the vault root (from `manifest.dir`), so `joinPath(vaultPath, pluginDir)` correctly yields the absolute plugin path. > Likely an incorrect or invalid review comment. </blockquote></details> <details> <summary>src/templates/embeddedTemplates.ts (4)</summary><blockquote> `14-25`: **LGTM! Clean constructor update with App dependency.** The constructor signature change to accept the App instance enables proper integration with Obsidian's vault adapter API. --- `51-74`: **LGTM! Proper async conversion with vault adapter usage.** The method correctly uses PathUtils for path operations and the vault adapter for file writing, maintaining consistency with Obsidian's API. --- `79-97`: **LGTM! Clean async iteration pattern.** The method properly awaits each template extraction in sequence, collecting results appropriately. --- `30-46`: **No additional error handling needed for `fileExists` calls.** PathUtils.fileExists catches all internal errors and always resolves to a boolean, so `getTemplateInfo` can safely rely on its result. </blockquote></details> <details> <summary>src/converters/pdf/ImageOptimizer.ts (2)</summary><blockquote> `183-189`: **LGTM! Good optional parameter addition.** The optional `plugin` parameter maintains backward compatibility while enabling vault-aware operations when available. --- `197-205`: **LGTM! Proper conditional path handling.** The code correctly uses PathUtils when a plugin is available, falling back to Node.js path.join otherwise. </blockquote></details> <details> <summary>src/core/TempDirectoryManager.ts (3)</summary><blockquote> `15-17`: **LGTM! Clean App integration.** The addition of the App instance to the options enables proper vault adapter usage throughout the class. --- `50-59`: **LGTM! Proper async conversion.** The method correctly uses async/await with vault adapter for directory operations. --- `64-81`: **LGTM! Consistent error handling.** The cleanup method properly handles errors and returns a boolean status, maintaining the expected API contract. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@@ -5,3 +4,4 @@
"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] (Migrated from github.com) commented 2025-09-25 13:05:39 +02:00

⚠️ 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 -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:39 +02:00

⚠️ Potential issue | 🔴 Critical

Don’t pre-quote args when using spawn; remove the extra quotes.

Passing "${templatesDir}" as a separate argv includes quotes literally, breaking path resolution with spaces.

-      const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates');
-      // Quote the path to handle spaces and special characters
-      args.push('--resource-path', `"${templatesDir}"`);
+      const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates');
+      args.push('--resource-path', templatesDir);
📝 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 templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates');
			args.push('--resource-path', templatesDir);
🤖 Prompt for AI Agents
In src/converters/pandoc/PandocCommandBuilder.ts around lines 111 to 114, the
code currently pushes a quoted templatesDir string into the args array which
embeds literal quotes and breaks path resolution for spawn; remove the extra
wrapping quotes and push the raw templatesDir value instead (i.e.,
args.push('--resource-path', templatesDir)) so spawn receives an unquoted
argument and can handle spaces/special characters correctly.

✅ Addressed in commits 3782f0a to d20e8cf

_⚠️ Potential issue_ | _🔴 Critical_ **Don’t pre-quote args when using spawn; remove the extra quotes.** Passing `"${templatesDir}"` as a separate argv includes quotes literally, breaking path resolution with spaces. ```diff - const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates'); - // Quote the path to handle spaces and special characters - args.push('--resource-path', `"${templatesDir}"`); + const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates'); + args.push('--resource-path', templatesDir); ``` <!-- 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 templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates'); args.push('--resource-path', templatesDir); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pandoc/PandocCommandBuilder.ts around lines 111 to 114, the code currently pushes a quoted templatesDir string into the args array which embeds literal quotes and breaks path resolution for spawn; remove the extra wrapping quotes and push the raw templatesDir value instead (i.e., args.push('--resource-path', templatesDir)) so spawn receives an unquoted argument and can handle spaces/special characters correctly. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 3782f0a to d20e8cf
@@ -79,36 +85,34 @@ export class ResourcePathResolver {
/**
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:39 +02:00

⚠️ 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
@@ -30,34 +32,28 @@ export class BinaryLocator {
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
const configDir = plugin?.app.vault.configDir || '.obsidian';
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:39 +02:00

⚠️ 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
@@ -18,2 +19,4 @@
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] (Migrated from github.com) commented 2025-09-25 13:05:39 +02:00

⚠️ 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
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify path consistency for vault.adapter operations.

When using vault.adapter.remove(), ensure that inputImagePath is in the correct format (vault-relative or absolute) that the adapter expects.


🏁 Script executed:

#!/bin/bash
# Check how inputImagePath is constructed and passed to this method
rg -A5 -B5 'optimizeImage\(' --type ts

Length of output: 1435


🏁 Script executed:

#!/bin/bash
# Show context around the optimizeImage call
rg -n 'optimizeImage' -C5 --type ts src/converters/PdfToImageConverter.ts

# Show where fileDiscovery is defined or used
rg -n 'fileDiscovery' -C5 --type ts src/converters/PdfToImageConverter.ts

# Show definition of outputDir
rg -n 'outputDir' -C5 --type ts src/converters/PdfToImageConverter.ts

Length of output: 2944


🏁 Script executed:

#!/bin/bash
# Find PathUtils definition
rg -n 'class PathUtils' -C5 --type ts

# Show ensureDir implementation
rg -n 'ensureDir' -C5 --type ts

Length of output: 6939


🏁 Script executed:

#!/bin/bash
# Locate FileDiscovery class and its findGeneratedFile method
rg -n 'class FileDiscovery' -C5 --type ts
rg -n 'findGeneratedFile' -C5 --type ts

Length of output: 2472


🏁 Script executed:

#!/bin/bash
# Show getVaultPath and joinPath implementations in PathUtils
rg -n 'getVaultPath' -C5 --type ts src/core/PathUtils.ts
rg -n 'joinPath' -C5 --type ts src/core/PathUtils.ts

Length of output: 1126


🏁 Script executed:

#!/bin/bash
# Show full implementation of findGeneratedFile
rg -n 'public static async findGeneratedFile' -C100 src/converters/pdf/FileDiscovery.ts

Length of output: 4576


🏁 Script executed:

#!/bin/bash
# Show full optimizeImage implementation to inspect inputImagePath handling
rg -n 'public static async optimizeImage' -C200 src/converters/pdf/ImageOptimizer.ts

Length of output: 9024


🏁 Script executed:

#!/bin/bash
# Show full getVaultPath implementation in PathUtils
rg -n 'getVaultPath' -C20 --type ts src/core/PathUtils.ts

Length of output: 2456


Normalize vault paths before adapter.remove()
In ImageOptimizer.optimizeImage (around the PNG‐cleanup at lines 219–226), strip the vault base path so you pass a vault-relative path into vault.adapter.remove(). For example:

const pathUtils = new PathUtils(plugin.app);
const vaultBase = pathUtils.getVaultPath();
const relativePath = inputImagePath.startsWith(vaultBase)
  ? inputImagePath.slice(vaultBase.length + 1)
  : inputImagePath;
await plugin.app.vault.adapter.remove(relativePath);

This ensures the adapter receives the correct path format.

🤖 Prompt for AI Agents
In src/converters/pdf/ImageOptimizer.ts around lines 220 to 226, the call to
plugin.app.vault.adapter.remove(inputImagePath) may be given an absolute
filesystem path instead of a vault-relative path; normalize by getting the vault
base path via PathUtils(plugin.app).getVaultPath(), detect if inputImagePath
starts with that base and if so strip the base (and leading separator) to
produce a vault-relative path, then pass that relativePath into
plugin.app.vault.adapter.remove(relativePath); keep the existing fallback to
fs.unlink when plugin.app is not present.

✅ Addressed in commits a129380 to 731a76e

_⚠️ Potential issue_ | _🔴 Critical_ <details> <summary>🧩 Analysis chain</summary> **Verify path consistency for vault.adapter operations.** When using `vault.adapter.remove()`, ensure that `inputImagePath` is in the correct format (vault-relative or absolute) that the adapter expects. --- 🏁 Script executed: ```shell #!/bin/bash # Check how inputImagePath is constructed and passed to this method rg -A5 -B5 'optimizeImage\(' --type ts ``` Length of output: 1435 --- 🏁 Script executed: ```shell #!/bin/bash # Show context around the optimizeImage call rg -n 'optimizeImage' -C5 --type ts src/converters/PdfToImageConverter.ts # Show where fileDiscovery is defined or used rg -n 'fileDiscovery' -C5 --type ts src/converters/PdfToImageConverter.ts # Show definition of outputDir rg -n 'outputDir' -C5 --type ts src/converters/PdfToImageConverter.ts ``` Length of output: 2944 --- 🏁 Script executed: ```shell #!/bin/bash # Find PathUtils definition rg -n 'class PathUtils' -C5 --type ts # Show ensureDir implementation rg -n 'ensureDir' -C5 --type ts ``` Length of output: 6939 --- 🏁 Script executed: ```shell #!/bin/bash # Locate FileDiscovery class and its findGeneratedFile method rg -n 'class FileDiscovery' -C5 --type ts rg -n 'findGeneratedFile' -C5 --type ts ``` Length of output: 2472 --- 🏁 Script executed: ```shell #!/bin/bash # Show getVaultPath and joinPath implementations in PathUtils rg -n 'getVaultPath' -C5 --type ts src/core/PathUtils.ts rg -n 'joinPath' -C5 --type ts src/core/PathUtils.ts ``` Length of output: 1126 --- 🏁 Script executed: ```shell #!/bin/bash # Show full implementation of findGeneratedFile rg -n 'public static async findGeneratedFile' -C100 src/converters/pdf/FileDiscovery.ts ``` Length of output: 4576 --- 🏁 Script executed: ```shell #!/bin/bash # Show full optimizeImage implementation to inspect inputImagePath handling rg -n 'public static async optimizeImage' -C200 src/converters/pdf/ImageOptimizer.ts ``` Length of output: 9024 --- 🏁 Script executed: ```shell #!/bin/bash # Show full getVaultPath implementation in PathUtils rg -n 'getVaultPath' -C20 --type ts src/core/PathUtils.ts ``` Length of output: 2456 --- </details> **Normalize vault paths before adapter.remove()** In ImageOptimizer.optimizeImage (around the PNG‐cleanup at lines 219–226), strip the vault base path so you pass a vault-relative path into vault.adapter.remove(). For example: ```ts const pathUtils = new PathUtils(plugin.app); const vaultBase = pathUtils.getVaultPath(); const relativePath = inputImagePath.startsWith(vaultBase) ? inputImagePath.slice(vaultBase.length + 1) : inputImagePath; await plugin.app.vault.adapter.remove(relativePath); ``` This ensures the adapter receives the correct path format. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/ImageOptimizer.ts around lines 220 to 226, the call to plugin.app.vault.adapter.remove(inputImagePath) may be given an absolute filesystem path instead of a vault-relative path; normalize by getting the vault base path via PathUtils(plugin.app).getVaultPath(), detect if inputImagePath starts with that base and if so strip the base (and leading separator) to produce a vault-relative path, then pass that relativePath into plugin.app.vault.adapter.remove(relativePath); keep the existing fallback to fs.unlink when plugin.app is not present. ``` </details> <!-- fingerprinting:phantom:medusa:armadillo --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 731a76e
@@ -0,0 +1,125 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ 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 -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ Potential issue | 🟡 Minor

Potential security issue: Path traversal vulnerability.

The current implementation uses simple string operations (startsWith and includes) for path validation, which could be vulnerable to path traversal attacks. Consider using normalized path comparison instead.

  public isPluginTempDir(dirPath: string): boolean {
    const pluginDir = this.getPluginDir();
-    // Simple string comparison for temp directory validation
-    return dirPath.startsWith(pluginDir) &&
-           (dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC));
+    const normalizedDirPath = normalizePath(dirPath);
+    const normalizedPluginDir = normalizePath(pluginDir);
+    const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/'));
+    const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/'));
+    
+    return normalizedDirPath.startsWith(tempImagesDir) || 
+           normalizedDirPath.startsWith(tempPandocDir);
  }

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

✅ Addressed in commits a129380 to 731a76e

_⚠️ Potential issue_ | _🟡 Minor_ **Potential security issue: Path traversal vulnerability.** The current implementation uses simple string operations (`startsWith` and `includes`) for path validation, which could be vulnerable to path traversal attacks. Consider using normalized path comparison instead. ```diff public isPluginTempDir(dirPath: string): boolean { const pluginDir = this.getPluginDir(); - // Simple string comparison for temp directory validation - return dirPath.startsWith(pluginDir) && - (dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC)); + const normalizedDirPath = normalizePath(dirPath); + const normalizedPluginDir = normalizePath(pluginDir); + const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/')); + const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/')); + + return normalizedDirPath.startsWith(tempImagesDir) || + normalizedDirPath.startsWith(tempPandocDir); } ``` > Committable suggestion skipped: line range outside the PR's diff. <!-- fingerprinting:phantom:medusa:armadillo --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 731a76e
@@ -132,16 +136,21 @@ export class ExportOrchestrator {
* Export a file with specific configuration
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ 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
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ Potential issue | 🟠 Major

Ensure cleanup targets the correct temp directories.

Also provide pluginName to create(...) for consistent cleanup.

-        const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
+        const cleanupManager = TempDirectoryManager.create(
+          vaultPath,
+          this.plugin.app.vault.configDir,
+          this.plugin.manifest.id,
+          this.plugin.app
+        );
         await cleanupManager.cleanupAllTempDirs();
📝 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 cleanupManager = TempDirectoryManager.create(
                  vaultPath,
                  this.plugin.app.vault.configDir,
                  this.plugin.manifest.id,
                  this.plugin.app
                );
                await cleanupManager.cleanupAllTempDirs();
🤖 Prompt for AI Agents
In src/plugin/ExportOrchestrator.ts around lines 252 to 254, the
TempDirectoryManager.create call must target the correct plugin-specific temp
directories and include the pluginName for consistent cleanup; update the call
to pass the plugin's name (e.g. this.plugin.manifest.name or this.pluginName) as
the third argument instead of undefined so it becomes
TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir,
<pluginName>, this.plugin.app), then keep awaiting
cleanupManager.cleanupAllTempDirs() to remove only that plugin's temp dirs.

✅ Addressed in commits a129380 to 21ed9e1

_⚠️ Potential issue_ | _🟠 Major_ **Ensure cleanup targets the correct temp directories.** Also provide `pluginName` to `create(...)` for consistent cleanup. ```diff - const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app); + const cleanupManager = TempDirectoryManager.create( + vaultPath, + this.plugin.app.vault.configDir, + this.plugin.manifest.id, + this.plugin.app + ); await cleanupManager.cleanupAllTempDirs(); ``` <!-- 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 cleanupManager = TempDirectoryManager.create( vaultPath, this.plugin.app.vault.configDir, this.plugin.manifest.id, this.plugin.app ); await cleanupManager.cleanupAllTempDirs(); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/ExportOrchestrator.ts around lines 252 to 254, the TempDirectoryManager.create call must target the correct plugin-specific temp directories and include the pluginName for consistent cleanup; update the call to pass the plugin's name (e.g. this.plugin.manifest.name or this.pluginName) as the third argument instead of undefined so it becomes TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, <pluginName>, this.plugin.app), then keep awaiting cleanupManager.cleanupAllTempDirs() to remove only that plugin's temp dirs. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 21ed9e1
@@ -90,1 +100,4 @@
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] (Migrated from github.com) commented 2025-09-25 13:05:41 +02:00

⚠️ 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
@@ -100,1 +113,3 @@
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] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ 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
@@ -119,1 +160,3 @@
this.cacheAvailableFonts().catch(cacheError => {
console.error('Failed to recreate fonts cache:', cacheError);
});
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:40 +02:00

⚠️ 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
@@ -27,24 +29,36 @@ export class TemplateManager {
async getAvailableTemplates(): Promise<string[]> {
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 13:05:41 +02:00

⚠️ 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
AlexKucera commented 2025-09-25 13:53:04 +02:00 (Migrated from github.com)

Applied fixes locally.

Applied fixes locally.
AlexKucera (Migrated from github.com) reviewed 2025-09-25 15:29:10 +02:00
@@ -5,3 +4,4 @@
"version": "1.3.0",
"minAppVersion": "1.9.12",
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
"author": "Alexander Kucera",
AlexKucera (Migrated from github.com) commented 2025-09-25 15:29:10 +02:00

@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] (Migrated from github.com) reviewed 2025-09-25 15:30:10 +02:00
@@ -5,3 +4,4 @@
"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] (Migrated from github.com) commented 2025-09-25 15:30:10 +02:00

@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 -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-09-25 15:58:09 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/converters/pandoc/PandocCommandBuilder.ts (2)

67-70: Avoid process.chdir in a shared plugin runtime.

Changing CWD can affect other operations/threads; rely on absolute paths and --resource-path instead.

Apply:

-		// Set working directory for relative paths
-		if (pandocOptions.vaultBasePath) {
-			process.chdir(pandocOptions.vaultBasePath);
-		}
+		// Avoid changing process CWD; rely on absolute paths and --resource-path entries.

118-124: Normalize template_path to POSIX separators for Typst import.

path.relative on Windows yields backslashes; normalize to forward slashes to avoid import failures.

Apply:

-			if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) {
-				// Make template path relative to vault for Typst import
-				templatePathForTypst = path.relative(pandocOptions.vaultBasePath, templatePathForTypst);
-			}
+			if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) {
+				// Make template path relative to vault for Typst import and normalize to POSIX separators
+				templatePathForTypst = normalizePath(
+					path.relative(pandocOptions.vaultBasePath, templatePathForTypst)
+				);
+			}

Add import:

import { normalizePath } from 'obsidian';
🧹 Nitpick comments (3)
plan-coderabbit.md (1)

1-232: Add language identifiers to all fenced code blocks (markdownlint MD040).

One or more fenced blocks lack a language hint. Use ts/typescript, diff, or sh for proper highlighting and lint compliance.

If helpful, I can run markdownlint locally or open a quick fix PR.

src/converters/pandoc/PandocCommandBuilder.ts (2)

43-45: Prefer separate args over --pdf-engine=.

Avoid potential parsing/quoting edge cases with spaces in paths.

Apply:

-		args.push(`--pdf-engine=${typstPath}`);
+		args.push('--pdf-engine', typstPath);

78-90: Deduplicate resource-path entries.

Minor optimization; avoids redundant search paths.

Apply:

-		for (const resourcePath of resourcePaths) {
+		for (const resourcePath of new Set(resourcePaths)) {
 			args.push('--resource-path', resourcePath);
 		}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c971c920ce and d20e8cf0ae.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • plan-coderabbit.md (1 hunks)
  • src/converters/pandoc/PandocCommandBuilder.ts (3 hunks)
  • src/converters/pandoc/ResourcePathResolver.ts (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • README.md
🧰 Additional context used
🧬 Code graph analysis (2)
src/converters/pandoc/PandocCommandBuilder.ts (2)
src/converters/pandoc/ResourcePathResolver.ts (1)
  • ResourcePathResolver (8-142)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pandoc/ResourcePathResolver.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
🪛 markdownlint-cli2 (0.18.1)
plan-coderabbit.md

7-7: Images should have alternate text (alt text)

(MD045, no-alt-text)


80-80: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (5)
src/converters/pandoc/PandocCommandBuilder.ts (2)

23-24: Good: ResourcePathResolver now receives plugin context.

This aligns with vault-adapter usage downstream.


99-114: Good: PathUtils join + existence checks; quotes removed.

Wrapper/dir path building is consistent, and argv no longer embeds quotes.

src/converters/pandoc/ResourcePathResolver.ts (3)

25-31: Early exit guard looks correct.

Safe handling when app/vaultBasePath are unavailable.


63-71: Good: Common attachment dirs resolved via PathUtils.

Vault-aware, absolute paths for external tools.


100-116: Correct: adapter.list uses vault-relative (''); returns absolute paths.

Fix aligns with Obsidian adapter contract; avoids cwd reliance.

**Actionable comments posted: 1** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to platform limitations. > > > > <details> > <summary>⚠️ Outside diff range comments (2)</summary><blockquote> > > <details> > <summary>src/converters/pandoc/PandocCommandBuilder.ts (2)</summary><blockquote> > > `67-70`: **Avoid process.chdir in a shared plugin runtime.** > > Changing CWD can affect other operations/threads; rely on absolute paths and --resource-path instead. > > Apply: > > ```diff > - // Set working directory for relative paths > - if (pandocOptions.vaultBasePath) { > - process.chdir(pandocOptions.vaultBasePath); > - } > + // Avoid changing process CWD; rely on absolute paths and --resource-path entries. > ``` > > --- > > `118-124`: **Normalize template_path to POSIX separators for Typst import.** > > path.relative on Windows yields backslashes; normalize to forward slashes to avoid import failures. > > Apply: > > ```diff > - if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) { > - // Make template path relative to vault for Typst import > - templatePathForTypst = path.relative(pandocOptions.vaultBasePath, templatePathForTypst); > - } > + if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) { > + // Make template path relative to vault for Typst import and normalize to POSIX separators > + templatePathForTypst = normalizePath( > + path.relative(pandocOptions.vaultBasePath, templatePathForTypst) > + ); > + } > ``` > > Add import: > > ```ts > import { normalizePath } from 'obsidian'; > ``` > > </blockquote></details> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (3)</summary><blockquote> <details> <summary>plan-coderabbit.md (1)</summary><blockquote> `1-232`: **Add language identifiers to all fenced code blocks (markdownlint MD040).** One or more fenced blocks lack a language hint. Use ```ts/```typescript, ```diff, or ```sh for proper highlighting and lint compliance. If helpful, I can run markdownlint locally or open a quick fix PR. </blockquote></details> <details> <summary>src/converters/pandoc/PandocCommandBuilder.ts (2)</summary><blockquote> `43-45`: **Prefer separate args over --pdf-engine=<path>.** Avoid potential parsing/quoting edge cases with spaces in paths. Apply: ```diff - args.push(`--pdf-engine=${typstPath}`); + args.push('--pdf-engine', typstPath); ``` --- `78-90`: **Deduplicate resource-path entries.** Minor optimization; avoids redundant search paths. Apply: ```diff - for (const resourcePath of resourcePaths) { + for (const resourcePath of new Set(resourcePaths)) { args.push('--resource-path', resourcePath); } ``` </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between c971c920ce9d7e4536c1bb21af081d2c64576d0e and d20e8cf0aeb566cf4938cb197842ac5b58d81f4c. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `README.md` (1 hunks) * `plan-coderabbit.md` (1 hunks) * `src/converters/pandoc/PandocCommandBuilder.ts` (3 hunks) * `src/converters/pandoc/ResourcePathResolver.ts` (4 hunks) </details> <details> <summary>✅ Files skipped from review due to trivial changes (1)</summary> * README.md </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🧬 Code graph analysis (2)</summary> <details> <summary>src/converters/pandoc/PandocCommandBuilder.ts (2)</summary><blockquote> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (1)</summary> * `ResourcePathResolver` (8-142) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> </details><details> <summary>🪛 markdownlint-cli2 (0.18.1)</summary> <details> <summary>plan-coderabbit.md</summary> 7-7: Images should have alternate text (alt text) (MD045, no-alt-text) --- 80-80: Fenced code blocks should have a language specified (MD040, fenced-code-language) </details> </details> </details> <details> <summary>🔇 Additional comments (5)</summary><blockquote> <details> <summary>src/converters/pandoc/PandocCommandBuilder.ts (2)</summary><blockquote> `23-24`: **Good: ResourcePathResolver now receives plugin context.** This aligns with vault-adapter usage downstream. --- `99-114`: **Good: PathUtils join + existence checks; quotes removed.** Wrapper/dir path building is consistent, and argv no longer embeds quotes. </blockquote></details> <details> <summary>src/converters/pandoc/ResourcePathResolver.ts (3)</summary><blockquote> `25-31`: **Early exit guard looks correct.** Safe handling when app/vaultBasePath are unavailable. --- `63-71`: **Good: Common attachment dirs resolved via PathUtils.** Vault-aware, absolute paths for external tools. --- `100-116`: **Correct: adapter.list uses vault-relative (''); returns absolute paths.** Fix aligns with Obsidian adapter contract; avoids cwd reliance. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 15:58:09 +02:00

⚠️ Potential issue | 🟡 Minor

Include additional image extensions (at least .tif).

.tif is common and currently missed, which can omit valid resource directories.

Apply:

-						const hasImages = dirContents.files.some((file: string) =>
-							/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
-						);
+						const hasImages = dirContents.files.some((file: string) =>
+							/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff|tif|avif|heic|heif)$/i.test(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 hasImages = dirContents.files.some((file: string) =>
							/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff|tif|avif|heic|heif)$/i.test(file)
						);
🤖 Prompt for AI Agents
In src/converters/pandoc/ResourcePathResolver.ts around lines 109 to 111, the
image-extension regex omits the common .tif extension; update the regex to
include tif (e.g. add tif to the alternation alongside tiff) so files like *.tif
are matched as images, keeping the case-insensitive flag and existing extensions
intact.
_⚠️ Potential issue_ | _🟡 Minor_ **Include additional image extensions (at least .tif).** .tif is common and currently missed, which can omit valid resource directories. Apply: ```diff - const hasImages = dirContents.files.some((file: string) => - /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file) - ); + const hasImages = dirContents.files.some((file: string) => + /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff|tif|avif|heic|heif)$/i.test(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 hasImages = dirContents.files.some((file: string) => /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff|tif|avif|heic|heif)$/i.test(file) ); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pandoc/ResourcePathResolver.ts around lines 109 to 111, the image-extension regex omits the common .tif extension; update the regex to include tif (e.g. add tif to the alternation alongside tiff) so files like *.tif are matched as images, keeping the case-insensitive flag and existing extensions intact. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated reply by CodeRabbit -->
AlexKucera (Migrated from github.com) reviewed 2025-09-25 16:14:35 +02:00
AlexKucera (Migrated from github.com) commented 2025-09-25 16:14:35 +02:00

@coderabbitai We consciously restrict the allowed images. I reject this change.

@coderabbitai We consciously restrict the allowed images. I reject this change.
coderabbitai[bot] (Migrated from github.com) reviewed 2025-09-25 16:14:58 +02:00
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:14:58 +02:00

@AlexKucera Understood! I'll respect that design decision. The current image extension set is intentionally curated for your specific requirements.


✏️ Learnings added
Learnt from: AlexKucera
PR: AlexKucera/obsidian-typst-pdf-export#5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.394Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.

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 Understood! I'll respect that design decision. The current image extension set is intentionally curated for your specific requirements. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera PR: AlexKucera/obsidian-typst-pdf-export#5 File: src/converters/pandoc/ResourcePathResolver.ts:109-111 Timestamp: 2025-09-25T14:14:57.394Z Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer. ``` > 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 -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-09-25 16:21:16 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 4

🧹 Nitpick comments (5)
src/converters/pdf/BinaryLocator.ts (3)

82-103: Search PATH and avoid non-bin Windows locations

Don’t scan npm-cache or Node’s install dir; they won’t contain CLI shims. Do scan PATH and dedupe. Keep APPDATA\npm for Windows.

-		// 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')
-			] : [])
-		];
+		// Define fallback search paths for different installation methods
+		const envPathDirs = (process.env.PATH || '').split(path.delimiter).filter(Boolean);
+		const fallbackPaths = [
+			// Standard npm binary location within the plugin
+			path.join(pluginDir, 'node_modules', '.bin'),
+			// Direct package binary location
+			path.join(pluginDir, 'node_modules', 'pdf-to-img', 'bin'),
+			// Common Windows global npm shims
+			...(process.platform === 'win32' ? [path.join(process.env.APPDATA || '', 'npm')] : []),
+			// Directories from PATH
+			...envPathDirs
+		]
+		// Only keep absolute, non-empty entries
+		.filter(p => p && path.isAbsolute(p));
+
+		// De-duplicate
+		const seen = new Set<string>();
+		const uniqueFallbackPaths = fallbackPaths.filter(p => (seen.has(p) ? false : (seen.add(p), true)));
 
-		// Try each fallback path with platform-specific extensions
-		for (const searchPath of fallbackPaths) {
+		// Try each fallback path with platform-specific extensions
+		for (const searchPath of uniqueFallbackPaths) {

32-35: Derive plugin dir from manifest.id; avoid non-null assertions

manifest.dir is not standard and may be undefined. Prefer manifest.id and build vault path using configDir/plugins/.

-			const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
+			const pluginDirName = plugin?.manifest?.id || 'obsidian-typst-pdf-export';
-			...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : [])
+			...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), configDir, 'plugins', pluginDirName)] : [])

Also applies to: 140-141


37-47: Non-plugin context leaves pluginDir at a possibly invalid default

When plugin is absent, we never validate candidates. Not a blocker given plugin context in Obsidian, but consider FS-based validation to improve resilience in tests or tooling.

-			let pluginDir = possiblePluginDirs[0]; // Default fallback
-			for (const dir of possiblePluginDirs) {
+			let pluginDir = possiblePluginDirs[0]; // Default fallback
+			for (const dir of possiblePluginDirs) {
 				try {
 					const nodeModulesPath = path.join(dir, 'node_modules');
-					if (plugin?.app) {
+					if (plugin?.app) {
 						const pathUtils = new PathUtils(plugin.app);
 						if (await pathUtils.fileExists(nodeModulesPath)) {
 							pluginDir = dir;
 							break;
 						}
-					}
+					} else {
+						const fs = require('fs').promises;
+						await fs.access(nodeModulesPath);
+						pluginDir = dir;
+						break;
+					}
 				} catch {
 					continue;
 				}
 			}
src/converters/pdf/FileDiscovery.ts (2)

216-256: Make pattern matching case-insensitive to avoid OS/filesystem variance

On Windows/macOS filesystems, case differences are common. Lowercase both sides in matching strategies to reduce false negatives.

-		const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName));
+		const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName));
+		const expectedBaseLower = expectedBase.toLowerCase();
+		const expectedFileLower = expectedFileName.toLowerCase();
@@
-		const exactMatch = files.find(f => f === expectedFileName);
+		const exactMatch = files.find(f => f.toLowerCase() === expectedFileLower);
@@
-		const baseNameMatch = files.find(f => {
-			const fileBase = path.basename(f, path.extname(f));
-			return fileBase === expectedBase;
+		const baseNameMatch = files.find(f => {
+			const fileBaseLower = path.basename(f, path.extname(f)).toLowerCase();
+			return fileBaseLower === expectedBaseLower;
 		});
@@
-		const sanitizedMatch = files.find(f => {
-			const fileBase = path.basename(f, path.extname(f));
-			const simplifiedActual = this.sanitizeFilename(fileBase);
-			return simplifiedActual === simplifiedExpected;
+		const sanitizedMatch = files.find(f => {
+			const fileBase = path.basename(f, path.extname(f));
+			const simplifiedActual = this.sanitizeFilename(fileBase).toLowerCase();
+			return simplifiedActual === simplifiedExpected.toLowerCase();
 		});
@@
-		const fuzzyMatch = files.find(f => {
-			const fileBase = path.basename(f, path.extname(f));
+		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);
 		});

258-260: Avoid picking an unrelated image arbitrarily

Returning the first image can select a wrong file when multiple images exist. Prefer returning no match unless exactly one candidate exists.

-		// Strategy 5: Fallback to first available image file if no pattern matches
-		return files.length > 0 ? files[0] : null;
+		// Strategy 5: Only fallback when there is exactly one candidate
+		return files.length === 1 ? files[0] : null;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d20e8cf0ae and 2cdc9c3976.

📒 Files selected for processing (5)
  • CHANGELOG.md (1 hunks)
  • src/converters/pdf/BinaryLocator.ts (5 hunks)
  • src/converters/pdf/FileDiscovery.ts (5 hunks)
  • src/plugin/ExportOrchestrator.ts (3 hunks)
  • src/plugin/FontManager.ts (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/plugin/ExportOrchestrator.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-25T14:14:57.394Z
Learnt from: AlexKucera
PR: AlexKucera/obsidian-typst-pdf-export#5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.394Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.

Applied to files:

  • src/converters/pdf/FileDiscovery.ts
🧬 Code graph analysis (3)
src/converters/pdf/BinaryLocator.ts (1)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/converters/pdf/FileDiscovery.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/plugin/FontManager.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-121)
src/core/constants.ts (1)
  • FALLBACK_FONTS (8-20)
🔇 Additional comments (3)
src/plugin/FontManager.ts (2)

74-79: Switched to vault-relative adapter paths — good fix.

Using vault-relative plugin paths for read/write resolves cross-adapter issues and aligns with Obsidian APIs.

Also applies to: 97-102, 111-115


117-126: Solid corrupted cache handling.

Removing bad cache, regenerating, and falling back gracefully is robust.

src/converters/pdf/FileDiscovery.ts (1)

20-22: JPEG/PNG regression addressed and discovery generalized

Good move to a centralized allowed list and non-PNG-only discovery; resolves prior hard-coding concerns.

Also applies to: 69-99, 147-166

**Actionable comments posted: 4** <details> <summary>🧹 Nitpick comments (5)</summary><blockquote> <details> <summary>src/converters/pdf/BinaryLocator.ts (3)</summary><blockquote> `82-103`: **Search PATH and avoid non-bin Windows locations** Don’t scan npm-cache or Node’s install dir; they won’t contain CLI shims. Do scan PATH and dedupe. Keep APPDATA\npm for Windows. ```diff - // 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') - ] : []) - ]; + // Define fallback search paths for different installation methods + const envPathDirs = (process.env.PATH || '').split(path.delimiter).filter(Boolean); + const fallbackPaths = [ + // Standard npm binary location within the plugin + path.join(pluginDir, 'node_modules', '.bin'), + // Direct package binary location + path.join(pluginDir, 'node_modules', 'pdf-to-img', 'bin'), + // Common Windows global npm shims + ...(process.platform === 'win32' ? [path.join(process.env.APPDATA || '', 'npm')] : []), + // Directories from PATH + ...envPathDirs + ] + // Only keep absolute, non-empty entries + .filter(p => p && path.isAbsolute(p)); + + // De-duplicate + const seen = new Set<string>(); + const uniqueFallbackPaths = fallbackPaths.filter(p => (seen.has(p) ? false : (seen.add(p), true))); - // Try each fallback path with platform-specific extensions - for (const searchPath of fallbackPaths) { + // Try each fallback path with platform-specific extensions + for (const searchPath of uniqueFallbackPaths) { ``` --- `32-35`: **Derive plugin dir from manifest.id; avoid non-null assertions** `manifest.dir` is not standard and may be undefined. Prefer `manifest.id` and build vault path using configDir/plugins/<id>. ```diff - const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export'; + const pluginDirName = plugin?.manifest?.id || 'obsidian-typst-pdf-export'; ``` ```diff - ...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : []) + ...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), configDir, 'plugins', pluginDirName)] : []) ``` Also applies to: 140-141 --- `37-47`: **Non-plugin context leaves `pluginDir` at a possibly invalid default** When `plugin` is absent, we never validate candidates. Not a blocker given plugin context in Obsidian, but consider FS-based validation to improve resilience in tests or tooling. ```diff - let pluginDir = possiblePluginDirs[0]; // Default fallback - for (const dir of possiblePluginDirs) { + let pluginDir = possiblePluginDirs[0]; // Default fallback + for (const dir of possiblePluginDirs) { try { const nodeModulesPath = path.join(dir, 'node_modules'); - if (plugin?.app) { + if (plugin?.app) { const pathUtils = new PathUtils(plugin.app); if (await pathUtils.fileExists(nodeModulesPath)) { pluginDir = dir; break; } - } + } else { + const fs = require('fs').promises; + await fs.access(nodeModulesPath); + pluginDir = dir; + break; + } } catch { continue; } } ``` </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (2)</summary><blockquote> `216-256`: **Make pattern matching case-insensitive to avoid OS/filesystem variance** On Windows/macOS filesystems, case differences are common. Lowercase both sides in matching strategies to reduce false negatives. ```diff - const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName)); + const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName)); + const expectedBaseLower = expectedBase.toLowerCase(); + const expectedFileLower = expectedFileName.toLowerCase(); @@ - const exactMatch = files.find(f => f === expectedFileName); + const exactMatch = files.find(f => f.toLowerCase() === expectedFileLower); @@ - const baseNameMatch = files.find(f => { - const fileBase = path.basename(f, path.extname(f)); - return fileBase === expectedBase; + const baseNameMatch = files.find(f => { + const fileBaseLower = path.basename(f, path.extname(f)).toLowerCase(); + return fileBaseLower === expectedBaseLower; }); @@ - const sanitizedMatch = files.find(f => { - const fileBase = path.basename(f, path.extname(f)); - const simplifiedActual = this.sanitizeFilename(fileBase); - return simplifiedActual === simplifiedExpected; + const sanitizedMatch = files.find(f => { + const fileBase = path.basename(f, path.extname(f)); + const simplifiedActual = this.sanitizeFilename(fileBase).toLowerCase(); + return simplifiedActual === simplifiedExpected.toLowerCase(); }); @@ - const fuzzyMatch = files.find(f => { - const fileBase = path.basename(f, path.extname(f)); + 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); }); ``` --- `258-260`: **Avoid picking an unrelated image arbitrarily** Returning the first image can select a wrong file when multiple images exist. Prefer returning no match unless exactly one candidate exists. ```diff - // Strategy 5: Fallback to first available image file if no pattern matches - return files.length > 0 ? files[0] : null; + // Strategy 5: Only fallback when there is exactly one candidate + return files.length === 1 ? files[0] : null; ``` </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d20e8cf0aeb566cf4938cb197842ac5b58d81f4c and 2cdc9c3976d2d9a3f5e9ac6d322165f350dafe7a. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `CHANGELOG.md` (1 hunks) * `src/converters/pdf/BinaryLocator.ts` (5 hunks) * `src/converters/pdf/FileDiscovery.ts` (5 hunks) * `src/plugin/ExportOrchestrator.ts` (3 hunks) * `src/plugin/FontManager.ts` (5 hunks) </details> <details> <summary>✅ Files skipped from review due to trivial changes (1)</summary> * CHANGELOG.md </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/plugin/ExportOrchestrator.ts </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🧠 Learnings (1)</summary> <details> <summary>📚 Learning: 2025-09-25T14:14:57.394Z</summary> ``` Learnt from: AlexKucera PR: AlexKucera/obsidian-typst-pdf-export#5 File: src/converters/pandoc/ResourcePathResolver.ts:109-111 Timestamp: 2025-09-25T14:14:57.394Z Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer. ``` **Applied to files:** - `src/converters/pdf/FileDiscovery.ts` </details> </details><details> <summary>🧬 Code graph analysis (3)</summary> <details> <summary>src/converters/pdf/BinaryLocator.ts (1)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> </blockquote></details> <details> <summary>src/plugin/FontManager.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-121) </details> <details> <summary>src/core/constants.ts (1)</summary> * `FALLBACK_FONTS` (8-20) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (3)</summary><blockquote> <details> <summary>src/plugin/FontManager.ts (2)</summary><blockquote> `74-79`: **Switched to vault-relative adapter paths — good fix.** Using vault-relative plugin paths for read/write resolves cross-adapter issues and aligns with Obsidian APIs. Also applies to: 97-102, 111-115 --- `117-126`: **Solid corrupted cache handling.** Removing bad cache, regenerating, and falling back gracefully is robust. </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (1)</summary><blockquote> `20-22`: **JPEG/PNG regression addressed and discovery generalized** Good move to a centralized allowed list and non-PNG-only discovery; resolves prior hard-coding concerns. Also applies to: 69-99, 147-166 </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@@ -83,19 +137,27 @@ export class BinaryLocator {
// Strategy 2: Assuming we're running from vault root
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:21:14 +02:00

⚠️ 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
@@ -16,65 +17,186 @@ export interface FileDiscoveryResult {
}
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:21:15 +02:00

⚠️ 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
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:21:15 +02:00

⚠️ Potential issue | 🟠 Major

Fix Windows PATH propagation in child process env (set both PATH and Path).

On Windows, some processes only read the 'Path' key. Set both to avoid lookup issues.

Apply this diff:

-				const enhancedEnv = {
-					...process.env,
-					PATH: this.buildPlatformSpecificPATH()
-				};
+				const enhancedEnv = { ...process.env };
+				const pathValue = this.buildPlatformSpecificPATH();
+				if (process.platform === 'win32') {
+					// Ensure Windows processes see the updated PATH (case-insensitive env key)
+					(enhancedEnv as any).PATH = pathValue;
+					(enhancedEnv as any).Path = pathValue;
+				} else {
+					(enhancedEnv as any).PATH = pathValue;
+				}
📝 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.

// Build platform-specific environment with enhanced PATH
const enhancedEnv = { ...process.env };
const pathValue = this.buildPlatformSpecificPATH();
if (process.platform === 'win32') {
  // Ensure Windows processes see the updated PATH (case-insensitive env key)
  (enhancedEnv as any).PATH = pathValue;
  (enhancedEnv as any).Path = pathValue;
} else {
  (enhancedEnv as any).PATH = pathValue;
}

const typstProcess = spawn(typstPath, ['fonts'], {
  stdio: ['pipe', 'pipe', 'pipe'],
  env: enhancedEnv
});
🤖 Prompt for AI Agents
In src/plugin/FontManager.ts around lines 25 to 34, the child process env
currently only sets PATH which can fail on Windows; update enhancedEnv to set
both PATH and Path to the value returned by buildPlatformSpecificPATH() so the
spawned typst process sees the same path on all platforms, i.e., compute const
pathValue = this.buildPlatformSpecificPATH() and spread process.env while
assigning PATH: pathValue and Path: pathValue before passing env to spawn.

✅ Addressed in commits a129380 to 21ed9e1

_⚠️ Potential issue_ | _🟠 Major_ **Fix Windows PATH propagation in child process env (set both PATH and Path).** On Windows, some processes only read the 'Path' key. Set both to avoid lookup issues. Apply this diff: ```diff - const enhancedEnv = { - ...process.env, - PATH: this.buildPlatformSpecificPATH() - }; + const enhancedEnv = { ...process.env }; + const pathValue = this.buildPlatformSpecificPATH(); + if (process.platform === 'win32') { + // Ensure Windows processes see the updated PATH (case-insensitive env key) + (enhancedEnv as any).PATH = pathValue; + (enhancedEnv as any).Path = pathValue; + } else { + (enhancedEnv as any).PATH = pathValue; + } ``` <!-- 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 // Build platform-specific environment with enhanced PATH const enhancedEnv = { ...process.env }; const pathValue = this.buildPlatformSpecificPATH(); if (process.platform === 'win32') { // Ensure Windows processes see the updated PATH (case-insensitive env key) (enhancedEnv as any).PATH = pathValue; (enhancedEnv as any).Path = pathValue; } else { (enhancedEnv as any).PATH = pathValue; } const typstProcess = spawn(typstPath, ['fonts'], { stdio: ['pipe', 'pipe', 'pipe'], env: enhancedEnv }); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/FontManager.ts around lines 25 to 34, the child process env currently only sets PATH which can fail on Windows; update enhancedEnv to set both PATH and Path to the value returned by buildPlatformSpecificPATH() so the spawned typst process sees the same path on all platforms, i.e., compute const pathValue = this.buildPlatformSpecificPATH() and spread process.env while assigning PATH: pathValue and Path: pathValue before passing env to spawn. ``` </details> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 21ed9e1
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:21:15 +02:00

⚠️ Potential issue | 🟠 Major

Expand '~' in PATH entries and actually de-duplicate paths.

Currently '~' entries won't resolve and duplicates are not removed despite the comment.

Apply this diff:

 	private buildPlatformSpecificPATH(): string {
-		const currentPath = process.env.PATH || '';
-		const pathSeparator = process.platform === 'win32' ? ';' : ':';
+		const currentPath = process.env.PATH || (process.env as any).Path || '';
+		const pathSeparator = process.platform === 'win32' ? ';' : ':';
+		const homedir =
+			(require('os').homedir?.() as string | undefined) ??
+			process.env.HOME ??
+			process.env.USERPROFILE ??
+			'';
+		const expandTilde = (p: string) =>
+			(homedir && /^~(\/|\\)/.test(p)) ? p.replace(/^~(?=\/|\\)/, homedir) : p;
@@
-		// Combine current PATH with additional paths, avoiding duplicates
-		const allPaths = [...additionalPaths, currentPath].filter(path => path.length > 0);
-		return allPaths.join(pathSeparator);
+		// Combine current PATH with additional paths, expand ~, and de-duplicate
+		const currentParts = currentPath.split(pathSeparator).filter(Boolean);
+		const combined = [...additionalPaths.map(expandTilde), ...currentParts].filter(Boolean);
+		const deduped = Array.from(new Set(combined));
+		return deduped.join(pathSeparator);
 	}
📝 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 buildPlatformSpecificPATH(): string {
-		const currentPath = process.env.PATH || '';
		const currentPath = process.env.PATH || (process.env as any).Path || '';
		const pathSeparator = process.platform === 'win32' ? ';' : ':';
		const homedir =
			(require('os').homedir?.() as string | undefined) ??
			process.env.HOME ??
			process.env.USERPROFILE ??
			'';
		const expandTilde = (p: string) =>
			(homedir && /^~(\/|\\)/.test(p)) ? p.replace(/^~(?=\/|\\)/, homedir) : p;

 		// Platform-specific common installation paths
 		let additionalPaths: string[] = [];

 		switch (process.platform) {
@@
-		// Combine current PATH with additional paths, avoiding duplicates
-		const allPaths = [...additionalPaths, currentPath].filter(path => path.length > 0);
		// Combine current PATH with additional paths, expand ~, and de-duplicate
		const currentParts = currentPath.split(pathSeparator).filter(Boolean);
		const combined = [...additionalPaths.map(expandTilde), ...currentParts].filter(Boolean);
		const deduped = Array.from(new Set(combined));
		return deduped.join(pathSeparator);
 	}

✅ Addressed in commits a129380 to 21ed9e1

_⚠️ Potential issue_ | _🟠 Major_ **Expand '~' in PATH entries and actually de-duplicate paths.** Currently '~' entries won't resolve and duplicates are not removed despite the comment. Apply this diff: ```diff private buildPlatformSpecificPATH(): string { - const currentPath = process.env.PATH || ''; - const pathSeparator = process.platform === 'win32' ? ';' : ':'; + const currentPath = process.env.PATH || (process.env as any).Path || ''; + const pathSeparator = process.platform === 'win32' ? ';' : ':'; + const homedir = + (require('os').homedir?.() as string | undefined) ?? + process.env.HOME ?? + process.env.USERPROFILE ?? + ''; + const expandTilde = (p: string) => + (homedir && /^~(\/|\\)/.test(p)) ? p.replace(/^~(?=\/|\\)/, homedir) : p; @@ - // Combine current PATH with additional paths, avoiding duplicates - const allPaths = [...additionalPaths, currentPath].filter(path => path.length > 0); - return allPaths.join(pathSeparator); + // Combine current PATH with additional paths, expand ~, and de-duplicate + const currentParts = currentPath.split(pathSeparator).filter(Boolean); + const combined = [...additionalPaths.map(expandTilde), ...currentParts].filter(Boolean); + const deduped = Array.from(new Set(combined)); + return deduped.join(pathSeparator); } ``` <!-- 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 buildPlatformSpecificPATH(): string { - const currentPath = process.env.PATH || ''; const currentPath = process.env.PATH || (process.env as any).Path || ''; const pathSeparator = process.platform === 'win32' ? ';' : ':'; const homedir = (require('os').homedir?.() as string | undefined) ?? process.env.HOME ?? process.env.USERPROFILE ?? ''; const expandTilde = (p: string) => (homedir && /^~(\/|\\)/.test(p)) ? p.replace(/^~(?=\/|\\)/, homedir) : p; // Platform-specific common installation paths let additionalPaths: string[] = []; switch (process.platform) { @@ - // Combine current PATH with additional paths, avoiding duplicates - const allPaths = [...additionalPaths, currentPath].filter(path => path.length > 0); // Combine current PATH with additional paths, expand ~, and de-duplicate const currentParts = currentPath.split(pathSeparator).filter(Boolean); const combined = [...additionalPaths.map(expandTilde), ...currentParts].filter(Boolean); const deduped = Array.from(new Set(combined)); return deduped.join(pathSeparator); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:poseidon:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a129380 to 21ed9e1
AlexKucera (Migrated from github.com) reviewed 2025-09-25 16:27:04 +02:00
@@ -0,0 +1,125 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
AlexKucera (Migrated from github.com) commented 2025-09-25 16:27:04 +02:00

@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] (Migrated from github.com) reviewed 2025-09-25 16:27:33 +02:00
@@ -0,0 +1,125 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:27:33 +02:00

@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 -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-09-25 16:51:35 +02:00
coderabbitai[bot] (Migrated from github.com) left a comment

Actionable comments posted: 8

🧹 Nitpick comments (11)
src/plugin/FontManager.ts (6)

25-31: Set PATH/Path only on Windows (reduce env noise on Unix).

No need to set both keys on non‑Windows. Keep PATH on Unix, both on win32.

-				const enhancedEnv = {
-					...process.env,
-					PATH: pathValue,
-					Path: pathValue
-				};
+				const enhancedEnv = { ...process.env };
+				if (process.platform === 'win32') {
+					(enhancedEnv as any).PATH = pathValue;
+					(enhancedEnv as any).Path = pathValue;
+				} else {
+					(enhancedEnv as any).PATH = pathValue;
+				}

33-56: Add a timeout to the typst subprocess to avoid hangs.

Guard against a stuck child process.

-				const typstProcess = spawn(typstPath, ['fonts'], {
+				const typstProcess = spawn(typstPath, ['fonts'], {
 					stdio: ['pipe', 'pipe', 'pipe'],
 					env: enhancedEnv
 				});
+				const killTimer = setTimeout(() => {
+					try { typstProcess.kill(); } catch {}
+				}, 15000); // 15s timeout
@@
 				typstProcess.on('close', (code: number | null) => {
+					clearTimeout(killTimer);
 					if (code === 0) {
 						resolve(output);
 					} else {
 						reject(new Error(`typst fonts command failed with code ${code}: ${error}`));
 					}
 				});
 				
 				typstProcess.on('error', (err: Error) => {
+					clearTimeout(killTimer);
 					reject(new Error(`Failed to spawn typst process: ${err.message}`));
 				});

76-81: Ensure plugin directory exists before writing.

Create the directory defensively to avoid adapter.write failures on fresh installs.

 			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 pathUtils.ensureDir(pluginDir);
 			await this.plugin.app.vault.adapter.write(fontsCachePath,
 				JSON.stringify(cacheData, null, 2));

99-104: Wrap fallback cache write to avoid cascading errors.

If writing the fallback fails, don’t rethrow from the catch branch.

 			const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
-			await this.plugin.app.vault.adapter.write(fontsCachePath,
-				JSON.stringify(cacheData, null, 2));
+			try {
+				await this.plugin.app.vault.adapter.write(
+					fontsCachePath,
+					JSON.stringify(cacheData, null, 2)
+				);
+			} catch (writeErr) {
+				console.warn('Failed to write fallback fonts cache:', writeErr);
+			}

113-117: Check existence before read to avoid avoidable exceptions.

Prefer a fast exists() check and early fallback.

 			const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
-			const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);
+			const exists = await this.plugin.app.vault.adapter.exists(fontsCachePath);
+			if (!exists) {
+				// Seed the cache asynchronously and serve fallbacks now
+				this.cacheAvailableFonts().catch(() => {});
+				return [...FALLBACK_FONTS];
+			}
+			const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);

138-149: Debounce background refresh to avoid duplicate spawns.

If getCachedFonts is called frequently, you may spawn multiple typst processes. Consider an in-flight Promise to coalesce refreshes.

I can draft a minimal inFlightCache Promise pattern if you want.

src/converters/pdf/BinaryLocator.ts (1)

41-47: Fallback to FS when plugin is absent

When plugin?.app is missing, we skip existence checks entirely. Add an FS check so discovery still works outside the Obsidian adapter path.

-					if (plugin?.app) {
+					if (plugin?.app) {
 						const pathUtils = new PathUtils(plugin.app);
 						if (await pathUtils.fileExists(nodeModulesPath)) {
 							pluginDir = dir;
 							break;
 						}
-					}
+					} else {
+						try {
+							const fs = require('fs').promises;
+							await fs.access(nodeModulesPath);
+							pluginDir = dir;
+							break;
+						} catch { /* continue */ }
+					}
src/plugin/ExportOrchestrator.ts (1)

139-141: Compute pluginDir deterministically (avoid manifest.dir ambiguity)

getPluginDir(this.plugin.manifest) may resolve to an absolute path or empty string depending on environment. Use vaultPath + configDir/plugins/<id> to avoid edge cases.

-		const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
+		const pluginDir = this.pathUtils.joinPath(
+			vaultPath,
+			this.plugin.app.vault.configDir,
+			'plugins',
+			this.plugin.manifest.id
+		);
src/converters/pdf/ImageOptimizer.ts (1)

199-205: Prefer vault-relative for adapter operations downstream

finalOutputPath will later be used with adapter methods; consider deriving and reusing a vault-relative variant alongside the absolute path to avoid repeated conversions.

src/converters/pdf/FileDiscovery.ts (2)

103-112: Ensure adapter.list receives vault-relative path with forward slashes

Follow-up to the previous change: adapter.list should be called only with the normalized, vault-relative dir.

-			if (isVaultRelative) {
-				// Use adapter for vault-relative paths
-				const dirList = await plugin.app.vault.adapter.list(vaultRelativeDir);
+			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));

32-34: Optional: reduce duplicate existence checks by sharing a tiny helper

Both branches pattern-match similarly; consider a small helper to DRY list+filter+match logic.

Also applies to: 133-141

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cdc9c3976 and 21ed9e122f.

📒 Files selected for processing (9)
  • README.md (1 hunks)
  • src/converters/pdf/BinaryLocator.ts (5 hunks)
  • src/converters/pdf/FileDiscovery.ts (5 hunks)
  • src/converters/pdf/ImageOptimizer.ts (5 hunks)
  • src/core/PathUtils.ts (1 hunks)
  • src/core/TempDirectoryManager.ts (2 hunks)
  • src/plugin/ExportOrchestrator.ts (3 hunks)
  • src/plugin/FontManager.ts (5 hunks)
  • src/templates/TemplateManager.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/core/PathUtils.ts
  • README.md
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
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.
📚 Learning: 2025-09-25T14:27:31.819Z
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.

Applied to files:

  • src/converters/pdf/ImageOptimizer.ts
  • src/core/TempDirectoryManager.ts
  • src/converters/pdf/FileDiscovery.ts
  • src/plugin/ExportOrchestrator.ts
  • src/converters/pdf/BinaryLocator.ts
  • src/templates/TemplateManager.ts
  • src/plugin/FontManager.ts
📚 Learning: 2025-09-25T14:14:57.394Z
Learnt from: AlexKucera
PR: AlexKucera/obsidian-typst-pdf-export#5
File: src/converters/pandoc/ResourcePathResolver.ts:109-111
Timestamp: 2025-09-25T14:14:57.394Z
Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer.

Applied to files:

  • src/converters/pdf/FileDiscovery.ts
🧬 Code graph analysis (7)
src/converters/pdf/ImageOptimizer.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-130)
src/core/TempDirectoryManager.ts (1)
src/core/constants.ts (1)
  • PLUGIN_DIRS (25-29)
src/converters/pdf/FileDiscovery.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-130)
src/plugin/ExportOrchestrator.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-130)
src/core/TempDirectoryManager.ts (1)
  • TempDirectoryManager (19-113)
src/converters/pdf/BinaryLocator.ts (1)
src/core/PathUtils.ts (1)
  • PathUtils (7-130)
src/templates/TemplateManager.ts (2)
main.ts (1)
  • obsidianTypstPDFExport (30-245)
src/core/PathUtils.ts (1)
  • PathUtils (7-130)
src/plugin/FontManager.ts (2)
src/core/PathUtils.ts (1)
  • PathUtils (7-130)
src/core/constants.ts (1)
  • FALLBACK_FONTS (8-20)
🔇 Additional comments (16)
src/plugin/FontManager.ts (7)

72-74: Good cache invalidation keys.

Including typstPath and platform will properly trigger refreshes on env changes.


119-128: Robust parse handling looks good.

Corruption path removes file, regenerates, and returns fallbacks.


130-136: Solid schema validation.

Good early regeneration on invalid shape.


151-157: Validating font strings is correct.

Good safeguard; falls back when list is empty.


160-163: Background rebuild on read error is appropriate.

Non-blocking recovery with fallbacks is sensible here.


180-249: Improve PATH construction: read both PATH/Path, robust homedir, and Windows case-insensitive de‑dupe.

Aligns with prior feedback: include Path, use os.homedir, and de-dupe case-insensitively on Windows.

-	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;
-		};
+	private buildPlatformSpecificPATH(): string {
+		const currentPath = process.env.PATH || (process.env as any).Path || '';
+		const pathSeparator = process.platform === 'win32' ? ';' : ':';
+		const homedir =
+			(require('os').homedir?.() as string | undefined) ??
+			process.env.HOME ??
+			process.env.USERPROFILE ??
+			'';
+		const expandTildePath = (p: string): string =>
+			(homedir && /^~(?=\/|\\)/.test(p)) ? p.replace(/^~(?=\/|\\)/, homedir) : p;
@@
 			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` : ''
+					process.env.USERPROFILE ? `${process.env.USERPROFILE}\\.cargo\\bin` : '',
+					// Common package manager shims
+					'C:\\ProgramData\\chocolatey\\bin',
+					process.env.USERPROFILE ? `${process.env.USERPROFILE}\\scoop\\shims` : ''
 				].filter(path => path.length > 0);
 				break;
@@
-		// 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);
+		// Split current PATH and combine with additional paths
+		const currentPaths = currentPath.split(pathSeparator).filter(Boolean);
+		const allPaths = [...expandedPaths, ...currentPaths];
+
+		// Remove duplicates while preserving order (case-insensitive on Windows)
+		const seen = new Set<string>();
+		const key = (p: string) => process.platform === 'win32' ? p.toLowerCase() : p;
+		const uniquePaths = allPaths.filter(p => {
+			const k = key(p);
+			if (seen.has(k)) return false;
+			seen.add(k);
+			return true;
+		});
+
+		return uniquePaths.join(pathSeparator);
 	}

19-21: Desktop-only flag present – manifest.json includes "isDesktopOnly": true, so using child_process is safe.

src/plugin/ExportOrchestrator.ts (3)

17-21: Good: centralizing vault/app path ops via PathUtils

Initializing a shared PathUtils aligns with the plugin’s vault-aware path strategy.


147-153: Good: TempDirectoryManager constructed with pluginName and app

Passing pluginName and app fixes mismatched temp-dir locations and enables adapter-based ops.


257-259: Good: Cleanup uses plugin-aware TempDirectoryManager.create

Ensures only this plugin’s temp dirs are cleaned with adapter-backed removal.

src/templates/TemplateManager.ts (2)

19-23: Good: templatesPath built via PathUtils

Consistent with vault-aware path handling and avoids Node path joins for vault paths.


38-50: Good: Convert absolute to vault-relative before adapter.list

This avoids adapter path mismatches and works across platforms.

src/core/TempDirectoryManager.ts (1)

100-112: Nice improvement: normalized dir validation to avoid traversal

Using normalizePath and explicit temp subpaths makes the check robust.

src/converters/pdf/FileDiscovery.ts (3)

20-22: LGTM: centralizing supported formats and validating extension

Consistent with the project’s intended set (.png/.jpg/.jpeg/.webp/.gif/.bmp/.tiff) and guards bad inputs by falling back to PNG.

Also applies to: 303-318


50-67: Good: plugin-aware expected path + PathUtils.fileExists fallback

Correctly branches between direct FS and vault-adapter lookups.


32-35: Verify removal of manifest.dir usage
No matches for manifest.dir or manifest.id found in the repo; manually confirm no remaining references.

**Actionable comments posted: 8** <details> <summary>🧹 Nitpick comments (11)</summary><blockquote> <details> <summary>src/plugin/FontManager.ts (6)</summary><blockquote> `25-31`: **Set PATH/Path only on Windows (reduce env noise on Unix).** No need to set both keys on non‑Windows. Keep PATH on Unix, both on win32. ```diff - const enhancedEnv = { - ...process.env, - PATH: pathValue, - Path: pathValue - }; + const enhancedEnv = { ...process.env }; + if (process.platform === 'win32') { + (enhancedEnv as any).PATH = pathValue; + (enhancedEnv as any).Path = pathValue; + } else { + (enhancedEnv as any).PATH = pathValue; + } ``` --- `33-56`: **Add a timeout to the typst subprocess to avoid hangs.** Guard against a stuck child process. ```diff - const typstProcess = spawn(typstPath, ['fonts'], { + const typstProcess = spawn(typstPath, ['fonts'], { stdio: ['pipe', 'pipe', 'pipe'], env: enhancedEnv }); + const killTimer = setTimeout(() => { + try { typstProcess.kill(); } catch {} + }, 15000); // 15s timeout @@ typstProcess.on('close', (code: number | null) => { + clearTimeout(killTimer); if (code === 0) { resolve(output); } else { reject(new Error(`typst fonts command failed with code ${code}: ${error}`)); } }); typstProcess.on('error', (err: Error) => { + clearTimeout(killTimer); reject(new Error(`Failed to spawn typst process: ${err.message}`)); }); ``` --- `76-81`: **Ensure plugin directory exists before writing.** Create the directory defensively to avoid adapter.write failures on fresh installs. ```diff 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 pathUtils.ensureDir(pluginDir); await this.plugin.app.vault.adapter.write(fontsCachePath, JSON.stringify(cacheData, null, 2)); ``` --- `99-104`: **Wrap fallback cache write to avoid cascading errors.** If writing the fallback fails, don’t rethrow from the catch branch. ```diff const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json'); - await this.plugin.app.vault.adapter.write(fontsCachePath, - JSON.stringify(cacheData, null, 2)); + try { + await this.plugin.app.vault.adapter.write( + fontsCachePath, + JSON.stringify(cacheData, null, 2) + ); + } catch (writeErr) { + console.warn('Failed to write fallback fonts cache:', writeErr); + } ``` --- `113-117`: **Check existence before read to avoid avoidable exceptions.** Prefer a fast exists() check and early fallback. ```diff const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json'); - const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath); + const exists = await this.plugin.app.vault.adapter.exists(fontsCachePath); + if (!exists) { + // Seed the cache asynchronously and serve fallbacks now + this.cacheAvailableFonts().catch(() => {}); + return [...FALLBACK_FONTS]; + } + const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath); ``` --- `138-149`: **Debounce background refresh to avoid duplicate spawns.** If getCachedFonts is called frequently, you may spawn multiple typst processes. Consider an in-flight Promise to coalesce refreshes. I can draft a minimal inFlightCache Promise pattern if you want. </blockquote></details> <details> <summary>src/converters/pdf/BinaryLocator.ts (1)</summary><blockquote> `41-47`: **Fallback to FS when plugin is absent** When `plugin?.app` is missing, we skip existence checks entirely. Add an FS check so discovery still works outside the Obsidian adapter path. ```diff - if (plugin?.app) { + if (plugin?.app) { const pathUtils = new PathUtils(plugin.app); if (await pathUtils.fileExists(nodeModulesPath)) { pluginDir = dir; break; } - } + } else { + try { + const fs = require('fs').promises; + await fs.access(nodeModulesPath); + pluginDir = dir; + break; + } catch { /* continue */ } + } ``` </blockquote></details> <details> <summary>src/plugin/ExportOrchestrator.ts (1)</summary><blockquote> `139-141`: **Compute pluginDir deterministically (avoid manifest.dir ambiguity)** `getPluginDir(this.plugin.manifest)` may resolve to an absolute path or empty string depending on environment. Use `vaultPath + configDir/plugins/<id>` to avoid edge cases. ```diff - const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest)); + const pluginDir = this.pathUtils.joinPath( + vaultPath, + this.plugin.app.vault.configDir, + 'plugins', + this.plugin.manifest.id + ); ``` </blockquote></details> <details> <summary>src/converters/pdf/ImageOptimizer.ts (1)</summary><blockquote> `199-205`: **Prefer vault-relative for adapter operations downstream** `finalOutputPath` will later be used with adapter methods; consider deriving and reusing a vault-relative variant alongside the absolute path to avoid repeated conversions. </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (2)</summary><blockquote> `103-112`: **Ensure adapter.list receives vault-relative path with forward slashes** Follow-up to the previous change: adapter.list should be called only with the normalized, vault-relative dir. ```diff - if (isVaultRelative) { - // Use adapter for vault-relative paths - const dirList = await plugin.app.vault.adapter.list(vaultRelativeDir); + 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)); ``` --- `32-34`: **Optional: reduce duplicate existence checks by sharing a tiny helper** Both branches pattern-match similarly; consider a small helper to DRY list+filter+match logic. Also applies to: 133-141 </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2cdc9c3976d2d9a3f5e9ac6d322165f350dafe7a and 21ed9e122f6a727cf3aaa2e543a3a1308fd72500. </details> <details> <summary>📒 Files selected for processing (9)</summary> * `README.md` (1 hunks) * `src/converters/pdf/BinaryLocator.ts` (5 hunks) * `src/converters/pdf/FileDiscovery.ts` (5 hunks) * `src/converters/pdf/ImageOptimizer.ts` (5 hunks) * `src/core/PathUtils.ts` (1 hunks) * `src/core/TempDirectoryManager.ts` (2 hunks) * `src/plugin/ExportOrchestrator.ts` (3 hunks) * `src/plugin/FontManager.ts` (5 hunks) * `src/templates/TemplateManager.ts` (4 hunks) </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary> * src/core/PathUtils.ts * README.md </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🧠 Learnings (3)</summary> <details> <summary>📓 Common learnings</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. ``` </details> <details> <summary>📚 Learning: 2025-09-25T14:27:31.819Z</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. ``` **Applied to files:** - `src/converters/pdf/ImageOptimizer.ts` - `src/core/TempDirectoryManager.ts` - `src/converters/pdf/FileDiscovery.ts` - `src/plugin/ExportOrchestrator.ts` - `src/converters/pdf/BinaryLocator.ts` - `src/templates/TemplateManager.ts` - `src/plugin/FontManager.ts` </details> <details> <summary>📚 Learning: 2025-09-25T14:14:57.394Z</summary> ``` Learnt from: AlexKucera PR: AlexKucera/obsidian-typst-pdf-export#5 File: src/converters/pandoc/ResourcePathResolver.ts:109-111 Timestamp: 2025-09-25T14:14:57.394Z Learning: In src/converters/pandoc/ResourcePathResolver.ts, the image extension regex /\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i is intentionally restricted and should not be expanded to include additional formats like .tif, .avif, .heic, .heif as this is a conscious design decision by the maintainer. ``` **Applied to files:** - `src/converters/pdf/FileDiscovery.ts` </details> </details><details> <summary>🧬 Code graph analysis (7)</summary> <details> <summary>src/converters/pdf/ImageOptimizer.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-130) </details> </blockquote></details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary><blockquote> <details> <summary>src/core/constants.ts (1)</summary> * `PLUGIN_DIRS` (25-29) </details> </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-130) </details> </blockquote></details> <details> <summary>src/plugin/ExportOrchestrator.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-130) </details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary> * `TempDirectoryManager` (19-113) </details> </blockquote></details> <details> <summary>src/converters/pdf/BinaryLocator.ts (1)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-130) </details> </blockquote></details> <details> <summary>src/templates/TemplateManager.ts (2)</summary><blockquote> <details> <summary>main.ts (1)</summary> * `obsidianTypstPDFExport` (30-245) </details> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-130) </details> </blockquote></details> <details> <summary>src/plugin/FontManager.ts (2)</summary><blockquote> <details> <summary>src/core/PathUtils.ts (1)</summary> * `PathUtils` (7-130) </details> <details> <summary>src/core/constants.ts (1)</summary> * `FALLBACK_FONTS` (8-20) </details> </blockquote></details> </details> </details> <details> <summary>🔇 Additional comments (16)</summary><blockquote> <details> <summary>src/plugin/FontManager.ts (7)</summary><blockquote> `72-74`: **Good cache invalidation keys.** Including typstPath and platform will properly trigger refreshes on env changes. --- `119-128`: **Robust parse handling looks good.** Corruption path removes file, regenerates, and returns fallbacks. --- `130-136`: **Solid schema validation.** Good early regeneration on invalid shape. --- `151-157`: **Validating font strings is correct.** Good safeguard; falls back when list is empty. --- `160-163`: **Background rebuild on read error is appropriate.** Non-blocking recovery with fallbacks is sensible here. --- `180-249`: **Improve PATH construction: read both PATH/Path, robust homedir, and Windows case-insensitive de‑dupe.** Aligns with prior feedback: include Path, use os.homedir, and de-dupe case-insensitively on Windows. ```diff - 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; - }; + private buildPlatformSpecificPATH(): string { + const currentPath = process.env.PATH || (process.env as any).Path || ''; + const pathSeparator = process.platform === 'win32' ? ';' : ':'; + const homedir = + (require('os').homedir?.() as string | undefined) ?? + process.env.HOME ?? + process.env.USERPROFILE ?? + ''; + const expandTildePath = (p: string): string => + (homedir && /^~(?=\/|\\)/.test(p)) ? p.replace(/^~(?=\/|\\)/, homedir) : p; @@ 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` : '' + process.env.USERPROFILE ? `${process.env.USERPROFILE}\\.cargo\\bin` : '', + // Common package manager shims + 'C:\\ProgramData\\chocolatey\\bin', + process.env.USERPROFILE ? `${process.env.USERPROFILE}\\scoop\\shims` : '' ].filter(path => path.length > 0); break; @@ - // 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); + // Split current PATH and combine with additional paths + const currentPaths = currentPath.split(pathSeparator).filter(Boolean); + const allPaths = [...expandedPaths, ...currentPaths]; + + // Remove duplicates while preserving order (case-insensitive on Windows) + const seen = new Set<string>(); + const key = (p: string) => process.platform === 'win32' ? p.toLowerCase() : p; + const uniquePaths = allPaths.filter(p => { + const k = key(p); + if (seen.has(k)) return false; + seen.add(k); + return true; + }); + + return uniquePaths.join(pathSeparator); } ``` --- `19-21`: **Desktop-only flag present** – manifest.json includes "isDesktopOnly": true, so using child_process is safe. </blockquote></details> <details> <summary>src/plugin/ExportOrchestrator.ts (3)</summary><blockquote> `17-21`: **Good: centralizing vault/app path ops via PathUtils** Initializing a shared `PathUtils` aligns with the plugin’s vault-aware path strategy. --- `147-153`: **Good: TempDirectoryManager constructed with pluginName and app** Passing `pluginName` and `app` fixes mismatched temp-dir locations and enables adapter-based ops. --- `257-259`: **Good: Cleanup uses plugin-aware TempDirectoryManager.create** Ensures only this plugin’s temp dirs are cleaned with adapter-backed removal. </blockquote></details> <details> <summary>src/templates/TemplateManager.ts (2)</summary><blockquote> `19-23`: **Good: templatesPath built via PathUtils** Consistent with vault-aware path handling and avoids Node path joins for vault paths. --- `38-50`: **Good: Convert absolute to vault-relative before adapter.list** This avoids adapter path mismatches and works across platforms. </blockquote></details> <details> <summary>src/core/TempDirectoryManager.ts (1)</summary><blockquote> `100-112`: **Nice improvement: normalized dir validation to avoid traversal** Using normalizePath and explicit temp subpaths makes the check robust. </blockquote></details> <details> <summary>src/converters/pdf/FileDiscovery.ts (3)</summary><blockquote> `20-22`: **LGTM: centralizing supported formats and validating extension** Consistent with the project’s intended set (.png/.jpg/.jpeg/.webp/.gif/.bmp/.tiff) and guards bad inputs by falling back to PNG. Also applies to: 303-318 --- `50-67`: **Good: plugin-aware expected path + PathUtils.fileExists fallback** Correctly branches between direct FS and vault-adapter lookups. --- `32-35`: **Verify removal of `manifest.dir` usage** No matches for `manifest.dir` or `manifest.id` found in the repo; manually confirm no remaining references. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@@ -53,4 +51,2 @@
error: `PDF2IMG binary not found at: ${pdf2imgPath}`
};
}
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:33 +02:00

⚠️ 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 -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:33 +02:00

⚠️ Potential issue | 🔴 Critical

Fix plugin path computation (don’t depend on manifest.dir and ensure vault-relative join)

manifest.dir! is unsafe and may produce malformed paths. Build the plugin dir under the vault’s configDir deterministically.

-			...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : [])
+			...(plugin ? [
+				path.join(
+					new PathUtils(plugin.app).getVaultPath(),
+					configDir,
+					'plugins',
+					pluginDirName
+				)
+			] : [])

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

🤖 Prompt for AI Agents
In src/converters/pdf/BinaryLocator.ts around lines 140-141, the code currently
uses manifest.dir! which is unsafe; replace that with a deterministic
vault-config-relative path: obtain the vault config directory from PathUtils
(e.g. getConfigDir()/getVaultConfigDir()), join it with the plugins subdirectory
and a stable plugin identifier (plugin.manifest.id || plugin.id || sanitized
plugin.manifest.name) instead of manifest.dir!, and normalize the result
(path.join(...), path.normalize) so the plugin path is always vault-relative and
does not rely on a possibly-missing manifest.dir.
_⚠️ Potential issue_ | _🔴 Critical_ **Fix plugin path computation (don’t depend on manifest.dir and ensure vault-relative join)** `manifest.dir!` is unsafe and may produce malformed paths. Build the plugin dir under the vault’s configDir deterministically. ```diff - ...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : []) + ...(plugin ? [ + path.join( + new PathUtils(plugin.app).getVaultPath(), + configDir, + 'plugins', + pluginDirName + ) + ] : []) ``` > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/BinaryLocator.ts around lines 140-141, the code currently uses manifest.dir! which is unsafe; replace that with a deterministic vault-config-relative path: obtain the vault config directory from PathUtils (e.g. getConfigDir()/getVaultConfigDir()), join it with the plugins subdirectory and a stable plugin identifier (plugin.manifest.id || plugin.id || sanitized plugin.manifest.name) instead of manifest.dir!, and normalize the result (path.join(...), path.normalize) so the plugin path is always vault-relative and does not rely on a possibly-missing manifest.dir. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -64,3 +117,4 @@
if (imageFiles.length === 0) {
return {
filePath: '',
found: false,
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:33 +02:00

⚠️ 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 -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:33 +02:00

⚠️ Potential issue | 🔴 Critical

Use vault-relative paths for adapter.readBinary/writeBinary/remove

These adapter calls currently use absolute paths; convert to vault-relative to prevent “file not found” errors when ImageMagick is unavailable and we keep 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);
-					} else {
+					if (plugin?.app) {
+						const pathUtils = new PathUtils(plugin.app);
+						const vaultBase = pathUtils.getVaultPath();
+						const toRel = (p: string) => p.startsWith(vaultBase) ? p.substring(vaultBase.length).replace(/^[/\\]+/, '') : p;
+						const inputRel = toRel(inputImagePath);
+						const targetRel = toRel(pngFinalPath);
+						const content = await plugin.app.vault.adapter.readBinary(inputRel);
+						await plugin.app.vault.adapter.writeBinary(targetRel, content);
+						await plugin.app.vault.adapter.remove(inputRel);
+					} else {
📝 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.

					if (plugin?.app) {
						const pathUtils = new PathUtils(plugin.app);
						const vaultBase = pathUtils.getVaultPath();
						const toRel = (p: string) =>
							p.startsWith(vaultBase)
								? p.substring(vaultBase.length).replace(/^[/\\]+/, '')
								: p;
						const inputRel = toRel(inputImagePath);
						const targetRel = toRel(pngFinalPath);
						const content = await plugin.app.vault.adapter.readBinary(inputRel);
						await plugin.app.vault.adapter.writeBinary(targetRel, content);
						await plugin.app.vault.adapter.remove(inputRel);
					} else {
						const fs = require('fs').promises;
						await fs.rename(inputImagePath, pngFinalPath);
					}
🤖 Prompt for AI Agents
In src/converters/pdf/ImageOptimizer.ts around lines 247 to 254, the
adapter.readBinary/writeBinary/remove calls use absolute filesystem paths;
change them to vault-relative paths by deriving the vault root prefix (e.g. via
plugin.app.vault.getRoot().path or equivalent) and stripping that prefix from
inputImagePath and pngFinalPath before passing to
plugin.app.vault.adapter.readBinary/writeBinary/remove so the adapter receives
paths relative to the vault; keep the fallback fs.rename for the non-plugin
branch unchanged.
_⚠️ Potential issue_ | _🔴 Critical_ **Use vault-relative paths for adapter.readBinary/writeBinary/remove** These adapter calls currently use absolute paths; convert to vault-relative to prevent “file not found” errors when ImageMagick is unavailable and we keep PNG. ```diff - 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 { + if (plugin?.app) { + const pathUtils = new PathUtils(plugin.app); + const vaultBase = pathUtils.getVaultPath(); + const toRel = (p: string) => p.startsWith(vaultBase) ? p.substring(vaultBase.length).replace(/^[/\\]+/, '') : p; + const inputRel = toRel(inputImagePath); + const targetRel = toRel(pngFinalPath); + const content = await plugin.app.vault.adapter.readBinary(inputRel); + await plugin.app.vault.adapter.writeBinary(targetRel, content); + await plugin.app.vault.adapter.remove(inputRel); + } else { ``` <!-- 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 if (plugin?.app) { const pathUtils = new PathUtils(plugin.app); const vaultBase = pathUtils.getVaultPath(); const toRel = (p: string) => p.startsWith(vaultBase) ? p.substring(vaultBase.length).replace(/^[/\\]+/, '') : p; const inputRel = toRel(inputImagePath); const targetRel = toRel(pngFinalPath); const content = await plugin.app.vault.adapter.readBinary(inputRel); await plugin.app.vault.adapter.writeBinary(targetRel, content); await plugin.app.vault.adapter.remove(inputRel); } else { const fs = require('fs').promises; await fs.rename(inputImagePath, pngFinalPath); } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/ImageOptimizer.ts around lines 247 to 254, the adapter.readBinary/writeBinary/remove calls use absolute filesystem paths; change them to vault-relative paths by deriving the vault root prefix (e.g. via plugin.app.vault.getRoot().path or equivalent) and stripping that prefix from inputImagePath and pngFinalPath before passing to plugin.app.vault.adapter.readBinary/writeBinary/remove so the adapter receives paths relative to the vault; keep the fallback fs.rename for the non-plugin branch unchanged. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:33 +02:00

⚠️ Potential issue | 🔴 Critical

Also normalize to vault-relative in the “keep PNG” path

Same issue as above when not converting: read/write/remove expect vault-relative paths.

-				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 {
+				if (plugin?.app) {
+					const pathUtils = new PathUtils(plugin.app);
+					const vaultBase = pathUtils.getVaultPath();
+					const toRel = (p: string) => p.startsWith(vaultBase) ? p.substring(vaultBase.length).replace(/^[/\\]+/, '') : p;
+					const inputRel = toRel(inputImagePath);
+					const targetRel = toRel(finalOutputPath);
+					const content = await plugin.app.vault.adapter.readBinary(inputRel);
+					await plugin.app.vault.adapter.writeBinary(targetRel, content);
+					await plugin.app.vault.adapter.remove(inputRel);
+				} else {
📝 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.

				if (plugin?.app) {
					const pathUtils = new PathUtils(plugin.app);
					const vaultBase = pathUtils.getVaultPath();
					const toRel = (p: string) =>
						p.startsWith(vaultBase)
							? p.substring(vaultBase.length).replace(/^[/\\]+/, '')
							: p;
					const inputRel = toRel(inputImagePath);
					const targetRel = toRel(finalOutputPath);
					const content = await plugin.app.vault.adapter.readBinary(inputRel);
					await plugin.app.vault.adapter.writeBinary(targetRel, content);
					await plugin.app.vault.adapter.remove(inputRel);
				} else {
					const fs = require('fs').promises;
					await fs.rename(inputImagePath, finalOutputPath);
				}
🤖 Prompt for AI Agents
In src/converters/pdf/ImageOptimizer.ts around lines 260-266, the "keep PNG"
branch is using fs.rename with absolute/OS paths while the vault adapter methods
expect vault-relative paths; normalize both inputImagePath and finalOutputPath
to vault-relative (make them relative to the vault root) and then use the vault
adapter readBinary/writeBinary/remove sequence (or adapter rename if available)
the same way the conversion branch does, replacing the fs.rename call so all
file ops use vault-relative paths and the vault adapter.
_⚠️ Potential issue_ | _🔴 Critical_ **Also normalize to vault-relative in the “keep PNG” path** Same issue as above when not converting: read/write/remove expect vault-relative paths. ```diff - 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 { + if (plugin?.app) { + const pathUtils = new PathUtils(plugin.app); + const vaultBase = pathUtils.getVaultPath(); + const toRel = (p: string) => p.startsWith(vaultBase) ? p.substring(vaultBase.length).replace(/^[/\\]+/, '') : p; + const inputRel = toRel(inputImagePath); + const targetRel = toRel(finalOutputPath); + const content = await plugin.app.vault.adapter.readBinary(inputRel); + await plugin.app.vault.adapter.writeBinary(targetRel, content); + await plugin.app.vault.adapter.remove(inputRel); + } else { ``` <!-- 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 if (plugin?.app) { const pathUtils = new PathUtils(plugin.app); const vaultBase = pathUtils.getVaultPath(); const toRel = (p: string) => p.startsWith(vaultBase) ? p.substring(vaultBase.length).replace(/^[/\\]+/, '') : p; const inputRel = toRel(inputImagePath); const targetRel = toRel(finalOutputPath); const content = await plugin.app.vault.adapter.readBinary(inputRel); await plugin.app.vault.adapter.writeBinary(targetRel, content); await plugin.app.vault.adapter.remove(inputRel); } else { const fs = require('fs').promises; await fs.rename(inputImagePath, finalOutputPath); } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/pdf/ImageOptimizer.ts around lines 260-266, the "keep PNG" branch is using fs.rename with absolute/OS paths while the vault adapter methods expect vault-relative paths; normalize both inputImagePath and finalOutputPath to vault-relative (make them relative to the vault root) and then use the vault adapter readBinary/writeBinary/remove sequence (or adapter rename if available) the same way the conversion branch does, replacing the fs.rename call so all file ops use vault-relative paths and the vault adapter. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
@@ -69,3 +75,3 @@
return true;
}
return true;
} catch (error) {
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:34 +02:00

⚠️ 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 -->
@@ -103,3 +105,1 @@
return normalizedPath.startsWith(normalizedPluginDir) &&
(dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC));
const normalizedDirPath = normalizePath(dirPath);
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:34 +02:00

⚠️ 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 -->
coderabbitai[bot] (Migrated from github.com) commented 2025-09-25 16:51:34 +02:00

⚠️ Potential issue | 🔴 Critical

Fix: adapter.read requires vault-relative path (avoid passing absolute path)

templatePath is absolute; adapter.read expects vault-relative. Convert before reading to avoid failures.

-			if (exists) {
-				return await this.plugin.app.vault.adapter.read(templatePath);
-			}
+			if (exists) {
+				const vaultBasePath = this.pathUtils.getVaultPath();
+				let readTarget = templatePath;
+				if (templatePath.startsWith(vaultBasePath)) {
+					readTarget = templatePath.substring(vaultBasePath.length).replace(/^[/\\]+/, '');
+				}
+				return await this.plugin.app.vault.adapter.read(readTarget);
+			}
📝 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 exists = await this.pathUtils.fileExists(templatePath);
			if (exists) {
				const vaultBasePath = this.pathUtils.getVaultPath();
				let readTarget = templatePath;
				if (templatePath.startsWith(vaultBasePath)) {
					readTarget = templatePath
						.substring(vaultBasePath.length)
						.replace(/^[/\\]+/, '');
				}
				return await this.plugin.app.vault.adapter.read(readTarget);
			}
🤖 Prompt for AI Agents
In src/templates/TemplateManager.ts around lines 90 to 93, templatePath is an
absolute filesystem path but adapter.read expects a vault-relative path, so
convert the absolute path to a vault-relative path before calling adapter.read
(for example, compute the relative path by removing the vault root prefix or
using path.relative against the vault root/getRoot().path or an existing helper
on pathUtils), then pass that vault-relative path to
this.plugin.app.vault.adapter.read; keep the fileExists check as-is (it can
accept absolute) but ensure adapter.read receives the converted relative path.
_⚠️ Potential issue_ | _🔴 Critical_ **Fix: adapter.read requires vault-relative path (avoid passing absolute path)** `templatePath` is absolute; `adapter.read` expects vault-relative. Convert before reading to avoid failures. ```diff - if (exists) { - return await this.plugin.app.vault.adapter.read(templatePath); - } + if (exists) { + const vaultBasePath = this.pathUtils.getVaultPath(); + let readTarget = templatePath; + if (templatePath.startsWith(vaultBasePath)) { + readTarget = templatePath.substring(vaultBasePath.length).replace(/^[/\\]+/, ''); + } + return await this.plugin.app.vault.adapter.read(readTarget); + } ``` <!-- 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 exists = await this.pathUtils.fileExists(templatePath); if (exists) { const vaultBasePath = this.pathUtils.getVaultPath(); let readTarget = templatePath; if (templatePath.startsWith(vaultBasePath)) { readTarget = templatePath .substring(vaultBasePath.length) .replace(/^[/\\]+/, ''); } return await this.plugin.app.vault.adapter.read(readTarget); } ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/templates/TemplateManager.ts around lines 90 to 93, templatePath is an absolute filesystem path but adapter.read expects a vault-relative path, so convert the absolute path to a vault-relative path before calling adapter.read (for example, compute the relative path by removing the vault root prefix or using path.relative against the vault root/getRoot().path or an existing helper on pathUtils), then pass that vault-relative path to this.plugin.app.vault.adapter.read; keep the fileExists check as-is (it can accept absolute) but ensure adapter.read receives the converted relative path. ``` </details> <!-- fingerprinting:phantom:medusa:chinchilla --> <!-- This is an auto-generated comment by CodeRabbit -->
Sign in to join this conversation.