Update ESLint rules and resolve bot review feedback #8

Merged
AlexKucera merged 24 commits from obsidian-bot-review into master 2025-11-09 12:06:31 +01:00
37 changed files with 4314 additions and 872 deletions
Showing only changes of commit 2c4076f3c9 - Show all commits

No files matched your search

+82 -39
View File
@@ -1,57 +1,100 @@
// @ts-check
import eslint from '@eslint/js';
import globals from 'globals';
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import obsidianmd from 'eslint-plugin-obsidianmd';
import importPlugin from 'eslint-plugin-import';
import globals from 'globals';
export default tseslint.config(
// Apply ESLint recommended rules
eslint.configs.recommended,
// Apply TypeScript-ESLint recommended rules
...tseslint.configs.recommended,
// Base JavaScript recommended rules
js.configs.recommended,
// TypeScript recommended type-checked rules
...tseslint.configs.recommendedTypeChecked,
// Obsidian-specific configuration
{
// Configure language options
plugins: {
obsidianmd: obsidianmd,
import: importPlugin,
},
languageOptions: {
globals: {
...globals.node,
...globals.es2022,
...globals.browser,
NodeJS: 'readonly', // TypeScript global namespace
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2022,
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
// Configure files to lint
files: ['**/*.ts', '**/*.js', 'main.ts'],
// Configure rules - incorporating Obsidian sample plugin settings
// Apply Obsidian plugin recommended rules (manually specified)
rules: {
// Disable base ESLint no-unused-vars in favor of TypeScript version
// Obsidian command rules
'obsidianmd/commands/no-command-in-command-id': 'error',
'obsidianmd/commands/no-command-in-command-name': 'error',
'obsidianmd/commands/no-default-hotkeys': 'error',
'obsidianmd/commands/no-plugin-id-in-command-id': 'error',
'obsidianmd/commands/no-plugin-name-in-command-name': 'error',
coderabbitai[bot] commented 2025-11-05 13:54:25 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Modern ESLint configuration pattern.

The configuration correctly uses projectService with import.meta.dirname for TypeScript parser configuration. Note that import.meta.dirname requires Node.js 20.11+ or a polyfill in earlier versions.

Verify that the project's minimum Node.js version supports import.meta.dirname:


🏁 Script executed:

#!/bin/bash
# Check package.json for Node.js version requirements
if [ -f package.json ]; then
    echo "=== Checking Node.js version requirements ==="
    jq -r '.engines.node // "Not specified"' package.json
fi

Length of output: 59


🏁 Script executed:

#!/bin/bash
# Check for Node.js version specification files
echo "=== Checking for version specification files ==="
fd -e nvmrc -e tool-versions | head -20

echo ""
echo "=== Checking README for Node.js version info ==="
if [ -f README.md ]; then
    grep -i "node.*version\|node.*20\|node.*18" README.md | head -10
fi

echo ""
echo "=== Checking GitHub Actions or CI configs for Node.js version ==="
fd -e yml -e yaml | xargs grep -l "node-version\|node_version" 2>/dev/null | head -5

Length of output: 210


Node.js version incompatibility with import.meta.dirname.

The code uses import.meta.dirname (line 31), which requires Node.js 20.11+ or 18.20+. However, the README specifies "Node.js: Version 16+" for development, creating a compatibility gap. Developers on Node.js 16 or 17.x versions cannot run this configuration.

Update the minimum Node.js version requirement to 18.20+ or 20.11+ in README.md and package.json, or replace import.meta.dirname with an alternative that supports Node.js 16+ (e.g., dirname(fileURLToPath(import.meta.url))).

🤖 Prompt for AI Agents
In eslint.config.mjs around lines 18 to 33 the config uses import.meta.dirname
which requires Node 18.20+/20.11+, causing incompatibility with the project's
stated minimum Node 16; either update the project's minimum Node version in
README.md and package.json to 18.20+ (or 20.11+) so import.meta.dirname is
supported, or replace import.meta.dirname with a Node-16-compatible alternative:
import { fileURLToPath } from 'url' and import { dirname } from 'path' then
derive tsconfigRootDir via dirname(fileURLToPath(import.meta.url)); make the
chosen change consistently (update docs, package.json engines if bumping Node)
and run lint to verify the config loads correctly.
_⚠️ Potential issue_ | _🔴 Critical_ <details> <summary>🧩 Analysis chain</summary> **Modern ESLint configuration pattern.** The configuration correctly uses `projectService` with `import.meta.dirname` for TypeScript parser configuration. Note that `import.meta.dirname` requires Node.js 20.11+ or a polyfill in earlier versions. Verify that the project's minimum Node.js version supports `import.meta.dirname`: --- 🏁 Script executed: ```shell #!/bin/bash # Check package.json for Node.js version requirements if [ -f package.json ]; then echo "=== Checking Node.js version requirements ===" jq -r '.engines.node // "Not specified"' package.json fi ``` Length of output: 59 --- 🏁 Script executed: ```shell #!/bin/bash # Check for Node.js version specification files echo "=== Checking for version specification files ===" fd -e nvmrc -e tool-versions | head -20 echo "" echo "=== Checking README for Node.js version info ===" if [ -f README.md ]; then grep -i "node.*version\|node.*20\|node.*18" README.md | head -10 fi echo "" echo "=== Checking GitHub Actions or CI configs for Node.js version ===" fd -e yml -e yaml | xargs grep -l "node-version\|node_version" 2>/dev/null | head -5 ``` Length of output: 210 --- </details> **Node.js version incompatibility with `import.meta.dirname`.** The code uses `import.meta.dirname` (line 31), which requires Node.js 20.11+ or 18.20+. However, the README specifies "Node.js: Version 16+" for development, creating a compatibility gap. Developers on Node.js 16 or 17.x versions cannot run this configuration. Update the minimum Node.js version requirement to 18.20+ or 20.11+ in README.md and package.json, or replace `import.meta.dirname` with an alternative that supports Node.js 16+ (e.g., `dirname(fileURLToPath(import.meta.url))`). <details> <summary>🤖 Prompt for AI Agents</summary> ``` In eslint.config.mjs around lines 18 to 33 the config uses import.meta.dirname which requires Node 18.20+/20.11+, causing incompatibility with the project's stated minimum Node 16; either update the project's minimum Node version in README.md and package.json to 18.20+ (or 20.11+) so import.meta.dirname is supported, or replace import.meta.dirname with a Node-16-compatible alternative: import { fileURLToPath } from 'url' and import { dirname } from 'path' then derive tsconfigRootDir via dirname(fileURLToPath(import.meta.url)); make the chosen change consistently (update docs, package.json engines if bumping Node) and run lint to verify the config loads correctly. ``` </details> <!-- This is an auto-generated comment by CodeRabbit -->
// Settings tab rules
'obsidianmd/settings-tab/no-manual-html-headings': 'error',
'obsidianmd/settings-tab/no-problematic-settings-headings': 'error',
// Other Obsidian rules
'obsidianmd/vault/iterate': 'error',
'obsidianmd/detach-leaves': 'error',
'obsidianmd/hardcoded-config-path': 'error',
'obsidianmd/no-forbidden-elements': 'error',
'obsidianmd/no-plugin-as-component': 'error',
'obsidianmd/no-sample-code': 'error',
'obsidianmd/no-tfile-tfolder-cast': 'error',
'obsidianmd/no-view-references-in-plugin': 'error',
'obsidianmd/no-static-styles-assignment': 'error',
'obsidianmd/object-assign': 'error',
'obsidianmd/platform': 'error',
'obsidianmd/prefer-file-manager-trash-file': 'warn',
'obsidianmd/prefer-abstract-input-suggest': 'error',
'obsidianmd/regex-lookbehind': 'error',
'obsidianmd/sample-names': 'error',
'obsidianmd/validate-manifest': 'error',
'obsidianmd/validate-license': 'error',
'obsidianmd/ui/sentence-case': ['error', { enforceCamelCaseLower: true }],
// General ESLint rules from Obsidian recommended
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
// Allow @ts-ignore comments (useful for Obsidian API quirks)
'@typescript-eslint/ban-ts-comment': 'off',
// Allow prototype builtins usage
'no-prototype-builtins': 'off',
// Allow empty functions (common in plugin architecture)
'@typescript-eslint/no-empty-function': 'off',
// Allow require() imports (Node.js environment with mixed modules)
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-var-requires': 'off',
// Obsidian plugins often use 'any' type for API flexibility
'@typescript-eslint/no-explicit-any': 'warn',
// Allow lexical declarations in case blocks
'no-case-declarations': 'off',
// Prefer const is good but not critical for existing code
'prefer-const': 'warn',
'no-self-compare': 'warn',
'no-eval': 'error',
'no-implied-eval': 'error',
'prefer-const': 'off',
'no-implicit-globals': 'error',
'no-console': ['error', { allow: ['warn', 'error', 'debug'] }],
'no-alert': 'error',
'no-undef': 'error',
// TypeScript rules from Obsidian recommended
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/no-explicit-any': ['error', { fixToUnknown: true }],
// Downgrade strict type checking rules to warnings
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-unsafe-call': 'warn',
'@typescript-eslint/no-unsafe-return': 'warn',
// Unused vars with underscore prefix
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
// Import rules
'import/no-extraneous-dependencies': 'error',
},
},
{
@@ -65,4 +108,4 @@ export default tseslint.config(
'coverage/**',
],
}
);
);
+4 -4
View File
@@ -11,6 +11,7 @@ import {
Notice,
MarkdownView
} from 'obsidian';
import { shell } from 'electron';
coderabbitai[bot] commented 2025-11-08 19:27:33 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🔴 Critical

Avoid top-level Electron import

Importing electron at module scope breaks the plugin on mobile builds (and any runtime without Electron) because the module cannot be resolved during load. Keep the dynamic require inside openPDF instead.

-import { shell } from 'electron';
@@
 	openPDF(pdfPath: string): void {
-		void shell.openPath(pdfPath);
+		// eslint-disable-next-line @typescript-eslint/no-var-requires
+		const { shell } = require('electron') as typeof import('electron');
+		void shell.openPath(pdfPath);
 	}

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

🤖 Prompt for AI Agents
In main.ts around lines 14-15, importing { shell } from 'electron' at module
scope breaks non-Electron targets; move the import into the openPDF function as
a dynamic require. Replace the top-level import by removing it, and inside
openPDF use const { shell } = require('electron') (or a try/catch around require
to handle non-Electron runtimes) so the module is only loaded at call time and
does not prevent mobile builds from loading the module.
_⚠️ Potential issue_ | _🔴 Critical_ **Avoid top-level Electron import** Importing `electron` at module scope breaks the plugin on mobile builds (and any runtime without Electron) because the module cannot be resolved during load. Keep the dynamic `require` inside `openPDF` instead. ```diff -import { shell } from 'electron'; @@ openPDF(pdfPath: string): void { - void shell.openPath(pdfPath); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { shell } = require('electron') as typeof import('electron'); + void shell.openPath(pdfPath); } ``` > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In main.ts around lines 14-15, importing { shell } from 'electron' at module scope breaks non-Electron targets; move the import into the openPDF function as a dynamic require. Replace the top-level import by removing it, and inside openPDF use const { shell } = require('electron') (or a try/catch around require to handle non-Electron runtimes) so the module is only loaded at call time and does not prevent mobile builds from loading the module. ``` </details> <!-- fingerprinting:phantom:medusa:sabertoothed --> <!-- This is an auto-generated reply by CodeRabbit -->
AlexKucera commented 2025-11-08 19:50:32 +01:00 (Migrated from github.com)
Review

@coderabbitai this is a Desktop only release. so Electron is no issue here.

@coderabbitai this is a Desktop only release. so Electron is no issue here.
coderabbitai[bot] commented 2025-11-08 19:51:01 +01:00 (Migrated from github.com)
Review

@AlexKucera, understood! Since this plugin is desktop-only, the top-level electron import is perfectly fine. Thank you for clarifying the deployment target.


✏️ Learnings added
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: main.ts:14-15
Timestamp: 2025-11-08T18:51:00.473Z
Learning: The obsidian-typst-pdf-export plugin is a desktop-only release and does not target mobile platforms, so Electron dependencies and desktop-specific APIs can be used without mobile compatibility concerns.

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.


🧠 Learnings used
Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian)

Learnt from: CR
Repo: AlexKucera/obsidian-typst-pdf-export PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-25T14:48:20.040Z
Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand)
@AlexKucera, understood! Since this plugin is desktop-only, the top-level `electron` import is perfectly fine. Thank you for clarifying the deployment target. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera Repo: AlexKucera/obsidian-typst-pdf-export PR: 8 File: main.ts:14-15 Timestamp: 2025-11-08T18:51:00.473Z Learning: The obsidian-typst-pdf-export plugin is a desktop-only release and does not target mobile platforms, so Electron dependencies and desktop-specific APIs can be used without mobile compatibility concerns. ``` > 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> --- <details> <summary>🧠 Learnings used</summary> ``` Learnt from: CR Repo: AlexKucera/obsidian-typst-pdf-export PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-25T14:48:20.040Z Learning: Applies to main.js : Build must produce a single bundled main.js at the plugin root (loaded by Obsidian) ``` --- ``` Learnt from: CR Repo: AlexKucera/obsidian-typst-pdf-export PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-25T14:48:20.040Z Learning: Applies to src/main.ts : Plugin entry point is main.ts under src/, focused on lifecycle only (onload, onunload, addCommand) ``` </details> <!-- This is an auto-generated reply by CodeRabbit -->
import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS } from './src/core/settings';
import { DependencyChecker } from './src/core/DependencyChecker';
@@ -177,8 +178,8 @@ export class obsidianTypstPDFExport extends Plugin {
);
}
async checkDependenciesAsync(): Promise<void> {
return DependencyChecker.checkDependenciesAsync(
checkDependenciesAsync(): void {
DependencyChecker.checkDependenciesAsync(
this.settings.pandocPath,
this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath,
@@ -212,8 +213,7 @@ export class obsidianTypstPDFExport extends Plugin {
* Open a PDF file in the default viewer
*/
openPDF(pdfPath: string): void {
const { shell } = require('electron');
shell.openPath(pdfPath);
void shell.openPath(pdfPath);
}
async loadSettings() {
+194
View File
@@ -0,0 +1,194 @@
### Required
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L81-L81)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/mmandRegistry.ts#L37-L37)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L23-L23)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L38-L38)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L56-L56)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L325-L325)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L31-L31)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L50-L50)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L57-L57)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L65-L65)
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L67-L67)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L80-L80)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L82-L82)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L94-L94)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L95-L95)
[16](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L97-L97)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L134-L134)
[18](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L138-L138)
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L160-L160)
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L179-L179)
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L182-L182)
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L232-L232)
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L138-L138)
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L222-L222)
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/BehaviorSection.ts#L14-L14)
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/neralSection.ts#L21-L21)
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L75-L75)
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L78-L78)
[30](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/youtSection.ts#L16-L16)
[31](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L16-L16)
[32](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L72-L72)
[33](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L166-L166)
[34](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L167-L167)
[35](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L174-L174)
[36](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L194-L194)
[37](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L195-L195)
[38](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L199-L199)
[39](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L200-L200)
[40](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L201-L201)
Use sentence case for UI text.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L215-L215)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/naryLocator.ts#L154-L154)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L38-L38)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L115-L115)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L183-L183)
[6](https://github.com/exKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L61-L61)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L111-L111)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L236-L236)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L252-L252)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L264-L264)
[11](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L114-L114)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L115-L115)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L35-L35)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L46-L46)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
[16](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
[18](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/eprocessors/FrontmatterProcessor.ts#L208-L208)
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L51-L51)
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ecutableChecker.ts#L128-L128)
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L158-L158)
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L215-L215)
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/PathUtils.ts#L115-L115)
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EmbedProcessor.ts#L164-L164)
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/bedProcessor.ts#L165-L165)
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/FontManager.ts#L19-L19)
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PathResolver.ts#L29-L29)
A `require()` style import is forbidden.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/MarkdownPreprocessor.ts#L117-L117)
Async method 'process' has no 'await' expression.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L138-L138)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/plugin/CommandRegistry.ts#L21-L21)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L30-L30)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L39-L39)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L26-L26)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L41-L41)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/entHandlers.ts#L59-L59)
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L68-L68)
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L95-L95)
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L104-L104)
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L56-L56)
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/uginLifecycle.ts#L59-L59)
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L72-L80)
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L88-L101)
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L86-L86)
[16](https://github.com/AlexKucerabsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L122-L122)
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L19-L19)
Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L180-L180)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/converters/PandocTypstConverter.ts#L187-L187)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/BinaryLocator.ts#L33-L33)
Obsidian's configuration folder is not necessarily `.obsidian`, can be configured by the user. Use `Vault#configDir` to get the current value
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L35-L35)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
[6](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L208-L208)
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
'js-yaml' should be listed in the project's dependencies. n 'npm i -S js-yaml' to add it
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L49-L49)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L50-L50)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L155-L155)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L156-L156)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExportErrorHandler.ts#L64-L64)
Unexpected console statement. Only these console methods are allowed: warn, error, debug.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L275-L275)
'value' will use Object's default stringification format ('[object Object]') when ringified.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/DependencyChecker.ts#L122-L122)
Static async method 'checkDependenciesAsync' has no 'await' expression.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ModalSettingsHelper.ts#L72-L72)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/dal/sections/PageSetupSection.ts#L60-L60)
The two values in this comparison do not have a shared enum type.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/SecurityUtils.ts#L56-L56)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/curityUtils.ts#L117-L117)
Unexpected undescribed directive comment. Include descriptions to explain why the comment is necessary.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L51-L51)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/portOrchestrator.ts#L322-L322)
A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object. Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an intended `this` value. If a function does not access `this`, it can be annotated with `this: void`.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L89-L91)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ugin/ExportOrchestrator.ts#L124-L126)
Promise returned in function argument where a void return was expected.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L160-L160)
`noticeEl` is deprecated. Use `messageEl` instead
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L31-L31)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L50-L50)
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L134-L134)
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L232-L232)
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L366-L366)
For a consistent UI use `new Setting(containerEl).setName(...).setHeading()` instead of creating HTML heading elements directly.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/templates/TemplateManager.ts#L132-L132)
Unexpected lexical declaration in case block.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L50-L50)
Promise-returning function provided to property where a void return was expected.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L152-L152)
Unexpected `await` of a non-Promise (non-"Thenable") value.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L260-L260)
Creating and attaching "style" elements is not allowed. For loading CSS, use a "styles.css" file instead, which sidian loads for you.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/state/ModalState.ts#L192-L192)
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/uiodal/state/ModalState.ts#L203-L203)
Unexpected use of 'localStorage'. Prefer `App#saveLocalStorage` / `App#loadLocalStorage` functions to write / read localStorage data that's unique to a vault.
### Optional
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L92-L92)
'_result' is assigned a value but never used.
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L124-L124)
'_progressPercent' is assigned a value but never used.
+3637 -455
View File
File diff suppressed because it is too large. Load diff
+7 -2
View File
@@ -27,14 +27,19 @@
"devDependencies": {
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.34.0",
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.19.24",
"@typescript-eslint/eslint-plugin": "5.29.0",
"@typescript-eslint/parser": "5.29.0",
"@typescript-eslint/eslint-plugin": "^8.46.3",
"@typescript-eslint/parser": "^8.46.3",
"@typescript-eslint/utils": "^8.46.3",
"@vitest/coverage-v8": "^4.0.6",
"@vitest/ui": "^4.0.6",
"archiver": "^7.0.1",
"builtin-modules": "3.3.0",
"electron": "^33.3.0",
"esbuild": "0.17.3",
"eslint": "^9.39.1",
"eslint-plugin-obsidianmd": "^0.1.8",
"globals": "^16.3.0",
"happy-dom": "^20.0.10",
"obsidian": "latest",
+7 -8
View File
@@ -202,7 +202,7 @@ export interface MarkdownPreprocessorConfig {
*
* // Process markdown
* const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]';
* const result = await preprocessor.process(obsidianMarkdown);
* const result = preprocessor.process(obsidianMarkdown);
*
* console.log(result.content); // Standard markdown
* console.log(result.metadata.imageEmbeds); // Image processing info
@@ -218,7 +218,7 @@ export interface MarkdownPreprocessorConfig {
* });
*
* // Process with new configuration
* const newResult = await preprocessor.process(markdown);
* const newResult = preprocessor.process(markdown);
* ```
*/
export class MarkdownPreprocessor {
@@ -268,7 +268,6 @@ export class MarkdownPreprocessor {
* in the correct order, aggregates metadata from each stage, and returns a complete
* result with processed content and comprehensive metadata.
*
* The method is async to support future extensions (though current processors are sync).
* Processing is stateless - each call operates independently on the provided content.
*
* Processing Order (critical for avoiding conflicts):
@@ -300,7 +299,7 @@ export class MarkdownPreprocessor {
* Callout: > [!note] This is important
* `;
*
* const result = await preprocessor.process(markdown);
* const result = preprocessor.process(markdown);
*
* // Check for errors
* if (result.errors.length > 0) {
@@ -320,7 +319,7 @@ export class MarkdownPreprocessor {
* ```typescript
* // Handle remote images
* const markdown = '![Remote](https://example.com/image.png)';
* const result = await preprocessor.process(markdown);
* const result = preprocessor.process(markdown);
*
* // Remote images are queued for download
* result.metadata.imageEmbeds.forEach(embed => {
@@ -329,7 +328,7 @@ export class MarkdownPreprocessor {
* });
* ```
*/
public async process(content: string): Promise<PreprocessingResult> {
public process(content: string): PreprocessingResult {
const result: PreprocessingResult = {
content: content,
metadata: {
@@ -506,7 +505,7 @@ export class MarkdownPreprocessor {
* });
*
* // Process note with web-friendly links
* const result = await preprocessor.process(markdown);
* const result = preprocessor.process(markdown);
* // Links will use the new base URL
* ```
*
@@ -521,7 +520,7 @@ export class MarkdownPreprocessor {
* });
*
* // Process with HTML-style links
* const result = await preprocessor.process(markdown);
* const result = preprocessor.process(markdown);
* // [[note]] becomes [note](note.html)
* ```
*
+3 -3
View File
@@ -299,7 +299,7 @@ export class PandocTypstConverter {
this.processCleanupHandler = () => {
coderabbitai[bot] commented 2025-11-05 13:54:25 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Fire-and-forget cleanup won't complete on process termination.

Process event handlers like 'exit', 'SIGINT', and 'SIGTERM' are synchronous and terminate immediately without waiting for promises. Calling void this.cleanup() means the async file removal operations in cleanup() (line 340) will likely not complete before the process exits, leaving temporary files behind.

Consider using Obsidian's plugin lifecycle methods (onunload) for cleanup instead of Node.js process events, as plugin unload hooks are better suited for async cleanup operations.

Apply this diff to document the limitation:

 		this.processCleanupHandler = () => {
 			// Only cleanup if not already disposed to avoid double-cleanup
 			if (!this.isDisposed) {
+				// Note: Async cleanup may not complete before process exit
 				void this.cleanup();
 			}
 		};
🤖 Prompt for AI Agents
In src/converters/PandocTypstConverter.ts around line 302, the code calls void
this.cleanup() from process event handlers which is fire-and-forget and will not
complete on process termination; replace these process-level handlers with the
plugin lifecycle unload hook (onunload) so cleanup() can be awaited and finish
async file removals, or if you must keep process handlers, make them synchronous
by performing sync removal or spawn a blocking cleanup before exit; remove or
stop using void this.cleanup() in process events and register/await cleanup
inside the plugin's onunload handler instead.

✅ Addressed in commits f0daebc to c1c02ee

_⚠️ Potential issue_ | _🟠 Major_ **Fire-and-forget cleanup won't complete on process termination.** Process event handlers like 'exit', 'SIGINT', and 'SIGTERM' are synchronous and terminate immediately without waiting for promises. Calling `void this.cleanup()` means the async file removal operations in `cleanup()` (line 340) will likely not complete before the process exits, leaving temporary files behind. Consider using Obsidian's plugin lifecycle methods (`onunload`) for cleanup instead of Node.js process events, as plugin unload hooks are better suited for async cleanup operations. Apply this diff to document the limitation: ```diff this.processCleanupHandler = () => { // Only cleanup if not already disposed to avoid double-cleanup if (!this.isDisposed) { + // Note: Async cleanup may not complete before process exit void this.cleanup(); } }; ``` <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/PandocTypstConverter.ts around line 302, the code calls void this.cleanup() from process event handlers which is fire-and-forget and will not complete on process termination; replace these process-level handlers with the plugin lifecycle unload hook (onunload) so cleanup() can be awaited and finish async file removals, or if you must keep process handlers, make them synchronous by performing sync removal or spawn a blocking cleanup before exit; remove or stop using void this.cleanup() in process events and register/await cleanup inside the plugin's onunload handler instead. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee
// Only cleanup if not already disposed to avoid double-cleanup
if (!this.isDisposed) {
this.cleanup();
void this.cleanup();
}
};
@@ -364,14 +364,14 @@ export class PandocTypstConverter {
if (!this.tempDir) {
if (this.pandocOptions.vaultBasePath) {
// Use TempDirectoryManager for plugin temp directories
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
const configDir = this.plugin?.app?.vault?.configDir;
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
this.tempDir = await tempManager.ensureTempDir('pandoc');
} else {
// Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
const pathUtils = new PathUtils(this.plugin.app);
const vaultPath = pathUtils.getVaultPath();
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
const configDir = this.plugin?.app?.vault?.configDir;
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
this.tempDir = await tempManager.ensureTempDir('pandoc');
}
+5 -2
View File
@@ -3,6 +3,7 @@
* Handles discovery of pdf2img and other CLI tools in the Obsidian environment.
*/
import { promises as fs } from 'fs';
import * as path from 'path';
import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils';
@@ -30,7 +31,10 @@ export class BinaryLocator {
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
// Try multiple strategies to find the plugin directory
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
const configDir = plugin?.app.vault.configDir || '.obsidian';
const configDir = plugin?.app.vault.configDir;
if (!configDir) {
throw new Error('Unable to determine Obsidian configuration directory');
}
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
// Find the first directory that exists and has node_modules
@@ -154,7 +158,6 @@ export class BinaryLocator {
try {
if (!plugin?.app) {
// This should not happen in normal plugin operation, but provide fallback
const fs = require('fs').promises;
await fs.access(binaryPath);
return true;
}
+2 -4
View File
@@ -3,6 +3,7 @@
* Handles filename pattern matching when pdf2img generates files with different names.
*/
import { promises as fs } from 'fs';
import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
@@ -35,7 +36,6 @@ export class FileDiscovery {
if (!plugin?.app) {
// Fallback to path for external tool output directories
const expectedOutputPath = path.join(outputDir, expectedFileName);
const fs = require('fs').promises;
try {
await fs.access(expectedOutputPath);
return {
@@ -112,8 +112,7 @@ export class FileDiscovery {
files = dirList.files.map(f => path.basename(f));
} else {
// Use filesystem fallback for absolute/external paths
const fs = require('fs').promises;
files = await fs.readdir(outputDir);
files = await fs.readdir(outputDir);
}
// Look for any image files that might match
@@ -180,7 +179,6 @@ export class FileDiscovery {
expectedOutputPath: string
): Promise<FileDiscoveryResult> {
try {
const fs = require('fs').promises;
// Debug: List what files are actually in the output directory
const files = await fs.readdir(outputDir);
+2 -5
View File
@@ -3,6 +3,8 @@
* Handles format conversion, quality management, and dimension detection.
*/
import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import * as path from 'path';
import { PathUtils } from '../../core/PathUtils';
import type { obsidianTypstPDFExport } from '../../../main';
@@ -58,7 +60,6 @@ export class ImageOptimizer {
quality: number = 90
): Promise<{success: boolean; error?: string}> {
try {
const { spawn } = require('child_process');
// Use ImageMagick to convert PNG to JPEG
const convertProcess = spawn('magick', [
@@ -108,7 +109,6 @@ export class ImageOptimizer {
fallbackDimensions: ImageDimensions = { width: 800, height: 600 }
): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> {
try {
const { spawn } = require('child_process');
// Use ImageMagick identify to get image dimensions
const identifyProcess = spawn('magick', [
@@ -233,7 +233,6 @@ export class ImageOptimizer {
await plugin.app.vault.adapter.remove(relativePath);
} else {
const fs = require('fs').promises;
await fs.unlink(inputImagePath);
}
} catch (unlinkError) {
1
@@ -249,7 +248,6 @@ export class ImageOptimizer {
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content);
await plugin.app.vault.adapter.remove(inputImagePath);
} else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, pngFinalPath);
}
actualImagePath = pngFinalPath;
@@ -261,7 +259,6 @@ export class ImageOptimizer {
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content);
await plugin.app.vault.adapter.remove(inputImagePath);
} else {
const fs = require('fs').promises;
await fs.rename(inputImagePath, finalOutputPath);
}
actualImagePath = finalOutputPath;
+2 -2
View File
@@ -3,6 +3,8 @@
* Executes external pdf2img binary to convert PDF pages to images.
*/
import { exec } from 'child_process';
import { promisify } from 'util';
import * as path from 'path';
import { BinaryLocator } from './BinaryLocator';
import { EnvironmentUtils } from './EnvironmentUtils';
@@ -111,8 +113,6 @@ export class PdfCliExecutor {
plugin?: obsidianTypstPDFExport
): Promise<PdfCliResult> {
try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
// Get augmented environment for CLI execution
@@ -3,6 +3,8 @@
* Extracted from MarkdownPreprocessor for better code organization
*/
import * as yaml from 'js-yaml';
import matter from 'gray-matter';
import { PreprocessingResult } from '../MarkdownPreprocessor';
export interface FrontmatterProcessorConfig {
@@ -32,7 +34,6 @@ export class FrontmatterProcessor {
if (!this.FRONTMATTER_PATTERN.test(content)) {
// No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle };
@@ -43,11 +44,10 @@ export class FrontmatterProcessor {
}
coderabbitai[bot] commented 2025-11-05 13:54:25 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Remove raw-content logging from diagnostics.
These new console.debug/console.error statements dump the first 200–500 characters of user notes directly to the developer console. Even in debug builds this is sensitive content (frontmatter often includes titles, tags, authors, etc.), so shipping this logging materially increases the risk of leaking private vault data. Please strip the raw-content logging (or gate it behind an explicit opt-in) before release.

Also applies to: 152-154

🤖 Prompt for AI Agents
In src/converters/preprocessors/FrontmatterProcessor.ts around lines 49-51 (and
likewise remove similar logging at 152-154), remove the console.debug calls that
print the raw content snippet to avoid leaking sensitive user data; instead
either delete those debug statements entirely or replace them with non-sensitive
diagnostics (e.g., log only that frontmatter was detected and the content length
or a redacted/hashed preview), and if you need full-content logging keep it
strictly behind an explicit opt-in debug flag or environment variable checked
before printing.

✅ Addressed in commits f0daebc to c1c02ee

_⚠️ Potential issue_ | _🟠 Major_ **Remove raw-content logging from diagnostics.** These new `console.debug`/`console.error` statements dump the first 200–500 characters of user notes directly to the developer console. Even in debug builds this is sensitive content (frontmatter often includes titles, tags, authors, etc.), so shipping this logging materially increases the risk of leaking private vault data. Please strip the raw-content logging (or gate it behind an explicit opt-in) before release. Also applies to: 152-154 <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/preprocessors/FrontmatterProcessor.ts around lines 49-51 (and likewise remove similar logging at 152-154), remove the console.debug calls that print the raw content snippet to avoid leaking sensitive user data; instead either delete those debug statements entirely or replace them with non-sensitive diagnostics (e.g., log only that frontmatter was detected and the content length or a redacted/hashed preview), and if you need full-content logging keep it strictly behind an explicit opt-in debug flag or environment variable checked before printing. ``` </details> <!-- fingerprinting:phantom:medusa:sabertoothed --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee
// Use gray-matter for robust frontmatter parsing
const matter = require('gray-matter');
// Add debugging to see what's being parsed
console.log('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
console.log('First 200 chars:', content.substring(0, 200));
console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
console.debug('First 200 chars:', content.substring(0, 200));
const parsed = matter(content);
@@ -100,7 +100,6 @@ export class FrontmatterProcessor {
if (this.preserveFrontmatter) {
// Keep the frontmatter in the content, but reconstruct it with the modified title
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(finalFrontmatter);
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
@@ -115,8 +114,7 @@ export class FrontmatterProcessor {
// Return content without frontmatter, but add title as frontmatter for Pandoc
let processedContent: string;
coderabbitai[bot] commented 2025-11-09 10:57:56 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟡 Minor

Fix indentation inconsistencies.

These lines appear to have extra leading whitespace. Ensure consistent indentation throughout the file.

Apply this diff to fix line 118:

 			if (this.noteTitle) {
-					const titleFrontmatter = yaml.dump({ title: this.noteTitle });
+				const titleFrontmatter = yaml.dump({ title: this.noteTitle });
 				processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;

Apply similar fixes to lines 185 and 204:

 				if (this.noteTitle) {
-							const newFrontmatter = yaml.dump(frontmatter);
+					const newFrontmatter = yaml.dump(frontmatter);
 					let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
 				if (this.noteTitle) {
-							const titleFrontmatter = yaml.dump({ title: this.noteTitle });
+					const titleFrontmatter = yaml.dump({ title: this.noteTitle });
 					let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);

Also applies to: 185-185, 204-204

🤖 Prompt for AI Agents
In src/converters/preprocessors/FrontmatterProcessor.ts around lines 118, 185
and 204, several lines have extra leading whitespace causing inconsistent
indentation; remove the extra leading spaces on each of the affected lines so
they align with the surrounding block indentation (match the same indent level
as neighboring statements), keeping existing spacing within the line intact and
ensuring the file's indentation style remains consistent.

✅ Addressed in commit efbff4e

_⚠️ Potential issue_ | _🟡 Minor_ **Fix indentation inconsistencies.** These lines appear to have extra leading whitespace. Ensure consistent indentation throughout the file. Apply this diff to fix line 118: ```diff if (this.noteTitle) { - const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`; ``` Apply similar fixes to lines 185 and 204: ```diff if (this.noteTitle) { - const newFrontmatter = yaml.dump(frontmatter); + const newFrontmatter = yaml.dump(frontmatter); let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); ``` ```diff if (this.noteTitle) { - const titleFrontmatter = yaml.dump({ title: this.noteTitle }); + const titleFrontmatter = yaml.dump({ title: this.noteTitle }); let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); ``` Also applies to: 185-185, 204-204 <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/converters/preprocessors/FrontmatterProcessor.ts around lines 118, 185 and 204, several lines have extra leading whitespace causing inconsistent indentation; remove the extra leading spaces on each of the affected lines so they align with the surrounding block indentation (match the same indent level as neighboring statements), keeping existing spacing within the line intact and ensuring the file's indentation style remains consistent. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit efbff4e
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
} else {
processedContent = parsed.content;
@@ -141,7 +139,6 @@ export class FrontmatterProcessor {
} else {
// No frontmatter found - add title frontmatter if we have a noteTitle
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle };
@@ -152,8 +149,8 @@ export class FrontmatterProcessor {
}
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.log('FrontmatterProcessor: gray-matter failed with error:', errorMessage);
console.log('Content being parsed (first 500 chars):', content.substring(0, 500));
console.error('FrontmatterProcessor: gray-matter failed with error:', errorMessage);
console.error('Content being parsed (first 500 chars):', content.substring(0, 500));
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
// Fallback to simple regex-based parsing
@@ -185,8 +182,7 @@ export class FrontmatterProcessor {
if (this.preserveFrontmatter) {
// Reconstruct frontmatter with modified title
if (this.noteTitle) {
const yaml = require('js-yaml');
const newFrontmatter = yaml.dump(frontmatter);
const newFrontmatter = yaml.dump(frontmatter);
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
// Add printed frontmatter if requested
@@ -205,8 +201,7 @@ export class FrontmatterProcessor {
} else {
// Add title as frontmatter for Pandoc even when not preserving original
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
// Add printed frontmatter if requested
@@ -230,7 +225,6 @@ export class FrontmatterProcessor {
} else {
// No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter
if (this.noteTitle) {
const yaml = require('js-yaml');
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
result.metadata.title = this.noteTitle;
result.metadata.frontmatter = { title: this.noteTitle };
@@ -265,13 +259,18 @@ export class FrontmatterProcessor {
if (Array.isArray(value)) {
// For arrays, put each item on its own line if there are many items
if (value.length > 3) {
formattedValue = '\n\n' + value.map(item => `- ${item}`).join('\n') + '\n';
formattedValue = '\n\n' + value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : String(item)
).join('\n').split('\n').map(line => `- ${line}`).join('\n') + '\n';
} else {
formattedValue = value.join(', ');
formattedValue = value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : String(item)
).join(', ');
}
} else if (typeof value === 'object') {
} else if (typeof value === 'object' && value !== null) {
formattedValue = JSON.stringify(value);
} else {
} else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
// Handle primitive values
const valueStr = String(value);
// If the value is very long (like email lists), break it up
if (valueStr.length > 80 && valueStr.includes(',')) {
@@ -308,8 +307,11 @@ export class FrontmatterProcessor {
} else {
formattedValue = valueStr;
}
} else {
// Handle null, undefined, or any other unexpected types
formattedValue = '';
}
// Add line break after the property label, then the value
if (formattedValue.startsWith('\n')) {
// Value already starts with newline (like lists), so just add the label
+2 -2
View File
@@ -348,12 +348,12 @@ ${dependencyResult.allAvailable
* // Run 'Check Dependencies' command for details."
* ```
*/
public static async checkDependenciesAsync(
public static checkDependenciesAsync(
pandocPath?: string,
typstPath?: string,
imagemagickPath?: string,
additionalPaths: string[] = []
): Promise<void> {
): void {
// Check dependencies silently on startup
try {
const missingDeps = this.checkDependenciesSync(
+1 -8
View File
@@ -9,6 +9,7 @@
* - Cross-platform path handling (Unix and Windows)
*/
import { spawn, spawnSync } from 'child_process';
import { DEPENDENCY_CONSTANTS } from './constants';
import * as path from 'path';
@@ -140,8 +141,6 @@ export class ExecutableChecker {
* ```
*/
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
const { spawn } = require('child_process');
try {
const stdout = await new Promise<string>((resolve, reject) => {
const env = this.getAugmentedEnv(additionalPaths);
@@ -259,8 +258,6 @@ export class ExecutableChecker {
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
// Try to find the executable using which command synchronously
const { spawnSync } = require('child_process');
// Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
@@ -323,8 +320,6 @@ export class ExecutableChecker {
versionCommand: string,
versionRegex: RegExp
): Promise<DependencyInfo> {
const { spawn } = require('child_process');
try {
// Use spawn instead of exec for security - arguments passed separately
const stdout = await new Promise<string>((resolve, reject) => {
@@ -396,8 +391,6 @@ export class ExecutableChecker {
* ```
*/
public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
const { spawnSync } = require('child_process');
try {
const result = spawnSync(executablePath, versionCommand.split(' '), {
encoding: 'utf8',
+1 -1
View File
@@ -181,7 +181,7 @@ export class ExportErrorHandler {
console.warn(`${operation}:`, error);
coderabbitai[bot] commented 2025-11-05 13:54:26 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟡 Minor

Align logLevel parameter with actual logging behavior.

The logLevel parameter accepts 'info' per the interface definition (line 46), but the implementation now uses console.debug() instead of console.info(). This creates a semantic mismatch where callers specify 'info' but receive debug-level logging.

Consider one of these options:

  1. Revert to console.info() if info-level logging is the intended behavior, OR
  2. Update the interface to accept 'debug' instead of 'info' to match the implementation

Option 1: Revert to console.info

 case 'info':
-	console.debug(`${operation}:`, error);
+	console.info(`${operation}:`, error);
 	break;

Option 2: Update interface and documentation

 export interface ExportError {
 	fileName?: string;
 	operation: string;
 	error: Error | string;
 	shouldShowNotice?: boolean;
-	logLevel?: 'error' | 'warn' | 'info';
+	logLevel?: 'error' | 'warn' | 'debug';
 }
📝 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.

			case 'info':
				console.info(`${operation}:`, error);
				break;
🤖 Prompt for AI Agents
In src/core/ExportErrorHandler.ts around lines 183 to 185, the method accepts a
logLevel of 'info' per the interface but calls console.debug(), creating a
mismatch; either change the implementation to call console.info() to match the
declared 'info' logLevel, or update the interface and any docs to accept 'debug'
(replace 'info' with 'debug' where the type/interface and comments mention it)
and ensure all callers using 'info' are updated to 'debug' or adjusted
accordingly.

✅ Addressed in commits f0daebc to c1c02ee

_⚠️ Potential issue_ | _🟡 Minor_ **Align logLevel parameter with actual logging behavior.** The `logLevel` parameter accepts `'info'` per the interface definition (line 46), but the implementation now uses `console.debug()` instead of `console.info()`. This creates a semantic mismatch where callers specify `'info'` but receive debug-level logging. Consider one of these options: 1. **Revert to `console.info()`** if info-level logging is the intended behavior, OR 2. **Update the interface** to accept `'debug'` instead of `'info'` to match the implementation **Option 1: Revert to console.info** ```diff case 'info': - console.debug(`${operation}:`, error); + console.info(`${operation}:`, error); break; ``` **Option 2: Update interface and documentation** ```diff export interface ExportError { fileName?: string; operation: string; error: Error | string; shouldShowNotice?: boolean; - logLevel?: 'error' | 'warn' | 'info'; + logLevel?: 'error' | 'warn' | 'debug'; } ``` <!-- 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 case 'info': console.info(`${operation}:`, error); break; ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/core/ExportErrorHandler.ts around lines 183 to 185, the method accepts a logLevel of 'info' per the interface but calls console.debug(), creating a mismatch; either change the implementation to call console.info() to match the declared 'info' logLevel, or update the interface and any docs to accept 'debug' (replace 'info' with 'debug' where the type/interface and comments mention it) and ensure all callers using 'info' are updated to 'debug' or adjusted accordingly. ``` </details> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee <!-- This is an auto-generated comment by CodeRabbit -->
AlexKucera commented 2025-11-05 15:16:04 +01:00 (Migrated from github.com)
Review

@coderabbitai ObsidianReviewBot raised this issue:

Unexpected console statement. Only these console methods are allowed: warn, error, debug.

@coderabbitai ObsidianReviewBot raised this issue: > Unexpected console statement. Only these console methods are allowed: warn, error, debug.
coderabbitai[bot] commented 2025-11-05 15:17:37 +01:00 (Migrated from github.com)
Review
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for any code using logLevel with 'info' value
rg -n "logLevel.*['\"]info['\"]" --type ts

Length of output: 72


🏁 Script executed:

#!/bin/bash
# Also search for the ExportError interface usage to find all places where logLevel might be specified
rg -n "ExportError|handleExportError" --type ts -C3

Length of output: 28847


@AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only console.warn, console.error, and console.debug means we need to align the interface with the implementation.

Since no code in the codebase is currently using logLevel: 'info' (confirmed by the search), you only need to update:

  1. Line 46 - Update the ExportError interface:
logLevel?: 'error' | 'warn' | 'debug';
  1. Line 39 - Update the JSDoc comment above the interface:
 * @property logLevel - Logging severity level (default: 'error')

(This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug')

  1. Line 165 in the example comment, change:
 *   logLevel: 'warn'

to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there.

The change from console.info() to console.debug() is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯


🧬 Code Graph Analysis Results

tests/mocks/obsidian.ts

At lines 4-6: ``` export class Notice { constructor(message: string) {} } ```

src/core/constants.ts

At lines 122-128: ``` export const EXPORT_CONSTANTS = { DEFAULT_TIMEOUT: 120000, // 2 minutes NOTICE_DURATION: { SHORT: 5000, LONG: 12000 } } as const; ```

✏️ Learnings added
Learnt from: AlexKucera
Repo: AlexKucera/obsidian-typst-pdf-export PR: 8
File: src/core/ExportErrorHandler.ts:183-185
Timestamp: 2025-11-05T14:17:36.572Z
Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info().

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.

<details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Search for any code using logLevel with 'info' value rg -n "logLevel.*['\"]info['\"]" --type ts ``` Length of output: 72 --- 🏁 Script executed: ``` #!/bin/bash # Also search for the ExportError interface usage to find all places where logLevel might be specified rg -n "ExportError|handleExportError" --type ts -C3 ``` Length of output: 28847 --- </details> @AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only `console.warn`, `console.error`, and `console.debug` means we need to align the interface with the implementation. Since no code in the codebase is currently using `logLevel: 'info'` (confirmed by the search), you only need to update: 1. **Line 46** - Update the `ExportError` interface: ```typescript logLevel?: 'error' | 'warn' | 'debug'; ``` 2. **Line 39** - Update the JSDoc comment above the interface: ```typescript * @property logLevel - Logging severity level (default: 'error') ``` (This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug') 3. **Line 165** in the example comment, change: ```typescript * logLevel: 'warn' ``` to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there. The change from `console.info()` to `console.debug()` is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯 --- <details> <summary>🧬 Code Graph Analysis Results</summary> <filename>tests/__mocks__/obsidian.ts</filename> <snippet> At lines 4-6: ``` export class Notice { constructor(message: string) {} } ``` </snippet> <filename>src/core/constants.ts</filename> <snippet> At lines 122-128: ``` export const EXPORT_CONSTANTS = { DEFAULT_TIMEOUT: 120000, // 2 minutes NOTICE_DURATION: { SHORT: 5000, LONG: 12000 } } as const; ``` </snippet> </details> --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera Repo: AlexKucera/obsidian-typst-pdf-export PR: 8 File: src/core/ExportErrorHandler.ts:183-185 Timestamp: 2025-11-05T14:17:36.572Z Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info(). ``` > 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> <!-- <agentComponentType>chat-answer</agentComponentType> --> <!-- <rawResChunk><answer><details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Search for any code using logLevel with 'info' value rg -n "logLevel.*['\"]info['\"]" --type ts ``` Length of output: 72 --- 🏁 Script executed: ``` #!/bin/bash # Also search for the ExportError interface usage to find all places where logLevel might be specified rg -n "ExportError|handleExportError" --type ts -C3 ``` Length of output: 28847 --- </details> @AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only `console.warn`, `console.error`, and `console.debug` means we need to align the interface with the implementation. Since no code in the codebase is currently using `logLevel: 'info'` (confirmed by the search), you only need to update: 1. **Line 46** - Update the `ExportError` interface: ```typescript logLevel?: 'error' | 'warn' | 'debug'; ``` 2. **Line 39** - Update the JSDoc comment above the interface: ```typescript * @property logLevel - Logging severity level (default: 'error') ``` (This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug') 3. **Line 165** in the example comment, change: ```typescript * logLevel: 'warn' ``` to remain as 'warn' (already correct), but the comment text that mentions "info" in the example doesn't exist, so you're good there. The change from `console.info()` to `console.debug()` is the right approach given the ObsidianReviewBot constraint. Just update the interface definition to match! 🎯 --- <details> <summary>🧬 Code Graph Analysis Results</summary> <filename>tests/__mocks__/obsidian.ts</filename> <snippet> At lines 4-6: ``` export class Notice { constructor(message: string) {} } ``` </snippet> <filename>src/core/constants.ts</filename> <snippet> At lines 122-128: ``` export const EXPORT_CONSTANTS = { DEFAULT_TIMEOUT: 120000, // 2 minutes NOTICE_DURATION: { SHORT: 5000, LONG: 12000 } } as const; ``` </snippet> </details> --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: AlexKucera Repo: AlexKucera/obsidian-typst-pdf-export PR: 8 File: src/core/ExportErrorHandler.ts:183-185 Timestamp: 2025-11-05T14:17:36.572Z Learning: In Obsidian plugin development, ObsidianReviewBot (a linting tool for Obsidian plugins) only allows the following console methods: console.warn(), console.error(), and console.debug(). The console.info() and console.log() methods are forbidden. When implementing logging functionality, use console.debug() for informational/debug messages instead of console.info(). ``` > 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> </answer></rawResChunk> --> <!-- This is an auto-generated reply by CodeRabbit -->
break;
case 'info':
console.info(`${operation}:`, error);
console.debug(`${operation}:`, error);
break;
}
+3 -3
View File
@@ -14,7 +14,7 @@
*/
import { TFile } from 'obsidian';
import { obsidianTypstPDFExportSettings } from './settings';
import { obsidianTypstPDFExportSettings, ExportFormat } from './settings';
import { ExportConfigModalSettings } from '../ui/modal/modalTypes';
/**
@@ -179,8 +179,8 @@ export class ModalSettingsHelper {
};
// Auto-adjust width for single-page landscape mode
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
&& settings.exportDefaults.format === 'single-page'
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
&& settings.exportDefaults.format === ExportFormat.SinglePage
? { width: 'auto' }
: {};
+1 -1
View File
@@ -1,6 +1,7 @@
// ABOUTME: Centralized path utilities for safe Obsidian API operations
// ABOUTME: Handles vault paths, plugin directories, and file operations
import { promises as fs } from 'fs';
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
import type { App, PluginManifest } from 'obsidian';
import * as path from 'path';
@@ -238,7 +239,6 @@ export class PathUtils {
if (isAbsolutePath) {
try {
const fs = require('fs').promises;
await fs.access(path);
return true;
} catch {
+3 -2
View File
@@ -218,7 +218,7 @@ export class SecurityUtils {
// Check for command injection attempts
const dangerousPatterns = [
/[;&|`$<>]/, // Shell metacharacters that can't appear in safe paths
// eslint-disable-next-line no-control-regex
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
/\x00/, // Null bytes
/\n|\r/, // Newlines
/\s*[;&|]\s*/, // Command separators with whitespace
@@ -374,7 +374,8 @@ export class SecurityUtils {
if (/[;&|`$<>]/.test(normalizedPath)) {
return 'Shell metacharacters are not allowed in executable paths';
}
if (/\x00/.test(normalizedPath)) { // eslint-disable-line no-control-regex
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
if (/\x00/.test(normalizedPath)) {
return 'Null bytes are not allowed in paths';
}
if (/\n|\r/.test(normalizedPath)) {
+9 -3
View File
@@ -18,7 +18,9 @@ export class CommandRegistry {
id: 'export-current-note',
name: 'Export current note(s)',
editorCallback: (editor: Editor, view: MarkdownView) => {
this.plugin.exportCurrentNote(view);
this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
});
}
});
@@ -27,7 +29,9 @@ export class CommandRegistry {
id: 'export-with-config',
name: 'Export with configuration…',
editorCallback: (editor: Editor, view: MarkdownView) => {
this.plugin.showExportModal(view);
this.plugin.showExportModal(view).catch(error => {
console.error('Failed to show export modal:', error);
});
}
coderabbitai[bot] commented 2025-11-05 13:54:26 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Error handling should notify users, not just log to console

When a user-initiated command fails, logging to console provides no feedback to the user. They won't know why the export didn't happen. Consider showing a Notice with the error message so users understand what went wrong.

Apply this pattern for user-facing error handling:

-				this.plugin.exportCurrentNote(view).catch(error => {
-					console.error('Failed to export current note:', error);
-				});
+				this.plugin.exportCurrentNote(view).catch(error => {
+					console.error('Failed to export current note:', error);
+					new Notice(`Export failed: ${error.message}`);
+				});

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

🤖 Prompt for AI Agents
In src/plugin/CommandRegistry.ts around lines 21 to 23, the catch currently only
logs the error to console which gives no user feedback; instead import and use
Obsidian's Notice to show a user-facing message (e.g., new Notice(`Failed to
export current note: ${error?.message ?? String(error)}`)) and optionally retain
console.error for debugging; ensure Notice is imported from 'obsidian' and that
the error is safely stringified so users see a readable explanation.

✅ Addressed in commits f0daebc to c1c02ee

_⚠️ Potential issue_ | _🟠 Major_ **Error handling should notify users, not just log to console** When a user-initiated command fails, logging to console provides no feedback to the user. They won't know why the export didn't happen. Consider showing a Notice with the error message so users understand what went wrong. Apply this pattern for user-facing error handling: ```diff - this.plugin.exportCurrentNote(view).catch(error => { - console.error('Failed to export current note:', error); - }); + this.plugin.exportCurrentNote(view).catch(error => { + console.error('Failed to export current note:', error); + new Notice(`Export failed: ${error.message}`); + }); ``` > Committable suggestion skipped: line range outside the PR's diff. <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/plugin/CommandRegistry.ts around lines 21 to 23, the catch currently only logs the error to console which gives no user feedback; instead import and use Obsidian's Notice to show a user-facing message (e.g., new Notice(`Failed to export current note: ${error?.message ?? String(error)}`)) and optionally retain console.error for debugging; ensure Notice is imported from 'obsidian' and that the error is safely stringified so users see a readable explanation. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits f0daebc to c1c02ee
});
@@ -36,7 +40,9 @@ export class CommandRegistry {
id: 'check-dependencies',
name: 'Check Pandoc and Typst dependencies',
callback: () => {
this.plugin.showDependencyStatus();
this.plugin.showDependencyStatus().catch(error => {
console.error('Failed to show dependency status:', error);
});
}
});
}
+9 -9
View File
@@ -3,6 +3,8 @@
* Handles processing of PDF, image, and file embeds for PDF export
*/
import { exec } from 'child_process';
import * as util from 'util';
import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main';
import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
@@ -108,7 +110,7 @@ export class EmbedProcessor {
// Select appropriate protocol based on parsed URL (handles case-insensitive schemes)
const protocol = urlObj.protocol === 'https:' ? https : http;
console.log(`Export: Downloading remote image: ${imageUrl}`);
console.debug(`Export:Downloading remote image: ${imageUrl}`);
// Use parsed URL object for the request to ensure correct protocol handling
const request = protocol.get(urlObj, (response) => {
@@ -120,7 +122,7 @@ export class EmbedProcessor {
// This handles both absolute URLs (e.g., "https://example.com/img.png")
// and relative URLs (e.g., "/assets/img.png" or "../img.png")
const absoluteRedirectUrl = new URL(redirectUrl, imageUrl).href;
console.log(`Export: Following redirect to: ${absoluteRedirectUrl}`);
console.debug(`Export:Following redirect to: ${absoluteRedirectUrl}`);
// Recursively follow redirect with resolved absolute URL
this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve);
return;
@@ -157,7 +159,7 @@ export class EmbedProcessor {
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
await this.plugin.app.vault.adapter.writeBinary(outputPath, arrayBuffer);
console.log(`Export: Successfully downloaded image to: ${outputPath}`);
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
resolve(outputPath);
} catch (err) {
console.error(`Export: Error writing image file: ${err.message}`);
@@ -295,13 +297,13 @@ export class EmbedProcessor {
if (isRemoteUrl) {
// Try to download the remote image
console.log(`Export: Attempting to download remote image: ${decodedPath}`);
console.debug(`Export:Attempting to download remote image: ${decodedPath}`);
const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir);
if (downloadedPath) {
// Successfully downloaded, use it as a local image
fullImagePath = downloadedPath;
console.log(`Export: Successfully downloaded and will embed remote image`);
console.debug(`Export:Successfully downloaded and will embed remote image`);
} else {
// Download failed, use placeholder
console.warn(`Export: Failed to download remote image: ${decodedPath}`);
@@ -342,11 +344,9 @@ export class EmbedProcessor {
await this.pathUtils.ensureDir(vaultTempImagesDir);
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
try {
// Use PathResolver to get the correct ImageMagick path
const { PathResolver } = await import('./PathResolver');
+19 -7
View File
@@ -23,7 +23,9 @@ export class EventHandlers {
.setTitle('Export to PDF (Typst)')
.setIcon('file-output')
.onClick(() => {
this.plugin.exportFile(file);
this.plugin.exportFile(file).catch(error => {
console.error('Failed to export file:', error);
});
});
});
}
@@ -38,7 +40,9 @@ export class EventHandlers {
.setTitle('Export to PDF (Typst)')
.setIcon('file-output')
.onClick(() => {
this.plugin.exportCurrentNote(view);
this.plugin.exportCurrentNote(view).catch(error => {
console.error('Failed to export current note:', error);
});
});
});
})
@@ -48,7 +52,7 @@ export class EventHandlers {
this.plugin.registerEvent(
this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => {
// Filter for markdown files only
const markdownFiles = files.filter(this.plugin.isMarkdownFile);
const markdownFiles = files.filter((file) => this.plugin.isMarkdownFile(file));
if (markdownFiles.length > 0) {
menu.addItem((item) => {
@@ -56,7 +60,9 @@ export class EventHandlers {
.setTitle(`Export to PDF (Typst)`)
.setIcon('file-output')
.onClick(() => {
this.plugin.exportFiles(markdownFiles);
this.plugin.exportFiles(markdownFiles).catch(error => {
console.error('Failed to export files:', error);
});
});
});
@@ -65,7 +71,9 @@ export class EventHandlers {
.setTitle(`Export with configuration...`)
.setIcon('settings')
.onClick(() => {
this.plugin.showExportModalForFiles(markdownFiles);
this.plugin.showExportModalForFiles(markdownFiles).catch(error => {
console.error('Failed to show export modal for files:', error);
});
});
});
}
@@ -92,7 +100,9 @@ export class EventHandlers {
.setTitle('Export current note(s)')
.setIcon('file-output')
.onClick(() => {
this.plugin.exportFile(activeView.file!);
this.plugin.exportFile(activeView.file!).catch(error => {
console.error('Failed to export file:', error);
});
})
);
@@ -101,7 +111,9 @@ export class EventHandlers {
.setTitle('Export with configuration…')
.setIcon('settings')
.onClick(() => {
this.plugin.showExportModal(activeView);
this.plugin.showExportModal(activeView).catch(error => {
console.error('Failed to show export modal:', error);
});
})
);
+3 -3
View File
@@ -157,7 +157,7 @@ export class ExportOrchestrator {
// Create progress notice with cancel button
const progressNotice = new Notice('', 0);
const cancelButton = progressNotice.noticeEl.createEl('button', {
const cancelButton = progressNotice.messageEl.createEl('button', {
text: 'Cancel',
cls: 'mod-warning'
});
@@ -179,7 +179,7 @@ export class ExportOrchestrator {
noteTitle: file.basename
});
const processedResult = await preprocessor.process(content);
const processedResult = preprocessor.process(content);
if (processedResult.errors.length > 0) {
console.warn('Preprocessing errors:', processedResult.errors);
@@ -319,7 +319,7 @@ export class ExportOrchestrator {
*/
async handleFolderExport(folder: TFolder): Promise<void> {
// Get all markdown files in the folder
const markdownFiles = folder.children.filter(this.plugin.isMarkdownFile);
const markdownFiles = folder.children.filter((file) => this.plugin.isMarkdownFile(file));
if (markdownFiles.length === 0) {
new Notice('No markdown files found in this folder');
+1 -2
View File
@@ -3,6 +3,7 @@
* Handles font discovery, caching, and retrieval for the plugin
*/
import { spawn } from 'child_process';
import type { obsidianTypstPDFExport } from '../../main';
import { ExportErrorHandler } from '../core/ExportErrorHandler';
import { FALLBACK_FONTS } from '../core/constants';
@@ -16,8 +17,6 @@ export class FontManager {
*/
async cacheAvailableFonts(): Promise<void> {
try {
const { spawn } = require('child_process');
const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
// Use spawn instead of exec for security - arguments passed separately
+1 -2
View File
@@ -3,6 +3,7 @@
* Handles executable path resolution and output path preparation
*/
import { spawnSync } from 'child_process';
import { TFile } from 'obsidian';
import type { obsidianTypstPDFExport } from '../../main';
import { SecurityUtils } from '../core/SecurityUtils';
@@ -26,8 +27,6 @@ export class PathResolver {
}
// Try to find the executable using which command
const { spawnSync } = require('child_process');
// Use platform-specific command: 'where' on Windows, 'which' on Unix
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
+7 -7
View File
@@ -51,12 +51,12 @@ export class PluginLifecycle {
// Clean up any leftover temp directories from previous sessions
this.cleanupStartupTempDirectories();
// Check dependencies on startup (async, don't await)
// Check dependencies on startup
this.plugin.checkDependenciesAsync();
// Cache available fonts (async, don't await)
this.plugin.cacheAvailableFonts();
void this.plugin.cacheAvailableFonts();
}
/**
@@ -69,7 +69,7 @@ export class PluginLifecycle {
}
// Clean up temp directories on plugin unload (fire-and-forget async)
(async () => {
void (async () => {
try {
const vaultPath = this.pathUtils.getVaultPath();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
@@ -85,11 +85,11 @@ export class PluginLifecycle {
*/
private cleanupStartupTempDirectories(): void {
// Clean up temp directories (fire-and-forget async)
(async () => {
void (async () => {
try {
const vaultPath = this.pathUtils.getVaultPath();
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
const _result = await cleanupManager.cleanupAllTempDirs();
await cleanupManager.cleanupAllTempDirs();
if (this.plugin.settings.behavior.debugMode) {
// Debug logging was here but empty in original
+20 -8
View File
@@ -27,8 +27,10 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Typst PDF Export Settings' });
new Setting(containerEl)
.setName('Typst PDF Export Settings')
.setHeading();
// Executable paths section
this.createExecutablePathsSection(containerEl);
@@ -47,14 +49,16 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
}
private createExecutablePathsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Executable Paths' });
new Setting(containerEl)
.setName('Executable paths')
.setHeading();
// Add dependency check button
new Setting(containerEl)
.setName('Dependencies')
.setDesc('Check the status of external dependencies')
.addButton(button => button
.setButtonText('Check Dependencies')
.setButtonText('Check dependencies')
.setCta()
.onClick(async () => {
await this.plugin.showDependencyStatus();
@@ -131,7 +135,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
}
private createExportDefaultsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Export Defaults' });
new Setting(containerEl)
.setName('Export defaults')
.setHeading();
new Setting(containerEl)
.setName('Default template')
@@ -229,7 +235,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
}
private createTypographyDefaultsSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Typography Defaults' });
new Setting(containerEl)
.setName('Typography defaults')
.setHeading();
// Use helper method for all three font dropdowns
this.createFontDropdown(
1
@@ -293,7 +301,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
}
private createPageSetupSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Page Setup' });
new Setting(containerEl)
.setName('Page setup')
.setHeading();
new Setting(containerEl)
.setName('Page size')
@@ -363,7 +373,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
}
private createBehaviorSection(containerEl: HTMLElement): void {
containerEl.createEl('h3', { text: 'Behavior' });
new Setting(containerEl)
.setName('Behavior')
.setHeading();
new Setting(containerEl)
.setName('Open after export')
+2 -1
View File
@@ -127,11 +127,12 @@ export class TemplateManager {
case 'version':
metadata.version = value;
break;
case 'variable':
case 'variable': {
// Parse variable definition (e.g., @variable: font:string:Body font family)
const [name, type, description] = value.split(':');
metadata.variables.push({ name, type, description });
break;
}
}
}
+8 -8
View File
@@ -20,7 +20,7 @@ export class ExportConfigModal extends Modal {
plugin: obsidianTypstPDFExport;
private state: ModalState;
private sections: Map<string, ModalSection> = new Map();
private onSubmit: (config: ExportConfig) => void;
private onSubmit: (config: ExportConfig) => void | Promise<void>;
private onCancel?: () => void;
private renderer: ModalRenderer;
private validator: ModalValidator;
@@ -29,7 +29,7 @@ export class ExportConfigModal extends Modal {
app: App,
plugin: obsidianTypstPDFExport,
settings: Partial<ExportConfigModalSettings>,
onSubmit: (config: ExportConfig) => void,
onSubmit: (config: ExportConfig) => void | Promise<void>,
onCancel?: () => void
) {
super(app);
@@ -38,7 +38,7 @@ export class ExportConfigModal extends Modal {
this.onCancel = onCancel;
// Initialize state
this.state = new ModalState(settings);
this.state = new ModalState(settings, app);
// Register sections
this.registerSections();
@@ -81,9 +81,9 @@ export class ExportConfigModal extends Modal {
// Initialize renderer with content container
this.renderer.initialize(contentContainer);
// Load available templates
this.loadAvailableTemplates();
void this.loadAvailableTemplates();
}
private async loadAvailableTemplates(): Promise<void> {
@@ -117,10 +117,10 @@ export class ExportConfigModal extends Modal {
// Re-render sections to update UI
this.renderer.refreshSections();
// Reload templates to update the dropdown
this.loadAvailableTemplates();
void this.loadAvailableTemplates();
ExportErrorHandler.showSettingsReset();
}
+5 -243
View File
@@ -10,7 +10,7 @@ import { ModalSection } from './modalTypes';
export interface ModalRendererCallbacks {
onReset: () => void;
onCancel: () => void;
onSubmit: () => void;
onSubmit: () => void | Promise<void>;
}
export class ModalRenderer {
@@ -47,7 +47,6 @@ export class ModalRenderer {
initialize(contentContainer: HTMLElement): void {
this.contentContainer = contentContainer;
this.setupInitialLayout();
this.addModalStyles();
}
/**
@@ -119,9 +118,9 @@ export class ModalRenderer {
// Progress bar container
const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container');
this.progressBar = progressBarContainer.createDiv('export-progress-bar');
// Progress percentage
const _progressPercent = this.progressContainer.createEl('div', {
this.progressContainer.createEl('div', {
cls: 'export-progress-percent',
text: '0%'
});
@@ -135,7 +134,7 @@ export class ModalRenderer {
// Reset button (left side)
this.resetButton = buttonContainer.createEl('button', {
text: 'Reset to Defaults',
text: 'Reset to defaults',
cls: 'mod-muted'
});
this.resetButton.addEventListener('click', () => this.callbacks.onReset());
1
@@ -219,7 +218,7 @@ export class ModalRenderer {
}
const errorContainer = this.formContainer.createDiv('validation-errors');
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' });
errorContainer.createEl('h4', { text: 'Validation errors', cls: 'error-title' });
const errorList = errorContainer.createEl('ul');
errors.forEach(error => {
@@ -251,241 +250,4 @@ export class ModalRenderer {
// Remove after 5 seconds
setTimeout(() => warningContainer.remove(), 5000);
}
/**
* Add custom CSS styles for the modal
*/
private addModalStyles(): void {
// Add custom styles for the modal
const style = document.createElement('style');
style.textContent = `
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 16px 24px 8px 24px;
border-bottom: 1px solid var(--background-modifier-border);
flex-shrink: 0;
}
.export-config-header h2 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.export-note-title {
margin: 0;
font-size: 14px;
color: var(--text-muted);
opacity: 0.8;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
}
.export-config-section {
margin-bottom: 24px;
}
.export-config-section:last-child {
margin-bottom: 0;
}
.export-config-section-title {
font-weight: 600;
margin-bottom: 12px;
padding-bottom: 4px;
border-bottom: 1px solid var(--background-modifier-border-hover);
}
.export-config-buttons {
padding: 16px 24px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 8px;
}
/* Progress styles */
.export-progress-container {
padding: 24px;
text-align: center;
}
.export-progress-container.export-hidden {
display: none;
}
.export-progress-container.export-progress-visible {
display: block;
}
.export-form-hidden {
display: none !important;
}
.export-progress-text {
margin-bottom: 16px;
font-size: 14px;
color: var(--text-muted);
}
.export-progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--background-modifier-border);
border-radius: 4px;
margin-bottom: 8px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background-color: var(--interactive-accent);
border-radius: 4px;
width: var(--progress-width, 0%);
transition: width 0.3s ease;
}
.export-progress-percent {
font-size: 12px;
color: var(--text-muted);
}
/* Form field styles */
.export-setting-item {
margin-bottom: 16px;
}
.export-setting-item-info {
margin-bottom: 6px;
}
.export-setting-item-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-setting-item-description {
font-size: 12px;
color: var(--text-muted);
}
.export-setting-item-control {
display: flex;
align-items: center;
}
.export-setting-item-control input,
.export-setting-item-control select {
flex: 1;
}
/* Folder suggest styles */
.export-folder-suggest-container {
position: relative;
}
.export-folder-suggest-input {
width: 100%;
padding: 6px 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 4px;
background: var(--background-primary);
color: var(--text-normal);
}
.export-folder-suggest-input:focus {
border-color: var(--interactive-accent);
outline: none;
}
/* Validation styles */
.validation-errors, .validation-warnings {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.validation-warnings {
background: var(--background-modifier-warning);
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.warning-title {
color: var(--text-warning);
margin: 0 0 10px 0;
}
.validation-errors ul, .validation-warnings ul {
margin: 0;
padding-left: 20px;
}
.export-validation-error {
color: var(--text-error);
font-size: 12px;
margin-top: 4px;
}
.export-validation-warning {
color: var(--text-warning);
font-size: 12px;
margin-top: 4px;
}
/* Template variable styles */
.export-template-variables {
margin-top: 12px;
}
.export-template-variable {
margin-bottom: 8px;
padding: 8px;
background: var(--background-secondary);
border-radius: 4px;
font-size: 12px;
}
.export-template-variable-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-template-variable-description {
color: var(--text-muted);
font-style: italic;
}
`;
if (!document.head.querySelector('style[data-export-config-modal]')) {
style.setAttribute('data-export-config-modal', 'true');
document.head.appendChild(style);
}
}
}
+3 -1
View File
@@ -11,7 +11,9 @@ export class BehaviorSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Export Behavior' });
new Setting(this.container)
.setName('Export behavior')
.setHeading();
this.createBehaviorToggles(state);
}
+3 -1
View File
@@ -18,7 +18,9 @@ export class GeneralSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
if (app) this.app = app;
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'General Settings' });
new Setting(this.container)
.setName('General settings')
.setHeading();
this.createTemplateSelection(state);
this.createFormatSelection(state);
2
+3 -1
View File
@@ -13,7 +13,9 @@ export class LayoutSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Layout' });
new Setting(this.container)
.setName('Page layout')
.setHeading();
this.createPageSizeSettings(state);
this.createOrientationSettings(state);
+8 -5
View File
@@ -6,6 +6,7 @@
import { Setting } from 'obsidian';
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
import { ExportFormat } from '../../../core/settings';
export class PageSetupSection implements ModalSection {
private container: HTMLElement | null = null;
@@ -13,7 +14,9 @@ export class PageSetupSection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState): void {
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Page Setup' });
new Setting(this.container)
.setName('Page setup')
.setHeading();
this.createPageSizeSettings(state);
this.createOrientationSettings(state);
@@ -53,12 +56,12 @@ export class PageSetupSection implements ModalSection {
.setValue(String(state.templateVariables.orientation || 'portrait'))
.onChange(value => {
const isLandscape = value === 'landscape';
state.updateTemplateVariables({
state.updateTemplateVariables({
orientation: value,
flipped: isLandscape,
// Auto-adjust width for single-page mode when flipped
...(isLandscape && state.settings.format === 'single-page'
? { width: 'auto' }
...(isLandscape && state.settings.format === ExportFormat.SinglePage
? { width: 'auto' }
: {})
});
});
@@ -69,7 +72,7 @@ export class PageSetupSection implements ModalSection {
if (!this.container) return;
const marginsContainer = this.container.createDiv('margins-container');
marginsContainer.createEl('h4', { text: 'Text Margins' });
marginsContainer.createEl('h4', { text: 'Text margins' });
marginsContainer.createEl('p', {
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
cls: 'setting-item-description'
+4 -2
View File
@@ -13,10 +13,12 @@ export class TypographySection implements ModalSection {
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
coderabbitai[bot] commented 2025-11-08 19:27:33 +01:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

Add error handling for fire-and-forget async call.

The void operator suppresses the promise without error handling, violating the coding guideline to "handle errors gracefully". If createFontSettings fails, errors will be silently swallowed. Additionally, this creates a UI ordering issue where the font size settings render before the font dropdowns, which may confuse users.

Consider one of these approaches:

Option 1: Await the font settings creation

-void this.createFontSettings(state);
-this.createFontSizeSettings(state);
+await this.createFontSettings(state);
+this.createFontSizeSettings(state);

Then change the render method signature to:

-render(containerEl: HTMLElement, state: ModalState, app?: App): void {
+async render(containerEl: HTMLElement, state: ModalState, app?: App): Promise<void> {

Option 2: Add error handling with void operator

-void this.createFontSettings(state);
+void this.createFontSettings(state).catch(error => {
+	console.error('Failed to create font settings:', error);
+	// Optionally show user-facing error
+});

As per coding guidelines.

📝 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.

		void this.createFontSettings(state).catch(error => {
			console.error('Failed to create font settings:', error);
			// Optionally show user-facing error
		});
🤖 Prompt for AI Agents
In src/ui/modal/sections/TypographySection.ts around line 21, the call "void
this.createFontSettings(state);" suppresses errors and causes font-size to
render before font dropdowns; either make render async and await
this.createFontSettings(state) so errors propagate and ordering is preserved
(update the render signature and all call sites accordingly), or keep the
fire-and-forget but attach explicit error handling like
this.createFontSettings(state).catch(err => /* log/report error */) and ensure
any ordering dependent UI updates wait for completion; implement one of these
fixes and remove the void operator.

✅ Addressed in commits 5219ef7 to d6d31af

_⚠️ Potential issue_ | _🟠 Major_ **Add error handling for fire-and-forget async call.** The `void` operator suppresses the promise without error handling, violating the coding guideline to "handle errors gracefully". If `createFontSettings` fails, errors will be silently swallowed. Additionally, this creates a UI ordering issue where the font size settings render before the font dropdowns, which may confuse users. Consider one of these approaches: **Option 1: Await the font settings creation** ```diff -void this.createFontSettings(state); -this.createFontSizeSettings(state); +await this.createFontSettings(state); +this.createFontSizeSettings(state); ``` Then change the `render` method signature to: ```diff -render(containerEl: HTMLElement, state: ModalState, app?: App): void { +async render(containerEl: HTMLElement, state: ModalState, app?: App): Promise<void> { ``` **Option 2: Add error handling with void operator** ```diff -void this.createFontSettings(state); +void this.createFontSettings(state).catch(error => { + console.error('Failed to create font settings:', error); + // Optionally show user-facing error +}); ``` As per coding guidelines. <!-- 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 void this.createFontSettings(state).catch(error => { console.error('Failed to create font settings:', error); // Optionally show user-facing error }); ``` </details> <!-- suggestion_end --> <details> <summary>🤖 Prompt for AI Agents</summary> ``` In src/ui/modal/sections/TypographySection.ts around line 21, the call "void this.createFontSettings(state);" suppresses errors and causes font-size to render before font dropdowns; either make render async and await this.createFontSettings(state) so errors propagate and ordering is preserved (update the render signature and all call sites accordingly), or keep the fire-and-forget but attach explicit error handling like this.createFontSettings(state).catch(err => /* log/report error */) and ensure any ordering dependent UI updates wait for completion; implement one of these fixes and remove the void operator. ``` </details> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 5219ef7 to d6d31af
if (app) this.app = app;
this.container = containerEl.createDiv('export-section');
this.container.createEl('h3', { text: 'Typography' });
new Setting(this.container)
.setName('Typography')
.setHeading();
// Create font settings asynchronously
this.createFontSettings(state);
void this.createFontSettings(state);
this.createFontSizeSettings(state);
}
+9 -8
View File
@@ -3,6 +3,7 @@
* Centralized state management for the Export Configuration Modal
*/
import { App } from 'obsidian';
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings';
@@ -13,7 +14,7 @@ export class ModalState implements IModalState {
private changeListeners: Set<() => void> = new Set();
private static readonly STORAGE_KEY = 'typst-export-modal-state';
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
constructor(initialSettings: Partial<ExportConfigModalSettings>, private app: App) {
// Load from localStorage if available
const savedState = this.loadFromStorage();
@@ -174,7 +175,7 @@ export class ModalState implements IModalState {
}
/**
* Save current state to localStorage
* Save current state to vault-specific storage
*/
private saveToStorage(): void {
const stateToSave = {
@@ -187,25 +188,25 @@ export class ModalState implements IModalState {
},
templateVariables: this.templateVariables
};
try {
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
this.app.saveLocalStorage(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
} catch (error) {
console.warn('Failed to save modal state to localStorage:', error);
console.warn('Failed to save modal state to vault storage:', error);
}
}
/**
* Load state from localStorage
* Load state from vault-specific storage
*/
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null {
try {
const saved = localStorage.getItem(ModalState.STORAGE_KEY);
const saved = this.app.loadLocalStorage(ModalState.STORAGE_KEY);
if (saved) {
return JSON.parse(saved);
}
} catch (error) {
console.warn('Failed to load modal state from localStorage:', error);
console.warn('Failed to load modal state from vault storage:', error);
}
return null;
}
+220
View File
@@ -134,3 +134,223 @@
.export-form-hidden {
display: none !important;
}
/* Export config modal styles */
.export-config-modal {
width: 90vw;
max-width: 520px;
height: 80vh;
max-height: 600px;
}
.export-config-container {
display: flex;
flex-direction: column;
height: 100%;
}
.export-config-header {
padding: 16px 24px 8px 24px;
border-bottom: 1px solid var(--background-modifier-border);
flex-shrink: 0;
}
.export-config-header h2 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.export-note-title {
margin: 0;
font-size: 14px;
color: var(--text-muted);
opacity: 0.8;
}
.export-config-form {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
}
.export-config-section {
margin-bottom: 24px;
}
.export-config-section:last-child {
margin-bottom: 0;
}
.export-config-section-title {
font-weight: 600;
margin-bottom: 12px;
padding-bottom: 4px;
border-bottom: 1px solid var(--background-modifier-border-hover);
}
.export-config-buttons {
padding: 16px 24px;
border-top: 1px solid var(--background-modifier-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.export-config-buttons .right-buttons {
display: flex;
gap: 8px;
}
/* Progress styles */
.export-progress-container {
padding: 24px;
text-align: center;
}
.export-progress-container.export-hidden {
display: none;
}
.export-progress-container.export-progress-visible {
display: block;
}
.export-progress-text {
margin-bottom: 16px;
font-size: 14px;
color: var(--text-muted);
}
.export-progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--background-modifier-border);
border-radius: 4px;
margin-bottom: 8px;
overflow: hidden;
}
.export-progress-bar {
height: 100%;
background-color: var(--interactive-accent);
border-radius: 4px;
width: var(--progress-width, 0%);
transition: width 0.3s ease;
}
.export-progress-percent {
font-size: 12px;
color: var(--text-muted);
}
/* Form field styles */
.export-setting-item {
margin-bottom: 16px;
}
.export-setting-item-info {
margin-bottom: 6px;
}
.export-setting-item-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-setting-item-description {
font-size: 12px;
color: var(--text-muted);
}
.export-setting-item-control {
display: flex;
align-items: center;
}
.export-setting-item-control input,
.export-setting-item-control select {
flex: 1;
}
/* Folder suggest styles */
.export-folder-suggest-container {
position: relative;
}
.export-folder-suggest-input {
width: 100%;
padding: 6px 8px;
border: 1px solid var(--background-modifier-border);
border-radius: 4px;
background: var(--background-primary);
color: var(--text-normal);
}
.export-folder-suggest-input:focus {
border-color: var(--interactive-accent);
outline: none;
}
/* Validation styles */
.validation-errors, .validation-warnings {
background: var(--background-modifier-error);
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.validation-warnings {
background: var(--background-modifier-warning);
}
.error-title {
color: var(--text-error);
margin: 0 0 10px 0;
}
.warning-title {
color: var(--text-warning);
margin: 0 0 10px 0;
}
.validation-errors ul, .validation-warnings ul {
margin: 0;
padding-left: 20px;
}
.export-validation-error {
color: var(--text-error);
font-size: 12px;
margin-top: 4px;
}
.export-validation-warning {
color: var(--text-warning);
font-size: 12px;
margin-top: 4px;
}
/* Template variable styles */
.export-template-variables {
margin-top: 12px;
}
.export-template-variable {
margin-bottom: 8px;
padding: 8px;
background: var(--background-secondary);
border-radius: 4px;
font-size: 12px;
}
.export-template-variable-name {
font-weight: 500;
margin-bottom: 2px;
}
.export-template-variable-description {
color: var(--text-muted);
font-style: italic;
}
+2
View File
@@ -11,6 +11,8 @@
"importHelpers": true,
"isolatedModules": true,
"strictNullChecks": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"lib": [
"DOM",
"ES5",