Update ESLint rules and resolve bot review feedback #8
No files matched your search
@@ -169,7 +169,7 @@ Go to the plugin settings and click **Check Dependencies** to ensure all require
|
||||
|
||||
- **Obsidian**: Version 1.9.12 or higher
|
||||
- **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it.
|
||||
- **Node.js**: Version 16+ (for development)
|
||||
- **Node.js**: Version 18.20+ (for development)
|
||||
|
||||
### External Dependencies
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
|
|
||||
// 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': ['warn', { 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/**',
|
||||
],
|
||||
}
|
||||
);
|
||||
);
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Notice,
|
||||
MarkdownView
|
||||
} from 'obsidian';
|
||||
import { shell } from 'electron';
|
||||
|
||||
|
⚠️ Potential issue | 🔴 Critical Avoid top-level Electron import Importing
🤖 Prompt for AI Agents_⚠️ 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 -->
@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.
@AlexKucera, understood! Since this plugin is desktop-only, the top-level ✏️ Learnings added
🧠 Learnings used@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';
|
||||
@@ -78,6 +79,7 @@ export class obsidianTypstPDFExport extends Plugin {
|
||||
`);
|
||||
|
||||
// Add ribbon icon using custom icon
|
||||
// eslint-disable-next-line obsidianmd/ui/sentence-case -- "PDF" is an acronym and "Typst" is a proper noun
|
||||
this.addRibbonIcon('typst-pdf-export', 'Export to PDF with Typst', (event: MouseEvent) => {
|
||||
this.eventHandlers.handleRibbonClick(event);
|
||||
});
|
||||
@@ -177,8 +179,8 @@ export class obsidianTypstPDFExport extends Plugin {
|
||||
);
|
||||
}
|
||||
|
||||
async checkDependenciesAsync(): Promise<void> {
|
||||
return DependencyChecker.checkDependenciesAsync(
|
||||
checkDependenciesOnStartup(): void {
|
||||
DependencyChecker.checkDependenciesOnStartup(
|
||||
this.settings.pandocPath,
|
||||
this.settings.typstPath,
|
||||
this.settings.executablePaths?.imagemagickPath,
|
||||
@@ -212,8 +214,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() {
|
||||
@@ -236,11 +237,14 @@ export class obsidianTypstPDFExport extends Plugin {
|
||||
throw error; // Re-throw to let callers handle appropriately
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
onunload() {
|
||||
|
||||
|
||||
// Obsidian supports async onunload and will await it properly, even though
|
||||
// the Plugin type definition shows void return. This ensures cleanup completes.
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
async onunload(): Promise<void> {
|
||||
// Use lifecycle manager for cleanup
|
||||
this.lifecycle.cleanup();
|
||||
await this.lifecycle.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -24,17 +24,25 @@
|
||||
],
|
||||
"author": "Alexander Kucera",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.20.0"
|
||||
},
|
||||
"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",
|
||||
@@ -45,6 +53,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"gray-matter": "^4.0.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"pdf-to-img": "^4.5.0"
|
||||
}
|
||||
}
|
||||
@@ -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 = '';
|
||||
* 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)
|
||||
* ```
|
||||
*
|
||||
|
||||
@@ -11,13 +11,14 @@
|
||||
* - Error handling
|
||||
*
|
||||
* The converter supports both file-based and content-based conversions, automatically
|
||||
* managing temporary directories and cleanup on process termination.
|
||||
* managing temporary directories with cleanup via the plugin lifecycle.
|
||||
*/
|
||||
|
||||
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
import { TempDirectoryManager } from '../core/TempDirectoryManager';
|
||||
import { PathUtils } from '../core/PathUtils';
|
||||
import { promises as fs } from 'fs';
|
||||
|
||||
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
|
||||
import { PandocExecutor } from './pandoc/PandocExecutor';
|
||||
@@ -32,7 +33,7 @@ import { PandocExecutor } from './pandoc/PandocExecutor';
|
||||
* Key features:
|
||||
* - File and content-based conversion support
|
||||
* - Automatic temporary directory management
|
||||
* - Process cleanup on termination (exit, SIGINT, SIGTERM, exceptions)
|
||||
* - Cleanup via plugin lifecycle (onunload)
|
||||
* - Progress callback support for UI updates
|
||||
* - Configurable Pandoc and Typst settings
|
||||
*
|
||||
@@ -40,8 +41,8 @@ import { PandocExecutor } from './pandoc/PandocExecutor';
|
||||
* 1. Constructor initializes command builder and executor
|
||||
* 2. Conversion methods create temp directories and build commands
|
||||
* 3. Executor runs Pandoc with Typst engine
|
||||
* 4. Cleanup automatically removes temporary files
|
||||
* 5. dispose() for manual cleanup when done
|
||||
* 4. Plugin unload calls dispose() to remove temporary files
|
||||
* 5. dispose() can also be called manually for cleanup when done
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
@@ -74,15 +75,14 @@ export class PandocTypstConverter {
|
||||
private plugin: obsidianTypstPDFExport;
|
||||
private commandBuilder: PandocCommandBuilder;
|
||||
private pandocExecutor: PandocExecutor;
|
||||
private processCleanupHandler: (() => void) | null = null;
|
||||
private isDisposed = false;
|
||||
|
||||
/**
|
||||
* Creates a new PandocTypstConverter instance with configuration.
|
||||
*
|
||||
* Initializes the converter with the plugin instance and configuration options
|
||||
* for both Pandoc and Typst. Sets up cleanup handlers to ensure temporary
|
||||
* files are removed on process termination.
|
||||
* for both Pandoc and Typst. Temporary files are cleaned up via dispose()
|
||||
* which is called during plugin unload.
|
||||
*
|
||||
* @param plugin - The main plugin instance for accessing app and settings
|
||||
* @param pandocOptions - Configuration options for Pandoc conversion (template, variables, etc.)
|
||||
@@ -115,8 +115,6 @@ export class PandocTypstConverter {
|
||||
this.plugin = plugin;
|
||||
this.commandBuilder = new PandocCommandBuilder(plugin);
|
||||
this.pandocExecutor = new PandocExecutor(plugin);
|
||||
// Set up cleanup handlers for process termination
|
||||
this.setupCleanup();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -254,7 +252,8 @@ export class PandocTypstConverter {
|
||||
const pathUtils = new PathUtils(this.plugin.app);
|
||||
const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
|
||||
|
||||
await this.plugin.app.vault.adapter.write(tempInputPath, content);
|
||||
// Use fs.writeFile for temp files since external tools (Pandoc) need absolute paths
|
||||
await fs.writeFile(tempInputPath, content, 'utf-8');
|
||||
|
||||
// Merge options
|
||||
this.pandocOptions = { ...this.pandocOptions, ...options };
|
||||
@@ -264,7 +263,8 @@ export class PandocTypstConverter {
|
||||
|
||||
// Cleanup temp file
|
||||
try {
|
||||
await this.plugin.app.vault.adapter.remove(tempInputPath);
|
||||
// Use fs.unlink for temp files since they're in external temp directories
|
||||
await fs.unlink(tempInputPath);
|
||||
} catch (error) {
|
||||
console.warn('Failed to cleanup temp file:', error);
|
||||
}
|
||||
@@ -279,38 +279,6 @@ export class PandocTypstConverter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up automatic cleanup handlers for process termination events.
|
||||
*
|
||||
* Registers the cleanup method to run on various process termination events
|
||||
* to ensure temporary files are removed even if the process exits unexpectedly.
|
||||
* Handlers are registered for:
|
||||
* - Normal exit
|
||||
* - SIGINT (Ctrl+C)
|
||||
* - SIGTERM (kill command)
|
||||
*
|
||||
* Note: Handlers are stored and removed on dispose() to prevent listener leaks.
|
||||
* The uncaughtException handler is NOT registered to avoid swallowing errors.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private setupCleanup(): void {
|
||||
// Store handler reference so we can remove it later
|
||||
this.processCleanupHandler = () => {
|
||||
// Only cleanup if not already disposed to avoid double-cleanup
|
||||
if (!this.isDisposed) {
|
||||
this.cleanup();
|
||||
}
|
||||
};
|
||||
|
||||
// Register cleanup handlers - these will be removed on dispose()
|
||||
process.on('exit', this.processCleanupHandler);
|
||||
process.on('SIGINT', this.processCleanupHandler);
|
||||
process.on('SIGTERM', this.processCleanupHandler);
|
||||
// Note: uncaughtException handler removed to avoid swallowing errors
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Cleans up temporary files and directories.
|
||||
*
|
||||
@@ -318,7 +286,7 @@ export class PandocTypstConverter {
|
||||
* directory created by the converter. Cleanup failures are logged but don't throw
|
||||
* to avoid interfering with normal operation or other cleanup operations.
|
||||
*
|
||||
* Called automatically on process termination or manually via dispose().
|
||||
* Called via dispose() during plugin unload.
|
||||
*
|
||||
* @private
|
||||
* @returns Promise that resolves when cleanup is complete
|
||||
@@ -364,14 +332,20 @@ 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;
|
||||
if (!configDir) {
|
||||
throw new Error('Unable to access vault configuration directory. Plugin may not be properly initialized.');
|
||||
}
|
||||
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;
|
||||
if (!configDir) {
|
||||
throw new Error('Unable to access vault configuration directory. Plugin may not be properly initialized.');
|
||||
}
|
||||
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
|
||||
this.tempDir = await tempManager.ensureTempDir('pandoc');
|
||||
}
|
||||
@@ -410,14 +384,6 @@ export class PandocTypstConverter {
|
||||
|
||||
this.isDisposed = true;
|
||||
|
||||
// Remove process event listeners to prevent memory leaks
|
||||
if (this.processCleanupHandler) {
|
||||
process.off('exit', this.processCleanupHandler);
|
||||
process.off('SIGINT', this.processCleanupHandler);
|
||||
process.off('SIGTERM', this.processCleanupHandler);
|
||||
this.processCleanupHandler = null;
|
||||
}
|
||||
|
||||
// Cleanup temporary files and resources
|
||||
await this.cleanup();
|
||||
}
|
||||
|
||||
@@ -413,10 +413,11 @@ export class PdfToImageConverter {
|
||||
};
|
||||
|
🛠️ Refactor suggestion | 🟠 Major Extract duplicated path conversion logic to PathUtils helper. This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability. See the detailed suggestion in the review comment for
🤖 Prompt for AI Agents_🛠️ Refactor suggestion_ | _🟠 Major_
**Extract duplicated path conversion logic to PathUtils helper.**
This vault-relative path conversion pattern is duplicated across multiple files (ImageOptimizer.ts, embeddedTemplates.ts, and here). Consolidating to a PathUtils helper method would reduce duplication and improve maintainability.
See the detailed suggestion in the review comment for `src/converters/pdf/ImageOptimizer.ts` lines 247-304. The same `pathUtils.toVaultRelative()` helper would simplify this code:
```diff
if (this.plugin?.app) {
const pathUtils = new PathUtils(this.plugin.app);
- const vaultPath = pathUtils.getVaultPath();
- // Convert absolute path to vault-relative
- let relativeOutputDir = outputDir;
- if (outputDir.startsWith(vaultPath)) {
- relativeOutputDir = outputDir.substring(vaultPath.length);
- if (relativeOutputDir.startsWith('/') || relativeOutputDir.startsWith('\\')) {
- relativeOutputDir = relativeOutputDir.substring(1);
- }
- }
+ const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
await pathUtils.ensureDir(relativeOutputDir);
}
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/PdfToImageConverter.ts around lines 416 to 428, the
vault-relative path conversion logic is duplicated and should be moved into
PathUtils; add a PathUtils.toVaultRelative(outputDir) (or similar) method that
returns the vault-relative path (trimming leading separators when needed) and
replace the inline conversion here with: const relativeOutputDir =
pathUtils.toVaultRelative(outputDir); then call await
pathUtils.ensureDir(relativeOutputDir); ensuring behavior matches existing
trimming and only converts when outputDir starts with the vault path.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
|
||||
}
|
||||
|
||||
// Ensure output directory exists
|
||||
// Ensure output directory exists (convert absolute path to vault-relative for vault.adapter)
|
||||
if (this.plugin?.app) {
|
||||
const pathUtils = new PathUtils(this.plugin.app);
|
||||
await pathUtils.ensureDir(outputDir);
|
||||
const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
|
||||
await pathUtils.ensureDir(relativeOutputDir);
|
||||
}
|
||||
|
||||
// Generate expected output file name for the first page
|
||||
|
||||
@@ -201,10 +201,6 @@ export class PandocCommandBuilder {
|
||||
// Enable standalone mode (required for PDF output)
|
||||
args.push('--standalone');
|
||||
|
||||
// Disable citeproc to prevent automatic bibliography processing
|
||||
// This prevents "document does not contain a bibliography" errors when
|
||||
// Pandoc detects citation-like patterns but no bibliography file is provided
|
||||
args.push('--no-citeproc');
|
||||
|
||||
// Embed resources (images, etc.) directly into the output
|
||||
args.push('--embed-resources');
|
||||
|
||||
@@ -3,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';
|
||||
@@ -29,8 +30,13 @@ export class BinaryLocator {
|
||||
// Get the plugin directory - need to handle Obsidian's environment
|
||||
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
|
||||
// Try multiple strategies to find the plugin directory
|
||||
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
|
||||
const configDir = plugin?.app.vault.configDir || '.obsidian';
|
||||
// Extract just the plugin folder name from manifest.dir (e.g., "typst-pdf-export" from ".obsidian/plugins/typst-pdf-export")
|
||||
const fullManifestDir = plugin?.manifest?.dir || 'typst-pdf-export';
|
||||
const pluginDirName = path.basename(fullManifestDir);
|
||||
const configDir = plugin?.app.vault.configDir;
|
||||
if (!configDir) {
|
||||
throw new Error('Unable to determine Obsidian configuration directory');
|
||||
}
|
||||
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
|
||||
|
||||
// Find the first directory that exists and has node_modules
|
||||
@@ -154,7 +160,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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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', [
|
||||
@@ -218,22 +218,10 @@ export class ImageOptimizer {
|
||||
// Clean up the original PNG if conversion succeeded
|
||||
try {
|
||||
if (plugin?.app) {
|
||||
// Convert absolute path to vault-relative path for adapter.remove()
|
||||
const pathUtils = new PathUtils(plugin.app);
|
||||
const vaultBasePath = pathUtils.getVaultPath();
|
||||
|
||||
let relativePath = inputImagePath;
|
||||
if (inputImagePath.startsWith(vaultBasePath)) {
|
||||
// Remove vault base path and leading separator
|
||||
relativePath = inputImagePath.substring(vaultBasePath.length);
|
||||
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
|
||||
relativePath = relativePath.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
const relativePath = pathUtils.toVaultRelative(inputImagePath);
|
||||
await plugin.app.vault.adapter.remove(relativePath);
|
||||
} else {
|
||||
const fs = require('fs').promises;
|
||||
await fs.unlink(inputImagePath);
|
||||
}
|
||||
} catch (unlinkError) {
|
||||
@@ -245,11 +233,14 @@ export class ImageOptimizer {
|
||||
// Just rename the file to PNG format
|
||||
const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png');
|
||||
if (plugin?.app) {
|
||||
const content = await plugin.app.vault.adapter.readBinary(inputImagePath);
|
||||
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content);
|
||||
await plugin.app.vault.adapter.remove(inputImagePath);
|
||||
const pathUtils = new PathUtils(plugin.app);
|
||||
const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
|
||||
const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
|
||||
|
||||
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
|
||||
await plugin.app.vault.adapter.writeBinary(relativePngPath, content);
|
||||
await plugin.app.vault.adapter.remove(relativeInputPath);
|
||||
} else {
|
||||
const fs = require('fs').promises;
|
||||
await fs.rename(inputImagePath, pngFinalPath);
|
||||
|
🛠️ Refactor suggestion | 🟠 Major Extract duplicated path conversion logic to PathUtils helper. The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies. Consider adding a helper method to PathUtils: Then replace the duplicated blocks: 🤖 Prompt for AI Agents_🛠️ Refactor suggestion_ | _🟠 Major_
**Extract duplicated path conversion logic to PathUtils helper.**
The vault-relative path conversion pattern (stripping vault base path and leading separators) is duplicated three times in this file (lines 220-234, 247-271, 280-304). This code duplication increases maintenance burden and the risk of inconsistencies.
Consider adding a helper method to PathUtils:
```typescript
// In PathUtils.ts
public toVaultRelative(absolutePath: string): string {
const vaultBasePath = this.getVaultPath();
if (!absolutePath.startsWith(vaultBasePath)) {
return absolutePath;
}
let relativePath = absolutePath.substring(vaultBasePath.length);
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.substring(1);
}
return relativePath;
}
```
Then replace the duplicated blocks:
```diff
if (plugin?.app) {
- // Convert absolute paths to vault-relative paths for adapter operations
const pathUtils = new PathUtils(plugin.app);
- const vaultBasePath = pathUtils.getVaultPath();
-
- let relativeInputPath = inputImagePath;
- if (inputImagePath.startsWith(vaultBasePath)) {
- // Remove vault base path and leading separator
- relativeInputPath = inputImagePath.substring(vaultBasePath.length);
- if (relativeInputPath.startsWith('/') || relativeInputPath.startsWith('\\')) {
- relativeInputPath = relativeInputPath.substring(1);
- }
- }
-
- let relativePngPath = pngFinalPath;
- if (pngFinalPath.startsWith(vaultBasePath)) {
- // Remove vault base path and leading separator
- relativePngPath = pngFinalPath.substring(vaultBasePath.length);
- if (relativePngPath.startsWith('/') || relativePngPath.startsWith('\\')) {
- relativePngPath = relativePngPath.substring(1);
- }
- }
+ const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
+ const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/converters/pdf/ImageOptimizer.ts around lines 247-304 (and also the
similar occurrences at ~220-234 and ~280-304), duplicate logic strips the vault
base path and leading separators; extract this into PathUtils.toVaultRelative
and replace the three duplicated blocks with calls to that helper. Add a public
toVaultRelative(absolutePath: string) method on PathUtils that returns the
original path if it does not start with getVaultPath(), otherwise removes the
vault base prefix and any leading '/' or '\' and returns the result; then in
ImageOptimizer create a PathUtils(plugin.app) instance and call toVaultRelative
for inputImagePath, pngFinalPath and finalOutputPath before passing them to
plugin.app.vault.adapter.readBinary/writeBinary/remove, removing the inline
substring/startsWith logic so behavior remains identical.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
|
||||
}
|
||||
actualImagePath = pngFinalPath;
|
||||
@@ -257,11 +248,14 @@ export class ImageOptimizer {
|
||||
} else {
|
||||
// Keep as PNG, just rename to final location
|
||||
if (plugin?.app) {
|
||||
const content = await plugin.app.vault.adapter.readBinary(inputImagePath);
|
||||
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content);
|
||||
await plugin.app.vault.adapter.remove(inputImagePath);
|
||||
const pathUtils = new PathUtils(plugin.app);
|
||||
const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
|
||||
const relativeFinalPath = pathUtils.toVaultRelative(finalOutputPath);
|
||||
|
||||
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
|
||||
await plugin.app.vault.adapter.writeBinary(relativeFinalPath, content);
|
||||
await plugin.app.vault.adapter.remove(relativeInputPath);
|
||||
} else {
|
||||
const fs = require('fs').promises;
|
||||
await fs.rename(inputImagePath, finalOutputPath);
|
||||
}
|
||||
actualImagePath = finalOutputPath;
|
||||
|
||||
@@ -3,11 +3,15 @@
|
||||
* 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';
|
||||
import type { obsidianTypstPDFExport } from '../../../main';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
export interface PdfCliOptions {
|
||||
/** Scale factor for the rendered image */
|
||||
scale: number;
|
||||
@@ -111,10 +115,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
|
||||
const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings);
|
||||
|
||||
|
||||
@@ -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,28 +44,30 @@ export class FrontmatterProcessor {
|
||||
}
|
||||
|
⚠️ Potential issue | 🟠 Major Remove raw-content logging from diagnostics. Also applies to: 152-154 🤖 Prompt for AI Agents_⚠️ 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', `(content length: ${content.length})`);
|
||||
|
||||
const parsed = matter(content);
|
||||
|
||||
if (parsed.data && Object.keys(parsed.data).length > 0) {
|
||||
// Replace frontmatter title with filename if noteTitle is provided
|
||||
// Sanitize frontmatter first to prevent citation fields from leaking to downstream consumers
|
||||
const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
|
||||
|
||||
// Store sanitized frontmatter in metadata (with title override if needed)
|
||||
if (this.noteTitle) {
|
||||
const frontmatterCopy = { ...parsed.data };
|
||||
frontmatterCopy.title = this.noteTitle;
|
||||
result.metadata.frontmatter = frontmatterCopy;
|
||||
result.metadata.frontmatter = {
|
||||
...sanitizedFrontmatter,
|
||||
title: this.noteTitle
|
||||
};
|
||||
} else {
|
||||
result.metadata.frontmatter = parsed.data;
|
||||
result.metadata.frontmatter = sanitizedFrontmatter;
|
||||
}
|
||||
|
||||
|
||||
// Extract tags from frontmatter if they exist
|
||||
if (parsed.data.tags) {
|
||||
let frontmatterTags: string[] = [];
|
||||
|
||||
|
||||
if (Array.isArray(parsed.data.tags)) {
|
||||
// Handle array of tags
|
||||
frontmatterTags = parsed.data.tags
|
||||
@@ -77,7 +80,7 @@ export class FrontmatterProcessor {
|
||||
.map((tag: string) => tag.trim())
|
||||
.filter((tag: string) => tag !== '');
|
||||
}
|
||||
|
||||
|
||||
// Merge with existing tags (avoid duplicates)
|
||||
for (const tag of frontmatterTags) {
|
||||
if (!result.metadata.tags.includes(tag)) {
|
||||
@@ -85,22 +88,19 @@ export class FrontmatterProcessor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Extract title - use noteTitle if available, otherwise frontmatter title
|
||||
if (this.noteTitle) {
|
||||
result.metadata.title = this.noteTitle;
|
||||
} else if (parsed.data.title && typeof parsed.data.title === 'string') {
|
||||
result.metadata.title = parsed.data.title.trim();
|
||||
}
|
||||
|
||||
// Handle frontmatter preservation and display options
|
||||
const finalFrontmatter = this.noteTitle ?
|
||||
{ ...parsed.data, title: this.noteTitle } :
|
||||
parsed.data;
|
||||
|
||||
// Use the sanitized frontmatter from metadata for writing
|
||||
const finalFrontmatter = result.metadata.frontmatter;
|
||||
|
||||
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,7 +115,6 @@ export class FrontmatterProcessor {
|
||||
// Return content without frontmatter, but add title as frontmatter for Pandoc
|
||||
|
⚠️ 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: Apply similar fixes to lines 185 and 204: Also applies to: 185-185, 204-204 🤖 Prompt for AI Agents✅ Addressed in commit _⚠️ 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
|
||||
let processedContent: string;
|
||||
if (this.noteTitle) {
|
||||
const yaml = require('js-yaml');
|
||||
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
|
||||
} else {
|
||||
@@ -141,7 +140,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 +150,7 @@ 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, `(content length: ${content.length})`);
|
||||
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
|
||||
|
||||
// Fallback to simple regex-based parsing
|
||||
@@ -185,7 +182,6 @@ export class FrontmatterProcessor {
|
||||
if (this.preserveFrontmatter) {
|
||||
// Reconstruct frontmatter with modified title
|
||||
if (this.noteTitle) {
|
||||
const yaml = require('js-yaml');
|
||||
const newFrontmatter = yaml.dump(frontmatter);
|
||||
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
|
||||
|
||||
@@ -205,7 +201,6 @@ 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 });
|
||||
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
|
||||
|
||||
@@ -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 };
|
||||
@@ -242,6 +236,20 @@ export class FrontmatterProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip citation-related fields from frontmatter to prevent Pandoc bibliography processing
|
||||
*/
|
||||
private stripCitationFields(frontmatter: Record<string, unknown>): Record<string, unknown> {
|
||||
const citationFields = ['bibliography', 'references', 'csl', 'citation-style', 'nocite', 'link-citations', 'reference-section-title'];
|
||||
const sanitized = { ...frontmatter };
|
||||
|
||||
for (const field of citationFields) {
|
||||
delete sanitized[field];
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format frontmatter as a readable display block
|
||||
*/
|
||||
@@ -265,13 +273,19 @@ 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 => {
|
||||
const itemStr = typeof item === 'object' ? JSON.stringify(item) : String(item);
|
||||
return `- ${itemStr}`;
|
||||
}).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 +322,12 @@ export class FrontmatterProcessor {
|
||||
} else {
|
||||
formattedValue = valueStr;
|
||||
}
|
||||
} else {
|
||||
// Handle null, undefined, or any other unexpected types
|
||||
console.debug('FrontmatterProcessor: Unexpected type in frontmatter display formatting', `key: ${key}, type: ${typeof value}`);
|
||||
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
|
||||
|
||||
@@ -321,7 +321,6 @@ ${dependencyResult.allAvailable
|
||||
* @param typstPath - Optional custom path to Typst executable
|
||||
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
|
||||
* @param additionalPaths - Additional directories to search for executables
|
||||
* @returns Promise that resolves when the check is complete
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
@@ -331,7 +330,7 @@ ${dependencyResult.allAvailable
|
||||
* await this.loadSettings();
|
||||
*
|
||||
* // Silent startup check - only shows notice if problems exist
|
||||
* await DependencyChecker.checkDependenciesAsync(
|
||||
* DependencyChecker.checkDependenciesOnStartup(
|
||||
* this.settings.pandocPath,
|
||||
* this.settings.typstPath,
|
||||
* this.settings.imagemagickPath,
|
||||
@@ -348,12 +347,12 @@ ${dependencyResult.allAvailable
|
||||
* // Run 'Check Dependencies' command for details."
|
||||
* ```
|
||||
*/
|
||||
public static async checkDependenciesAsync(
|
||||
public static checkDependenciesOnStartup(
|
||||
pandocPath?: string,
|
||||
typstPath?: string,
|
||||
imagemagickPath?: string,
|
||||
additionalPaths: string[] = []
|
||||
): Promise<void> {
|
||||
): void {
|
||||
// Check dependencies silently on startup
|
||||
try {
|
||||
const missingDeps = this.checkDependenciesSync(
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* - Consistent error messaging and logging
|
||||
* - Batch export result tracking and reporting
|
||||
* - User-facing notices with appropriate durations
|
||||
* - Support for different log levels (error, warn, info)
|
||||
* - Support for different log levels (error, warn, debug)
|
||||
* - Specialized handlers for different error types (dependency, processing, validation)
|
||||
*/
|
||||
|
||||
@@ -43,7 +43,7 @@ export interface ExportError {
|
||||
operation: string;
|
||||
error: Error | string;
|
||||
shouldShowNotice?: boolean;
|
||||
logLevel?: 'error' | 'warn' | 'info';
|
||||
logLevel?: 'error' | 'warn' | 'debug';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -180,8 +180,8 @@ export class ExportErrorHandler {
|
||||
case 'warn':
|
||||
console.warn(`${operation}:`, error);
|
||||
|
⚠️ Potential issue | 🟡 Minor Align logLevel parameter with actual logging behavior. The Consider one of these options:
Option 1: Revert to console.info Option 2: Update interface and documentation 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ 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 -->
@coderabbitai ObsidianReviewBot raised this issue:
@coderabbitai ObsidianReviewBot raised this issue:
> Unexpected console statement. Only these console methods are allowed: warn, error, debug.
🧩 Analysis chain🏁 Script executed: Length of output: 72 🏁 Script executed: Length of output: 28847 @AlexKucera, thank you for clarifying! That makes sense—ObsidianReviewBot's restriction to only Since no code in the codebase is currently using
(This is fine as-is, but you could optionally clarify it accepts 'error' | 'warn' | 'debug')
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 🧬 Code Graph Analysis Resultstests/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
<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);
|
||||
case 'debug':
|
||||
console.debug(`${operation}:`, error);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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';
|
||||
@@ -105,6 +106,11 @@ export class PathUtils {
|
||||
return '';
|
||||
}
|
||||
const result = path.join(...filtered);
|
||||
// Don't use normalizePath on absolute paths as it strips the leading slash
|
||||
// Only normalize vault-relative paths
|
||||
if (path.isAbsolute(result)) {
|
||||
return result;
|
||||
}
|
||||
return normalizePath(result);
|
||||
}
|
||||
|
||||
@@ -132,8 +138,10 @@ export class PathUtils {
|
||||
await this.app.vault.adapter.mkdir(normalizedPath);
|
||||
}
|
||||
} catch (error) {
|
||||
new Notice(`Failed to create directory: ${normalizedPath}`);
|
||||
throw error;
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const userMessage = `Failed to create output directory "${normalizedPath}". ${errorMessage.includes('parent') || errorMessage.includes('ENOENT') ? 'The parent directory may not exist or you may not have write permissions.' : 'You may not have write permissions or the path is invalid.'}`;
|
||||
new Notice(userMessage);
|
||||
throw new Error(userMessage);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,7 +246,6 @@ export class PathUtils {
|
||||
|
||||
if (isAbsolutePath) {
|
||||
try {
|
||||
const fs = require('fs').promises;
|
||||
await fs.access(path);
|
||||
return true;
|
||||
} catch {
|
||||
@@ -248,4 +255,36 @@ export class PathUtils {
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an absolute path to a vault-relative path.
|
||||
*
|
||||
* This method is used to convert absolute filesystem paths to vault-relative
|
||||
* paths suitable for use with Obsidian's vault adapter operations. If the path
|
||||
* does not start with the vault base path, it is returned unchanged.
|
||||
*
|
||||
* @param absolutePath - The absolute path to convert
|
||||
* @returns The vault-relative path (without leading slash) or the original path if not within vault
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const pathUtils = new PathUtils(app);
|
||||
* const vaultPath = '/Users/name/vault';
|
||||
* const absolutePath = '/Users/name/vault/folder/file.md';
|
||||
* const relative = pathUtils.toVaultRelative(absolutePath);
|
||||
* // Returns: 'folder/file.md'
|
||||
* ```
|
||||
*/
|
||||
toVaultRelative(absolutePath: string): string {
|
||||
const vaultBasePath = this.getVaultPath();
|
||||
if (!absolutePath.startsWith(vaultBasePath)) {
|
||||
return absolutePath;
|
||||
}
|
||||
|
||||
let relativePath = absolutePath.substring(vaultBasePath.length);
|
||||
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
|
||||
relativePath = relativePath.substring(1);
|
||||
}
|
||||
return relativePath;
|
||||
}
|
||||
}
|
||||
@@ -116,13 +116,17 @@ export class SecurityUtils {
|
||||
if (!outputFolder || typeof outputFolder !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Normalize and resolve the path to detect traversal attempts
|
||||
const normalizedPath = path.normalize(outputFolder.trim());
|
||||
|
||||
|
||||
// Normalize path (reject absolute paths so exports stay inside the vault)
|
||||
const trimmed = outputFolder.trim();
|
||||
if (path.isAbsolute(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
const normalizedPath = path.normalize(trimmed);
|
||||
|
||||
// Check for path traversal attempts
|
||||
if (normalizedPath.includes('..') ||
|
||||
normalizedPath.startsWith('/') ||
|
||||
if (normalizedPath.includes('..') ||
|
||||
normalizedPath.startsWith('/') ||
|
||||
normalizedPath.startsWith('\\') ||
|
||||
normalizedPath.includes('\x00')) {
|
||||
return false;
|
||||
@@ -218,7 +222,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
|
||||
@@ -280,9 +284,14 @@ export class SecurityUtils {
|
||||
if (!outputFolder || typeof outputFolder !== 'string') {
|
||||
return 'Output folder is required';
|
||||
}
|
||||
|
||||
const normalizedPath = path.normalize(outputFolder.trim());
|
||||
|
||||
|
||||
// Normalize path (reject absolute paths so exports stay inside the vault)
|
||||
const trimmed = outputFolder.trim();
|
||||
if (path.isAbsolute(trimmed)) {
|
||||
return 'Absolute paths are not allowed - use relative paths from vault root';
|
||||
}
|
||||
const normalizedPath = path.normalize(trimmed);
|
||||
|
||||
if (normalizedPath.includes('..')) {
|
||||
return 'Path traversal attempts (..) are not allowed';
|
||||
}
|
||||
@@ -374,7 +383,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)) {
|
||||
|
||||
@@ -24,6 +24,7 @@ import { PLUGIN_DIRS } from './constants';
|
||||
import { normalizePath } from 'obsidian';
|
||||
import type { App } from 'obsidian';
|
||||
import * as path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
|
||||
/**
|
||||
* Configuration options for TempDirectoryManager initialization.
|
||||
@@ -167,7 +168,8 @@ export class TempDirectoryManager {
|
||||
private getPluginDir(): string {
|
||||
// path.join automatically handles absolute paths correctly
|
||||
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
|
||||
return normalizePath(result);
|
||||
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||
return path.isAbsolute(result) ? result : normalizePath(result);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,7 +209,8 @@ export class TempDirectoryManager {
|
||||
// Use path.join to properly handle absolute paths
|
||||
const result = path.join(pluginDir, dirName);
|
||||
|
||||
return normalizePath(result);
|
||||
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||
return path.isAbsolute(result) ? result : normalizePath(result);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,9 +256,13 @@ export class TempDirectoryManager {
|
||||
public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
|
||||
const tempDir = this.getTempDir(type);
|
||||
|
||||
const exists = await this.app.vault.adapter.exists(tempDir);
|
||||
if (!exists) {
|
||||
await this.app.vault.adapter.mkdir(tempDir);
|
||||
// Use fs.mkdir for temp directories since external tools (pdf2img, ImageMagick)
|
||||
// need to write to them directly with absolute paths
|
||||
try {
|
||||
await fs.access(tempDir);
|
||||
} catch {
|
||||
// Directory doesn't exist, create it with recursive option
|
||||
await fs.mkdir(tempDir, { recursive: true });
|
||||
}
|
||||
|
||||
return tempDir;
|
||||
@@ -302,13 +309,19 @@ export class TempDirectoryManager {
|
||||
public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
|
||||
const tempDir = this.getTempDir(type);
|
||||
|
||||
// Use fs for temp directory cleanup since these directories contain
|
||||
// files created by external tools
|
||||
try {
|
||||
const exists = await this.app.vault.adapter.exists(tempDir);
|
||||
const exists = await fs.access(tempDir).then(() => true).catch(() => false);
|
||||
if (exists) {
|
||||
const list = await this.app.vault.adapter.list(tempDir);
|
||||
const files = await fs.readdir(tempDir);
|
||||
// Remove only files, not subdirectories (matching current pattern)
|
||||
for (const file of list.files) {
|
||||
await this.app.vault.adapter.remove(file);
|
||||
for (const file of files) {
|
||||
const filePath = path.join(tempDir, file);
|
||||
const stat = await fs.stat(filePath);
|
||||
if (stat.isFile()) {
|
||||
await fs.unlink(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Handles registration of all plugin commands and their callbacks
|
||||
*/
|
||||
|
||||
import { Editor, MarkdownView } from 'obsidian';
|
||||
import { Editor, MarkdownView, Notice } from 'obsidian';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
|
||||
export class CommandRegistry {
|
||||
@@ -18,7 +18,11 @@ 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);
|
||||
const errorMessage = error?.message ?? String(error);
|
||||
new Notice(`Failed to export current note: ${errorMessage}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -27,16 +31,24 @@ 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);
|
||||
|
⚠️ 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:
🤖 Prompt for AI Agents_⚠️ 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
|
||||
const errorMessage = error?.message ?? String(error);
|
||||
new Notice(`Failed to show export modal: ${errorMessage}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Check dependencies command
|
||||
this.plugin.addCommand({
|
||||
id: 'check-dependencies',
|
||||
name: 'Check Pandoc and Typst dependencies',
|
||||
name: 'Check pandoc and typst dependencies',
|
||||
callback: () => {
|
||||
this.plugin.showDependencyStatus();
|
||||
this.plugin.showDependencyStatus().catch(error => {
|
||||
console.error('Failed to show dependency status:', error);
|
||||
const errorMessage = error?.message ?? String(error);
|
||||
new Notice(`Failed to show dependency status: ${errorMessage}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -12,6 +14,8 @@ import * as path from 'path';
|
||||
import * as https from 'https';
|
||||
import * as http from 'http';
|
||||
|
||||
const execAsync = util.promisify(exec);
|
||||
|
||||
export class EmbedProcessor {
|
||||
private readonly pathUtils: PathUtils;
|
||||
|
||||
@@ -19,6 +23,44 @@ export class EmbedProcessor {
|
||||
this.pathUtils = new PathUtils(plugin.app);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle completion of image download and write to vault.
|
||||
* @param chunks Downloaded image data chunks
|
||||
* @param outputPath Absolute path where the image should be written
|
||||
* @param resolve Promise resolver to call with result
|
||||
*/
|
||||
private async handleDownloadComplete(
|
||||
chunks: Buffer[],
|
||||
outputPath: string,
|
||||
resolve: (value: string | null) => void
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Check if file already exists to avoid overwriting
|
||||
const exists = await this.pathUtils.fileExists(outputPath);
|
||||
if (exists) {
|
||||
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
return;
|
||||
}
|
||||
|
||||
// Combine chunks and write using vault adapter
|
||||
const buffer = Buffer.concat(chunks);
|
||||
// Convert Buffer to ArrayBuffer for vault adapter
|
||||
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
||||
|
||||
// Convert absolute path to vault-relative for adapter operations
|
||||
const relativeOutputPath = this.pathUtils.toVaultRelative(outputPath);
|
||||
|
||||
await this.plugin.app.vault.adapter.writeBinary(relativeOutputPath, arrayBuffer);
|
||||
|
||||
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
} catch (err) {
|
||||
console.error(`Export: Error writing image file: ${err.message}`);
|
||||
resolve(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a local file path using Obsidian's API and filesystem fallbacks
|
||||
* @param decodedPath The decoded (non-URL-encoded) path to resolve
|
||||
@@ -86,7 +128,7 @@ export class EmbedProcessor {
|
||||
* Returns the local path if successful, null if failed
|
||||
*/
|
||||
private async downloadRemoteImage(imageUrl: string, tempDir: string): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// Parse URL to get filename
|
||||
const urlObj = new URL(imageUrl);
|
||||
@@ -108,7 +150,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,9 +162,9 @@ 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);
|
||||
this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve).catch(reject);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -141,29 +183,9 @@ export class EmbedProcessor {
|
||||
chunks.push(chunk);
|
||||
});
|
||||
|
||||
response.on('end', async () => {
|
||||
try {
|
||||
// Check if file already exists to avoid overwriting
|
||||
const exists = await this.pathUtils.fileExists(outputPath);
|
||||
if (exists) {
|
||||
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
return;
|
||||
}
|
||||
|
||||
// Combine chunks and write using vault adapter
|
||||
const buffer = Buffer.concat(chunks);
|
||||
// Convert Buffer to ArrayBuffer for vault adapter
|
||||
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
||||
await this.plugin.app.vault.adapter.writeBinary(outputPath, arrayBuffer);
|
||||
|
||||
console.log(`Export: Successfully downloaded image to: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
} catch (err) {
|
||||
console.error(`Export: Error writing image file: ${err.message}`);
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
response.on('end', () => {
|
||||
void this.handleDownloadComplete(chunks, outputPath, resolve);
|
||||
});
|
||||
|
||||
response.on('error', (err) => {
|
||||
console.error(`Export: Error receiving image data: ${err.message}`);
|
||||
@@ -295,13 +317,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}`);
|
||||
@@ -338,15 +360,14 @@ export class EmbedProcessor {
|
||||
// Convert WebP to PNG using ImageMagick
|
||||
const originalImageName = path.basename(fullImagePath);
|
||||
const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
|
||||
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||
await this.pathUtils.ensureDir(vaultTempImagesDir);
|
||||
|
||||
// Use vault-relative path for ensureDir (it uses vault.adapter)
|
||||
const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||
await this.pathUtils.ensureDir(vaultRelativeTempDir);
|
||||
// But use absolute path for ImageMagick
|
||||
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
|
||||
|
||||
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
|
||||
|
||||
const { 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');
|
||||
@@ -523,8 +544,11 @@ export class EmbedProcessor {
|
||||
vaultBasePath: string
|
||||
): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
|
||||
// Copy image to vault temp directory for access
|
||||
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||
await this.pathUtils.ensureDir(vaultTempImagesDir);
|
||||
// Use vault-relative path for ensureDir (it uses vault.adapter)
|
||||
const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||
await this.pathUtils.ensureDir(vaultRelativeTempDir);
|
||||
// But use absolute path for file operations
|
||||
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
|
||||
|
||||
// Sanitize the basename for use in filename - replace problematic characters
|
||||
const sanitizedBaseName = baseName
|
||||
@@ -536,8 +560,12 @@ export class EmbedProcessor {
|
||||
const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName);
|
||||
|
||||
// Copy file using vault adapter
|
||||
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath);
|
||||
await this.plugin.app.vault.adapter.writeBinary(vaultImagePath, sourceBuffer);
|
||||
// Convert absolute paths to vault-relative paths for adapter operations
|
||||
const relativeSourcePath = this.pathUtils.toVaultRelative(imagePath);
|
||||
const relativeVaultImagePath = this.pathUtils.toVaultRelative(vaultImagePath);
|
||||
|
||||
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSourcePath);
|
||||
await this.plugin.app.vault.adapter.writeBinary(relativeVaultImagePath, sourceBuffer);
|
||||
|
||||
// Get relative paths from vault base
|
||||
const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
|
||||
|
||||
@@ -20,10 +20,12 @@ export class EventHandlers {
|
||||
if (file.extension === 'md') {
|
||||
menu.addItem((item) => {
|
||||
item
|
||||
.setTitle('Export to PDF (Typst)')
|
||||
.setTitle('Export to PDF')
|
||||
.setIcon('file-output')
|
||||
.onClick(() => {
|
||||
this.plugin.exportFile(file);
|
||||
this.plugin.exportFile(file).catch(error => {
|
||||
console.error('Failed to export file:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -35,10 +37,12 @@ export class EventHandlers {
|
||||
this.plugin.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => {
|
||||
menu.addItem((item) => {
|
||||
item
|
||||
.setTitle('Export to PDF (Typst)')
|
||||
.setTitle('Export to PDF')
|
||||
.setIcon('file-output')
|
||||
.onClick(() => {
|
||||
this.plugin.exportCurrentNote(view);
|
||||
this.plugin.exportCurrentNote(view).catch(error => {
|
||||
console.error('Failed to export current note:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
})
|
||||
@@ -48,15 +52,17 @@ 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) => {
|
||||
item
|
||||
.setTitle(`Export to PDF (Typst)`)
|
||||
.setTitle(`Export to PDF`)
|
||||
.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);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
@@ -143,7 +143,7 @@ export class ExportOrchestrator {
|
||||
this.plugin.currentExportController = new AbortController();
|
||||
|
||||
try {
|
||||
// Create temp directory for conversion
|
||||
// Create temp directories for conversion
|
||||
const tempManager = new TempDirectoryManager({
|
||||
vaultPath: vaultPath,
|
||||
configDir: this.plugin.app.vault.configDir,
|
||||
@@ -151,20 +151,21 @@ export class ExportOrchestrator {
|
||||
pluginName: this.plugin.manifest.id
|
||||
});
|
||||
const tempDir = await tempManager.ensureTempDir('pandoc');
|
||||
const tempImagesDir = await tempManager.ensureTempDir('images');
|
||||
|
||||
// Load file content
|
||||
const content = await this.plugin.app.vault.read(file);
|
||||
|
||||
// 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'
|
||||
});
|
||||
cancelButton.addEventListener('click', () => this.cancelExport());
|
||||
progressNotice.setMessage('Preprocessing markdown content...');
|
||||
progressNotice.setMessage('Preprocessing Markdown content...');
|
||||
|
||||
// Preprocess markdown
|
||||
// Preprocess Markdown
|
||||
const preprocessor = new MarkdownPreprocessor({
|
||||
vaultPath: vaultPath,
|
||||
options: {
|
||||
@@ -179,7 +180,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);
|
||||
@@ -191,12 +192,12 @@ export class ExportOrchestrator {
|
||||
// Process PDF embeds if any were found
|
||||
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
|
||||
const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles;
|
||||
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles);
|
||||
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempImagesDir, file, embedPdfFiles);
|
||||
}
|
||||
|
||||
// Process image embeds if any were found
|
||||
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
|
||||
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempDir, file);
|
||||
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempImagesDir, file);
|
||||
}
|
||||
|
||||
// Process file embeds if any were found
|
||||
@@ -319,10 +320,10 @@ 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');
|
||||
new Notice('No Markdown files found in this folder');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -60,16 +59,21 @@ export class PathResolver {
|
||||
* Prepare the output path for a file
|
||||
*/
|
||||
async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> {
|
||||
// Check if output folder is set
|
||||
if (!outputFolder || outputFolder.trim() === '') {
|
||||
throw new Error('Output folder is not set. Please configure the output folder in plugin settings.');
|
||||
}
|
||||
|
||||
// Validate output folder for security
|
||||
if (!SecurityUtils.validateOutputPath(outputFolder)) {
|
||||
throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`);
|
||||
throw new Error(`Invalid output folder path: "${outputFolder}". Path contains invalid characters or traversal attempts.`);
|
||||
}
|
||||
|
||||
const vaultPath = this.pathUtils.getVaultPath();
|
||||
const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder);
|
||||
|
||||
// Create output directory if it doesn't exist
|
||||
await this.pathUtils.ensureDir(outputDir);
|
||||
// Create output directory if it doesn't exist (use vault-relative path for vault adapter)
|
||||
await this.pathUtils.ensureDir(outputFolder);
|
||||
|
||||
// Preserve folder structure if configured
|
||||
let relativePath = '';
|
||||
@@ -77,8 +81,9 @@ export class PathResolver {
|
||||
const folderPath = path.dirname(file.path);
|
||||
if (folderPath !== '.') {
|
||||
relativePath = folderPath;
|
||||
const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath);
|
||||
await this.pathUtils.ensureDir(fullOutputDir);
|
||||
// Use vault-relative path for vault adapter
|
||||
const vaultRelativeOutputDir = this.pathUtils.joinPath(outputFolder, relativePath);
|
||||
await this.pathUtils.ensureDir(vaultRelativeOutputDir);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,33 +51,36 @@ export class PluginLifecycle {
|
||||
|
||||
// Clean up any leftover temp directories from previous sessions
|
||||
this.cleanupStartupTempDirectories();
|
||||
|
||||
// Check dependencies on startup (async, don't await)
|
||||
this.plugin.checkDependenciesAsync();
|
||||
|
||||
|
||||
// Check dependencies on startup
|
||||
this.plugin.checkDependenciesOnStartup();
|
||||
|
||||
// Cache available fonts (async, don't await)
|
||||
this.plugin.cacheAvailableFonts();
|
||||
void this.plugin.cacheAvailableFonts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up resources during onunload
|
||||
*/
|
||||
cleanup(): void {
|
||||
async cleanup(): Promise<void> {
|
||||
// Cancel any ongoing exports
|
||||
if (this.plugin.currentExportController) {
|
||||
this.plugin.currentExportController.abort();
|
||||
}
|
||||
|
||||
// Clean up temp directories on plugin unload (fire-and-forget async)
|
||||
(async () => {
|
||||
try {
|
||||
const vaultPath = this.pathUtils.getVaultPath();
|
||||
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||
await cleanupManager.cleanupAllTempDirs();
|
||||
} catch (error) {
|
||||
console.warn('Export: Failed to clean up temp directories during unload:', error);
|
||||
}
|
||||
})();
|
||||
|
||||
// Dispose converter to clean up its temp directories
|
||||
if (this.plugin.converter) {
|
||||
await this.plugin.converter.dispose();
|
||||
}
|
||||
|
||||
// Clean up temp directories on plugin unload
|
||||
try {
|
||||
const vaultPath = this.pathUtils.getVaultPath();
|
||||
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||
await cleanupManager.cleanupAllTempDirs();
|
||||
} catch (error) {
|
||||
console.warn('Export: Failed to clean up temp directories during unload:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,11 +88,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
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Setting,
|
||||
normalizePath
|
||||
} from 'obsidian';
|
||||
import * as path from 'path';
|
||||
import type { obsidianTypstPDFExport } from '../../main';
|
||||
import { ExportFormat } from '../core/settings';
|
||||
import { SecurityUtils } from '../core/SecurityUtils';
|
||||
@@ -27,9 +28,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
display(): void {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
|
||||
containerEl.createEl('h2', { text: 'Typst PDF Export Settings' });
|
||||
|
||||
|
||||
// Executable paths section
|
||||
this.createExecutablePathsSection(containerEl);
|
||||
|
||||
@@ -47,14 +46,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();
|
||||
@@ -62,9 +63,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Pandoc path')
|
||||
.setDesc('Path to pandoc executable (leave empty to use system PATH)')
|
||||
.setDesc('Path to pandoc executable (leave empty to use system path)')
|
||||
.addText(text => text
|
||||
.setPlaceholder('pandoc')
|
||||
.setPlaceholder('Pandoc')
|
||||
.setValue(this.plugin.settings.pandocPath)
|
||||
.onChange(async (value) => {
|
||||
if (!SecurityUtils.validateExecutablePath(value)) {
|
||||
@@ -77,9 +78,9 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Typst path')
|
||||
.setDesc('Path to typst executable (leave empty to use system PATH)')
|
||||
.setDesc('Path to typst executable (leave empty to use system path)')
|
||||
.addText(text => text
|
||||
.setPlaceholder('typst')
|
||||
.setPlaceholder('Typst')
|
||||
.setValue(this.plugin.settings.typstPath)
|
||||
.onChange(async (value) => {
|
||||
if (!SecurityUtils.validateExecutablePath(value)) {
|
||||
@@ -91,10 +92,10 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('ImageMagick path')
|
||||
.setDesc('Path to ImageMagick executable (leave empty to use system PATH)')
|
||||
.setName('Imagemagick path')
|
||||
.setDesc('Path to imagemagick executable (leave empty to use system path)')
|
||||
.addText(text => text
|
||||
.setPlaceholder('magick')
|
||||
.setPlaceholder('Magick')
|
||||
.setValue(this.plugin.settings.executablePaths.imagemagickPath)
|
||||
.onChange(async (value) => {
|
||||
if (!SecurityUtils.validateExecutablePath(value)) {
|
||||
@@ -131,11 +132,13 @@ 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')
|
||||
.setDesc('Default Typst template for exports')
|
||||
.setDesc('Default typst template for exports')
|
||||
.addDropdown(async (dropdown) => {
|
||||
try {
|
||||
const templates = await this.plugin.templateManager.getAvailableTemplates();
|
||||
@@ -157,7 +160,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
} catch (error) {
|
||||
console.error('Failed to load templates:', error);
|
||||
// Fallback to text input
|
||||
dropdown.addOption('default.typ', 'default.typ');
|
||||
dropdown.addOption('default.typ', 'Default.typ');
|
||||
dropdown.setValue(this.plugin.settings.exportDefaults.template);
|
||||
}
|
||||
});
|
||||
@@ -176,13 +179,14 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName('Output folder')
|
||||
.setDesc('Default folder for exported PDFs (relative to vault root)')
|
||||
.setDesc('Folder for exported pdfs (relative to vault root)')
|
||||
.addText(text => {
|
||||
text
|
||||
.setPlaceholder('exports')
|
||||
.setPlaceholder('Exports')
|
||||
.setValue(this.plugin.settings.outputFolder)
|
||||
.onChange(async (value) => {
|
||||
const normalizedValue = normalizePath(value);
|
||||
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
|
||||
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
|
||||
ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue));
|
||||
return;
|
||||
@@ -229,7 +233,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(
|
||||
@@ -293,7 +299,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 +371,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')
|
||||
|
||||
@@ -36,15 +36,7 @@ export class TemplateManager {
|
||||
}
|
||||
|
||||
// Read directory contents - convert absolute path to vault-relative
|
||||
const vaultBasePath = this.pathUtils.getVaultPath();
|
||||
let vaultRelativePath = this.templatesPath;
|
||||
|
||||
// Convert absolute path to vault-relative path
|
||||
if (this.templatesPath.startsWith(vaultBasePath)) {
|
||||
vaultRelativePath = this.templatesPath.substring(vaultBasePath.length);
|
||||
// Remove leading separators
|
||||
vaultRelativePath = vaultRelativePath.replace(/^[/\\]+/, '');
|
||||
}
|
||||
const vaultRelativePath = this.pathUtils.toVaultRelative(this.templatesPath);
|
||||
|
||||
const list = await this.plugin.app.vault.adapter.list(vaultRelativePath);
|
||||
const files = list.files.map(filePath => path.basename(filePath));
|
||||
@@ -127,11 +119,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,9 @@ export class EmbeddedTemplateManager {
|
||||
}
|
||||
|
🛠️ Refactor suggestion | 🟠 Major Extract duplicated path conversion logic to PathUtils helper. The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts. Add a Also applies to: 116-125 _🛠️ Refactor suggestion_ | _🟠 Major_
**Extract duplicated path conversion logic to PathUtils helper.**
The vault-relative path conversion is duplicated both within this file (lines 60-69 and 116-125) and across other files in this PR. This is the same duplication issue identified in ImageOptimizer.ts and PdfToImageConverter.ts.
Add a `toVaultRelative()` helper to PathUtils (see detailed suggestion in ImageOptimizer.ts review), then simplify both locations:
```diff
try {
- // Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
- const vaultPath = this.pathUtils.getVaultPath();
- let relativeTemplatesDir = this.templatesDir;
- if (this.templatesDir.startsWith(vaultPath)) {
- relativeTemplatesDir = this.templatesDir.substring(vaultPath.length);
- if (relativeTemplatesDir.startsWith('/') || relativeTemplatesDir.startsWith('\\')) {
- relativeTemplatesDir = relativeTemplatesDir.substring(1);
- }
- }
+ const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
await this.pathUtils.ensureDir(relativeTemplatesDir);
```
Also applies to: 116-125
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
|
||||
|
||||
try {
|
||||
// Ensure templates directory exists
|
||||
await this.pathUtils.ensureDir(this.templatesDir);
|
||||
// Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
|
||||
const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
|
||||
await this.pathUtils.ensureDir(relativeTemplatesDir);
|
||||
|
||||
// Extract template content
|
||||
const content = extractTemplate(templateName, filePath);
|
||||
@@ -105,8 +106,9 @@ export class EmbeddedTemplateManager {
|
||||
|
||||
const embeddedNames = getAllTemplateNames();
|
||||
|
||||
// Ensure templates directory exists
|
||||
await this.pathUtils.ensureDir(this.templatesDir);
|
||||
// Ensure templates directory exists (convert absolute to vault-relative for vault.adapter)
|
||||
const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
|
||||
await this.pathUtils.ensureDir(relativeTemplatesDir);
|
||||
|
||||
for (const templateName of embeddedNames) {
|
||||
try {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
@@ -155,7 +154,20 @@ export class ModalRenderer {
|
||||
text: 'Export',
|
||||
|
⚠️ Potential issue | 🟠 Major Handle potential promise rejection from async onSubmit. The Apply this diff to add proper error handling:
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟠 Major_
**Handle potential promise rejection from async onSubmit.**
The `void` operator correctly discards the promise, but if `onSubmit` is async and throws an error, it will result in an unhandled promise rejection. This could lead to unexpected behavior or silent failures.
Apply this diff to add proper error handling:
```diff
- this.submitButton.addEventListener('click', () => void this.callbacks.onSubmit());
+ this.submitButton.addEventListener('click', async () => {
+ try {
+ await this.callbacks.onSubmit();
+ } catch (error) {
+ console.error('Export failed:', error);
+ // Optionally show error to user via validation errors
+ this.showValidationErrors([`Export failed: ${error instanceof Error ? error.message : String(error)}`]);
+ }
+ });
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/ModalRenderer.ts around line 157, the click handler currently
calls this.callbacks.onSubmit() with the void operator which discards the
returned promise and can create unhandled promise rejections if onSubmit is
async; change the handler to capture the promise and attach error handling
(e.g., call Promise.resolve(this.callbacks.onSubmit()).catch(err => { /*
handle/log error and update UI state */ })) or wrap the invocation in an async
function with try/catch so any thrown/rejected error is caught and handled
appropriately (log the error and provide user-facing feedback or disable the
submit button as needed).
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
|
||||
cls: 'mod-cta'
|
||||
});
|
||||
this.submitButton.addEventListener('click', () => this.callbacks.onSubmit());
|
||||
this.submitButton.addEventListener('click', () => {
|
||||
this.setExportingState(true);
|
||||
Promise.resolve(this.callbacks.onSubmit()).catch(err => {
|
||||
// Log the error for debugging
|
||||
console.error('Export submission failed:', err);
|
||||
|
||||
// Show user-facing error feedback
|
||||
const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred during export';
|
||||
this.showValidationErrors([errorMessage]);
|
||||
|
||||
// Re-enable buttons so user can try again or cancel
|
||||
this.setExportingState(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,7 +231,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 +263,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { Setting, App, normalizePath, DropdownComponent } from 'obsidian';
|
||||
import * as path from 'path';
|
||||
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
||||
import { ExportFormat } from '../../../core/settings';
|
||||
import { FolderSuggest } from '../../components/FolderSuggest';
|
||||
@@ -18,7 +19,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);
|
||||
@@ -72,13 +75,14 @@ export class GeneralSection implements ModalSection {
|
||||
|
||||
|
⚠️ Potential issue | 🟡 Minor Description contradicts absolute path handling. The description states "relative to vault root", but the code on lines 84-85 now accepts and preserves absolute paths. Either update the description to clarify that absolute paths are supported, or remove the absolute path handling to match the description. If absolute paths are intended, consider updating the description: 🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟡 Minor_
**Description contradicts absolute path handling.**
The description states "relative to vault root", but the code on lines 84-85 now accepts and preserves absolute paths. Either update the description to clarify that absolute paths are supported, or remove the absolute path handling to match the description.
If absolute paths are intended, consider updating the description:
```diff
- .setDesc('Location for exported PDF files (relative to vault root)')
+ .setDesc('Location for exported PDF files (relative to vault root, or absolute path)')
```
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/sections/GeneralSection.ts around line 78, the UI description
currently reads "Location for exported PDF files (relative to vault root)" but
the code now accepts and preserves absolute paths; update the description to
accurately reflect that both relative paths (resolved against vault root) and
absolute paths are supported (e.g., "Location for exported PDF files (relative
to vault root or absolute path)") or, if absolute paths are not intended, remove
the absolute-path handling in the code so the behavior matches the original
"relative" wording; ensure text is concise and consistent with the actual path
handling logic.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
|
||||
new Setting(this.container)
|
||||
.setName('Output folder')
|
||||
.setDesc('Folder where PDFs will be saved (relative to vault root)')
|
||||
.setDesc('Location for exported PDF files (relative to vault root or absolute path)')
|
||||
.addText(text => {
|
||||
const input = text
|
||||
.setPlaceholder('exports')
|
||||
.setPlaceholder('PDF exports')
|
||||
.setValue(state.settings.outputFolder || 'exports')
|
||||
.onChange(value => {
|
||||
const normalizedValue = normalizePath(value);
|
||||
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
|
||||
state.updateSettings({ outputFolder: normalizedValue });
|
||||
});
|
||||
this.outputFolderInput = input.inputEl;
|
||||
@@ -102,9 +106,11 @@ export class GeneralSection implements ModalSection {
|
||||
|
||||
// Validate output folder
|
||||
if (this.outputFolderInput) {
|
||||
|
⚠️ Potential issue | 🟠 Major Inconsistent path handling between onChange and validate. The onChange handler preserves absolute paths (line 85), but the validate() method always normalizes paths including absolute ones (line 109). This inconsistency could cause validation to incorrectly handle absolute paths that were previously accepted. Apply this diff to make validation consistent:
🤖 Prompt for AI Agents_⚠️ Potential issue_ | _🟠 Major_
**Inconsistent path handling between onChange and validate.**
The onChange handler preserves absolute paths (line 85), but the validate() method always normalizes paths including absolute ones (line 109). This inconsistency could cause validation to incorrectly handle absolute paths that were previously accepted.
Apply this diff to make validation consistent:
```diff
// Validate output folder
if (this.outputFolderInput) {
- const value = normalizePath(this.outputFolderInput.value.trim());
+ const rawValue = this.outputFolderInput.value.trim();
+ const value = rawValue.startsWith('/') ? rawValue : normalizePath(rawValue);
if (!SecurityUtils.validateOutputPath(value)) {
errors.push(SecurityUtils.getPathValidationError(value));
}
}
```
> Committable suggestion skipped: line range outside the PR's diff.
<details>
<summary>🤖 Prompt for AI Agents</summary>
```
In src/ui/modal/sections/GeneralSection.ts around lines 84-86 and 109,
validation is inconsistent: onChange preserves absolute paths but validate()
always normalizes them. Update validate() to mirror onChange by checking
path.isAbsolute(value) and using the raw value for absolute paths, otherwise
passing normalizePath(value); then run the existing validation logic against
that normalizedValue so absolute paths are treated consistently between onChange
and validate.
```
</details>
<!-- This is an auto-generated comment by CodeRabbit -->
✅ Addressed in commits f0daebc to c1c02ee
|
||||
const value = normalizePath(this.outputFolderInput.value.trim());
|
||||
if (!SecurityUtils.validateOutputPath(value)) {
|
||||
errors.push(SecurityUtils.getPathValidationError(value));
|
||||
const rawValue = this.outputFolderInput.value.trim();
|
||||
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||
const normalizedValue = path.isAbsolute(rawValue) ? rawValue : normalizePath(rawValue);
|
||||
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
|
||||
errors.push(SecurityUtils.getPathValidationError(normalizedValue));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Handles font selection and size configuration
|
||||
*/
|
||||
|
||||
import { Setting, App, DropdownComponent } from 'obsidian';
|
||||
import { Setting, App } from 'obsidian';
|
||||
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
||||
|
||||
export class TypographySection implements ModalSection {
|
||||
@@ -13,36 +13,41 @@ export class TypographySection implements ModalSection {
|
||||
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
||||
|
⚠️ Potential issue | 🟠 Major Add error handling for fire-and-forget async call. The Consider one of these approaches: Option 1: Await the font settings creation Then change the Option 2: Add error handling with void operator As per coding guidelines. 📝 Committable suggestion
🤖 Prompt for AI Agents_⚠️ 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' });
|
||||
|
||||
// Create font settings asynchronously
|
||||
this.createFontSettings(state);
|
||||
this.createFontSizeSettings(state);
|
||||
new Setting(this.container)
|
||||
.setName('Typography')
|
||||
.setHeading();
|
||||
|
||||
// Create font settings asynchronously with explicit error handling
|
||||
// Font size settings are created after font dropdowns to preserve logical ordering
|
||||
this.createFontSettings(state).catch(error => {
|
||||
console.error('Failed to create font settings:', error);
|
||||
// If font loading fails, getAvailableFonts will use hardcoded fallback fonts
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private async createFontSettings(state: ModalState): Promise<void> {
|
||||
if (!this.container) return;
|
||||
|
||||
|
||||
// Get available fonts from cache
|
||||
const availableFonts = await this.getAvailableFonts(state);
|
||||
|
||||
|
||||
// Body font dropdown
|
||||
new Setting(this.container)
|
||||
.setName('Body font')
|
||||
.setDesc('Primary font for document text')
|
||||
.addDropdown(dropdown => {
|
||||
const currentFont = String(state.templateVariables.bodyFont || 'Times New Roman');
|
||||
|
||||
|
||||
// Add all available fonts
|
||||
availableFonts.forEach(font => {
|
||||
dropdown.addOption(font, font);
|
||||
});
|
||||
|
||||
|
||||
// Add current font if it's not in the list
|
||||
if (!availableFonts.includes(currentFont)) {
|
||||
dropdown.addOption(currentFont, currentFont);
|
||||
}
|
||||
|
||||
|
||||
// Set current value and change handler
|
||||
dropdown
|
||||
.setValue(currentFont)
|
||||
@@ -50,24 +55,24 @@ export class TypographySection implements ModalSection {
|
||||
state.updateTemplateVariables({ bodyFont: value });
|
||||
});
|
||||
});
|
||||
|
||||
// Heading font dropdown
|
||||
|
||||
// Heading font dropdown
|
||||
new Setting(this.container)
|
||||
.setName('Heading font')
|
||||
.setDesc('Font for headings and titles')
|
||||
.addDropdown(dropdown => {
|
||||
const currentFont = String(state.templateVariables.headingFont || 'Times New Roman');
|
||||
|
||||
|
||||
// Add all available fonts
|
||||
availableFonts.forEach(font => {
|
||||
dropdown.addOption(font, font);
|
||||
});
|
||||
|
||||
|
||||
// Add current font if it's not in the list
|
||||
if (!availableFonts.includes(currentFont)) {
|
||||
dropdown.addOption(currentFont, currentFont);
|
||||
}
|
||||
|
||||
|
||||
// Set current value and change handler
|
||||
dropdown
|
||||
.setValue(currentFont)
|
||||
@@ -75,24 +80,24 @@ export class TypographySection implements ModalSection {
|
||||
state.updateTemplateVariables({ headingFont: value });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Monospace font dropdown
|
||||
new Setting(this.container)
|
||||
.setName('Monospace font')
|
||||
.setDesc('Font for code blocks and inline code')
|
||||
.addDropdown(dropdown => {
|
||||
const currentFont = String(state.templateVariables.monospaceFont || 'Courier New');
|
||||
|
||||
|
||||
// Add all available fonts
|
||||
availableFonts.forEach(font => {
|
||||
dropdown.addOption(font, font);
|
||||
});
|
||||
|
||||
|
||||
// Add current font if it's not in the list
|
||||
if (!availableFonts.includes(currentFont)) {
|
||||
dropdown.addOption(currentFont, currentFont);
|
||||
}
|
||||
|
||||
|
||||
// Set current value and change handler
|
||||
dropdown
|
||||
.setValue(currentFont)
|
||||
@@ -100,8 +105,11 @@ export class TypographySection implements ModalSection {
|
||||
state.updateTemplateVariables({ monospaceFont: value });
|
||||
});
|
||||
});
|
||||
|
||||
// Create font size settings after font dropdowns for logical ordering
|
||||
this.createFontSizeSettings(state);
|
||||
}
|
||||
|
||||
|
||||
private createFontSizeSettings(state: ModalState): void {
|
||||
if (!this.container) return;
|
||||
|
||||
@@ -160,51 +168,7 @@ export class TypographySection implements ModalSection {
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
private addFallbackBodyFonts(dropdown: DropdownComponent, state: ModalState, fontType: 'body' | 'heading'): void {
|
||||
dropdown
|
||||
.addOption('Concourse OT', 'Concourse OT')
|
||||
.addOption('Times New Roman', 'Times New Roman')
|
||||
.addOption('Georgia', 'Georgia')
|
||||
.addOption('Arial', 'Arial')
|
||||
.addOption('Helvetica', 'Helvetica')
|
||||
.addOption('Calibri', 'Calibri')
|
||||
.addOption('Cambria', 'Cambria')
|
||||
.addOption('Palatino', 'Palatino')
|
||||
.addOption('Book Antiqua', 'Book Antiqua');
|
||||
|
||||
// Set the appropriate value based on font type
|
||||
const currentValue = fontType === 'body'
|
||||
? state.templateVariables.bodyFont
|
||||
: state.templateVariables.headingFont;
|
||||
|
||||
dropdown
|
||||
.setValue(String(currentValue || 'Concourse OT'))
|
||||
.onChange((value: string) => {
|
||||
if (fontType === 'body') {
|
||||
state.updateTemplateVariables({ bodyFont: value });
|
||||
} else {
|
||||
state.updateTemplateVariables({ headingFont: value });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private addFallbackMonospaceFonts(dropdown: DropdownComponent, state: ModalState): void {
|
||||
dropdown
|
||||
.addOption('Source Code Pro', 'Source Code Pro')
|
||||
.addOption('Courier New', 'Courier New')
|
||||
.addOption('Monaco', 'Monaco')
|
||||
.addOption('Consolas', 'Consolas')
|
||||
.addOption('Menlo', 'Menlo')
|
||||
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
|
||||
.addOption('Liberation Mono', 'Liberation Mono')
|
||||
.addOption('Ubuntu Mono', 'Ubuntu Mono')
|
||||
.setValue(String(state.templateVariables.monospaceFont || 'Source Code Pro'))
|
||||
.onChange((value: string) => {
|
||||
state.updateTemplateVariables({ monospaceFont: value });
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
validate(): ValidationResult {
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -11,6 +11,8 @@
|
||||
"importHelpers": true,
|
||||
"isolatedModules": true,
|
||||
"strictNullChecks": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"lib": [
|
||||
"DOM",
|
||||
"ES5",
|
||||
|
||||
⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Modern ESLint configuration pattern.
The configuration correctly uses
projectServicewithimport.meta.dirnamefor TypeScript parser configuration. Note thatimport.meta.dirnamerequires 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:
Length of output: 59
🏁 Script executed:
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.dirnamewith an alternative that supports Node.js 16+ (e.g.,dirname(fileURLToPath(import.meta.url))).🤖 Prompt for AI Agents