From ac20fadef6a102f3bd2ddee07367547217b43011 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:11:44 +0200 Subject: [PATCH 01/60] Guards against empty cache arrays Prevents errors when attempting to process an empty cache. Deletes the cache entry if it is empty to avoid repeatedly attempting to process an invalid cache entry. --- services/promptGenerator.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index 7b8c746..fc7f792 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -118,6 +118,12 @@ export class PromptGeneratorService { return null; } + // Guard against empty cache arrays + if (cached.length === 0) { + this.cache.delete(cacheKey); + return null; + } + const now = new Date().getTime(); const cacheTime = cached[0].timestamp.getTime(); -- 2.36.6 From 847768417ce077f2782542cdd45e81ff53307b43 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:13:03 +0200 Subject: [PATCH 02/60] Updates author and license info Updates the author name to include the last name. Also, changes the plugin license to GPL-3.0-only. --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 22121cf..06649bd 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,8 @@ "version": "node version-bump.mjs && git add manifest.json versions.json" }, "keywords": ["obsidian", "plugin", "writing", "prompts", "ai", "claude", "freewriting"], - "author": "Alexander", - "license": "MIT", + "author": "Alexander Kucera", + "license": "GPL-3.0-only", "devDependencies": { "@types/node": "^16.11.6", "@typescript-eslint/eslint-plugin": "5.29.0", -- 2.36.6 From 9249897d27869d109c94863f38ba4171007f50c6 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:18:13 +0200 Subject: [PATCH 03/60] Prevents race conditions in timed prompts Adds a flag to prevent the timed prompt execution from running concurrently, avoiding potential race conditions and unexpected behavior. Also, addresses edge case in the status check where the displayed current prompt number could be inaccurate. --- commands/timedPrompts.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index e9fc75a..8e8077e 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -9,15 +9,22 @@ export class TimedPromptsCommand { private activeInterval: number | null = null; private promptQueue: string[] = []; private currentIndex = 0; + private inProgress = false; constructor(private promptGenerator: PromptGeneratorService) {} // MARK: - Public Methods async execute(settings: FreewritingPromptsSettings): Promise { + // Check if already in progress to prevent race conditions + if (this.inProgress) { + return; + } + // Stop any existing timed sequence this.stop(); + this.inProgress = true; try { // Generate prompts const prompts = await this.promptGenerator.generateTimedPrompts(settings); @@ -42,6 +49,8 @@ export class TimedPromptsCommand { } catch (error) { console.error('Error executing timed prompts command:', error); // Error handling is done in the service layer + } finally { + this.inProgress = false; } } @@ -52,6 +61,7 @@ export class TimedPromptsCommand { } this.promptQueue = []; this.currentIndex = 0; + this.inProgress = false; } isRunning(): boolean { @@ -100,10 +110,13 @@ export class TimedPromptsCommand { // MARK: - Status Methods getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } { + const totalPrompts = this.promptQueue.length; + const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts); + return { isRunning: this.isRunning(), - currentPrompt: this.currentIndex + 1, - totalPrompts: this.promptQueue.length + currentPrompt, + totalPrompts }; } -- 2.36.6 From d7497c125942d1db3ea787473e77bd7450007bf0 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:19:54 +0200 Subject: [PATCH 04/60] Removes unnecessary error notification The Notice was removed because the error is already being logged to the console and re-thrown. --- api/anthropicClient.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 431682a..9027771 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -50,7 +50,6 @@ export class AnthropicClient { } catch (error) { console.error('Error generating prompts:', error); if (error instanceof Error) { - new Notice(`Failed to generate prompts: ${error.message}`); throw error; } throw new Error('Unknown error occurred while generating prompts'); -- 2.36.6 From b8b701d78b74efd3f41c9795f9279cae8a53c2f7 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:20:00 +0200 Subject: [PATCH 05/60] Simplifies cursor placement after prompt insertion Removes conditional logic for setting the cursor position after inserting a prompt. Now, the cursor is consistently placed at the end of the inserted text, regardless of the previous cursor location. This change ensures consistent behavior and simplifies the code. --- commands/notePrompts.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index ca09b3a..ee61408 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -75,12 +75,7 @@ export class NotePromptsCommand { const newCursorLine = cursor.line + lines.length - 1; const newCursorCh = lines[lines.length - 1].length; - if (cursor.line === lastLine && !needsNewlineBefore) { - // If we were at the last line and didn't add a newline before, adjust - editor.setCursor(cursor.line, cursor.ch + contentToInsert.length); - } else { - editor.setCursor(newCursorLine, newCursorCh); - } + editor.setCursor(newCursorLine, newCursorCh); } private formatPrompts(prompts: string[]): string { -- 2.36.6 From 8b0b4f66072775de8bbfe9865eec6e4ef4cec2fd Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:22:50 +0200 Subject: [PATCH 06/60] Updates repository links and license Updates the repository links in the README to reflect the rename of the repository. Changes the license to GNU General Public License v3 (GPLv3). --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 597d00a..6cae4c1 100644 --- a/README.md +++ b/README.md @@ -226,8 +226,8 @@ The plugin provides detailed error messages for different scenarios: ### Getting Help -- **Issues**: Report bugs on [GitHub Issues](https://github.com/alexanderkucera/obsidian-freewriting-prompts/issues) -- **Discussions**: Ask questions in [GitHub Discussions](https://github.com/alexanderkucera/obsidian-freewriting-prompts/discussions) +- **Issues**: Report bugs on [GitHub Issues](https://github.com/AlexKucera/freewriting-prompts/issues) +- **Discussions**: Ask questions in [GitHub Discussions](https://github.com/AlexKucera/freewriting-prompts/discussions) ## Development @@ -235,8 +235,8 @@ The plugin provides detailed error messages for different scenarios: ```bash # Clone the repository -git clone https://github.com/alexanderkucera/obsidian-freewriting-prompts.git -cd obsidian-freewriting-prompts +git clone https://github.com/AlexKucera/freewriting-prompts.git +cd freewriting-prompts # Install dependencies npm install @@ -284,7 +284,7 @@ Contributions are welcome! Please feel free to submit a Pull Request. ## License -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +This project is licensed under the GNU General Public License v3 (GPLv3) - see the [LICENSE](LICENSE) file for details. ## Support -- 2.36.6 From f58905791224e2dc0570f6fb59c3a5e152b87957 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:23:51 +0200 Subject: [PATCH 07/60] Updates repository URLs in CHANGELOG Updates the repository URLs in the CHANGELOG.md file to reflect the new repository name and location. This ensures that the links to previous versions and comparisons are accurate and functional. --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0e82ca..98b8830 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Input validation for all user settings - Rate limiting awareness with appropriate error handling -[Unreleased]: https://github.com/alexanderkucera/obsidian-freewriting-prompts/compare/1.1.0...HEAD -[1.1.0]: https://github.com/alexanderkucera/obsidian-freewriting-prompts/compare/1.0.0...1.1.0 -[1.0.0]: https://github.com/alexanderkucera/obsidian-freewriting-prompts/releases/tag/1.0.0 \ No newline at end of file +[Unreleased]: https://github.com/AlexKucera/freewriting-prompts/compare/1.1.1...HEAD +[1.1.1]: https://github.com/AlexKucera/freewriting-prompts/compare/1.1.0...1.1.1 +[1.1.0]: https://github.com/AlexKucera/freewriting-prompts/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/AlexKucera/freewriting-prompts/releases/tag/1.0.0 \ No newline at end of file -- 2.36.6 From 8dc28ccd5e284a67848d6e19e77783803654ec97 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:25:03 +0200 Subject: [PATCH 08/60] Updates release action and BRAT repo URL Updates the release action to the latest major version. Also corrects the repository URL in the BRAT installation instructions to reflect the rename of the repository. --- .github/workflows/release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f44eeef..95be913 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -108,7 +108,7 @@ jobs: - name: Create Release id: create_release - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: @@ -127,7 +127,7 @@ jobs: ### BRAT (Beta Reviewer's Auto-update Tool) 1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat) - 2. Add this repository: `alexanderkucera/obsidian-freewriting-prompts` + 2. Add this repository: `AlexKucera/freewriting-prompts` 3. Enable the plugin after installation ### Manual Installation -- 2.36.6 From a79dcec18f087da239afb4638d5821af6bb9bd91 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 26 Sep 2025 08:44:55 +0200 Subject: [PATCH 09/60] Updates CHANGELOG.md with correct release dates Corrects release dates for versions 1.0.0, 1.1.0, and 1.1.1 in the changelog. --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98b8830..cec0c6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [1.1.1] - 2025-01-21 +## [1.1.1] - 2025-09-21 ### Added - Plugin combination recommendations for enhanced writing workflow @@ -25,7 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Enhanced code quality and maintainability - **Settings UI**: Removed redundant "Settings" text from settings tab heading -## [1.1.0] - 2025-01-20 +## [1.1.0] - 2025-09-20 ### Changed - **Enhanced Staggered Prompts**: Now generates ultra-short, direct prompts perfect for quick responses (1-5 words or single sentence) @@ -42,7 +42,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Dynamic notification duration based on user delay settings - Enhanced Claude model support including latest Opus 4.1 and Sonnet models -## [1.0.0] - 2025-01-20 +## [1.0.0] - 2025-09-19 ### Added - **Staggered Freewriting Prompts** command for timed writing sessions -- 2.36.6 From 20530142e4f78b61d5e1c18dbfb9755c64cb81b6 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Thu, 23 Oct 2025 10:17:30 +0200 Subject: [PATCH 10/60] feat: add dynamic model fetching from Anthropic API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace hardcoded model list with dynamic API-based model fetching that queries the Anthropic models endpoint. Implements 24-hour caching with automatic fallback to hardcoded models if API is unavailable. Changes: - Add ModelService to fetch and cache available models from API - Implement 24-hour TTL cache persisted in plugin data - Update AnthropicClient with fetchModels() method - Modify settings UI to load models asynchronously with loading states - Auto-refresh models when API key is entered or changed - Display model names using display_name field from API - Preserve user's selected model across updates and restarts - Show notice when falling back to hardcoded model list - Change model type from strict enum to string for dynamic support Technical details: - New ModelInfo and ModelsListResponse interfaces for API response - ModelCache interface with timestamp for TTL validation - FreewritingPromptsData extends settings to include cache - Settings dropdown disabled during model fetch/refresh - Fallback to ANTHROPIC_MODELS constant on API failure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- api/anthropicClient.ts | 41 ++++++++++-- main.ts | 18 ++++- services/modelService.ts | 129 ++++++++++++++++++++++++++++++++++++ services/promptGenerator.ts | 6 +- settings.ts | 87 ++++++++++++++++++++++-- types.ts | 25 ++++++- 6 files changed, 287 insertions(+), 19 deletions(-) create mode 100644 services/modelService.ts diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 9027771..b8bbaad 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -1,12 +1,13 @@ // ABOUTME: Anthropic API client for generating writing prompts using Claude // ABOUTME: Handles API requests, error handling, and response parsing -import { Notice, requestUrl } from 'obsidian'; -import { AnthropicRequest, AnthropicResponse, AnthropicModel } from '../types'; +import { requestUrl } from 'obsidian'; +import { AnthropicRequest, AnthropicResponse, ModelsListResponse } from '../types'; export class AnthropicClient { private apiKey: string; - private baseUrl = 'https://api.anthropic.com/v1/messages'; + private messagesUrl = 'https://api.anthropic.com/v1/messages'; + private modelsUrl = 'https://api.anthropic.com/v1/models'; private readonly SYSTEM_PROMPT_SUFFIX = '\n\nIMPORTANT OUTPUT REQUIREMENTS:\n- Return ONLY the numbered writing prompts, nothing else\n- Do not include any explanations, questions, or additional commentary\n- Do not ask if the user wants more prompts or different styles\n- Format: numbered list with one prompt per line (1. [prompt], 2. [prompt], etc.)'; private readonly TIMED_PROMPT_MODIFIER = '\n\nFOR TIMED PROMPTS - MAKE THEM EXTREMELY SHORT AND DIRECT:\n- Each prompt should be answerable in 1-5 words or a single sentence\n- Focus on immediate, concrete observations or quick thoughts\n- Avoid complex scenarios or deep philosophical questions\n- Examples: "What color is closest to you?", "Your favorite word today:", "First sound you hear:", "Describe your mood in one word", "Name something soft"\n- Keep prompts simple, immediate, and concrete'; @@ -19,7 +20,7 @@ export class AnthropicClient { async generatePrompts( count: number, - model: AnthropicModel, + model: string, systemPrompt: string, examplePrompt: string, type: 'timed' | 'note' @@ -56,6 +57,34 @@ export class AnthropicClient { } } + async fetchModels(): Promise { + if (!this.apiKey) { + throw new Error('API key is required'); + } + + try { + const response = await requestUrl({ + url: this.modelsUrl, + method: 'GET', + headers: { + 'x-api-key': this.apiKey, + 'anthropic-version': '2023-06-01' + } + }); + + if (response.status < 200 || response.status >= 300) { + throw new Error(`Models API request failed: ${response.status}\n${response.text}`); + } + + return response.json as ModelsListResponse; + } catch (error) { + if (error instanceof Error) { + throw error; + } + throw new Error(`Network request failed: ${String(error)}`); + } + } + // MARK: - Private Methods private createUserMessage(count: number, examplePrompt: string): string { @@ -71,7 +100,7 @@ export class AnthropicClient { private async makeRequest(request: AnthropicRequest): Promise { try { const response = await requestUrl({ - url: this.baseUrl, + url: this.messagesUrl, method: 'POST', headers: { 'Content-Type': 'application/json', @@ -131,7 +160,7 @@ export class AnthropicClient { return !!(this.apiKey && this.apiKey.trim().length > 0); } - async testApiKey(model: AnthropicModel): Promise<{ + async testApiKey(model: string): Promise<{ success: boolean; message: string; details?: { diff --git a/main.ts b/main.ts index 1ec931b..7a9969e 100644 --- a/main.ts +++ b/main.ts @@ -2,15 +2,17 @@ // ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle import { Editor, MarkdownView, Notice, Plugin } from 'obsidian'; -import { FreewritingPromptsSettings } from './types'; +import { FreewritingPromptsSettings, FreewritingPromptsData } from './types'; import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings'; import { PromptGeneratorService } from './services/promptGenerator'; +import { ModelService } from './services/modelService'; import { TimedPromptsCommand } from './commands/timedPrompts'; import { NotePromptsCommand } from './commands/notePrompts'; export default class FreewritingPromptsPlugin extends Plugin { settings: FreewritingPromptsSettings; promptGenerator: PromptGeneratorService; + modelService: ModelService; timedCommand: TimedPromptsCommand; noteCommand: NotePromptsCommand; @@ -19,9 +21,16 @@ export default class FreewritingPromptsPlugin extends Plugin { // Initialize services this.promptGenerator = new PromptGeneratorService(this.settings); + this.modelService = new ModelService(this.promptGenerator.anthropicClient); this.timedCommand = new TimedPromptsCommand(this.promptGenerator); this.noteCommand = new NotePromptsCommand(this.promptGenerator); + // Load model cache + const data = await this.loadData() as FreewritingPromptsData | null; + if (data?.modelCache) { + this.modelService.loadCache(data.modelCache); + } + // Register commands this.registerCommands(); @@ -48,7 +57,12 @@ export default class FreewritingPromptsPlugin extends Plugin { } async saveSettings() { - await this.saveData(this.settings); + // Save settings with model cache + const data: FreewritingPromptsData = { + ...this.settings, + modelCache: this.modelService?.getCache() || undefined + }; + await this.saveData(data); // Update the prompt generator with new settings if (this.promptGenerator) { diff --git a/services/modelService.ts b/services/modelService.ts new file mode 100644 index 0000000..44ebf63 --- /dev/null +++ b/services/modelService.ts @@ -0,0 +1,129 @@ +// ABOUTME: Service for managing Claude model list from Anthropic API +// ABOUTME: Handles fetching, caching with 24-hour TTL, and fallback to hardcoded list + +import { Notice } from 'obsidian'; +import { AnthropicClient } from '../api/anthropicClient'; +import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types'; + +export interface ModelOption { + id: string; + displayName: string; +} + +export class ModelService { + private anthropicClient: AnthropicClient; + private modelCache: ModelCache | null = null; + private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours + + constructor(anthropicClient: AnthropicClient) { + this.anthropicClient = anthropicClient; + } + + // MARK: - Public Methods + + /** + * Get available models with caching and fallback logic + * Returns models from cache if valid, otherwise fetches from API + * Falls back to hardcoded list if API fails + */ + async getAvailableModels(): Promise { + // Check if we have a valid cache + if (this.isCacheValid() && this.modelCache) { + return this.formatModels(this.modelCache.models); + } + + // Try to fetch from API + try { + const response = await this.anthropicClient.fetchModels(); + this.updateCache(response.data); + return this.formatModels(response.data); + } catch (error) { + console.error('Failed to fetch models from API:', error); + new Notice('Fetching current models failed. Using hardcoded fallback list.'); + return this.getFallbackModels(); + } + } + + /** + * Force refresh the model list from API + * Used when user changes API key + */ + async refreshModels(): Promise { + try { + const response = await this.anthropicClient.fetchModels(); + this.updateCache(response.data); + return this.formatModels(response.data); + } catch (error) { + console.error('Failed to refresh models from API:', error); + new Notice('Fetching current models failed. Using hardcoded fallback list.'); + return this.getFallbackModels(); + } + } + + /** + * Load cache from plugin data + */ + loadCache(cache: ModelCache | null): void { + this.modelCache = cache; + } + + /** + * Get current cache for saving to plugin data + */ + getCache(): ModelCache | null { + return this.modelCache; + } + + /** + * Clear the cache (for testing or manual refresh) + */ + clearCache(): void { + this.modelCache = null; + } + + // MARK: - Private Methods + + /** + * Check if the current cache is still valid (within TTL) + */ + private isCacheValid(): boolean { + if (!this.modelCache) { + return false; + } + + const now = Date.now(); + const age = now - this.modelCache.fetchedAt; + return age < this.CACHE_TTL_MS; + } + + /** + * Update cache with new model data + */ + private updateCache(models: ModelInfo[]): void { + this.modelCache = { + models, + fetchedAt: Date.now() + }; + } + + /** + * Format ModelInfo array to ModelOption array for dropdown + * Uses display_name if available, otherwise falls back to id + */ + private formatModels(models: ModelInfo[]): ModelOption[] { + return models.map(model => ({ + id: model.id, + displayName: model.display_name || model.id + })); + } + + /** + * Get fallback models from hardcoded list + */ + private getFallbackModels(): ModelOption[] { + return ANTHROPIC_MODELS.map(id => ({ + id, + displayName: id + })); + } +} diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index fc7f792..5b3f3fd 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -3,7 +3,7 @@ import { Notice } from 'obsidian'; import { AnthropicClient } from '../api/anthropicClient'; -import { FreewritingPromptsSettings, GeneratedPrompt, AnthropicModel } from '../types'; +import { FreewritingPromptsSettings, GeneratedPrompt } from '../types'; export class PromptGeneratorService { private client: AnthropicClient; @@ -54,7 +54,7 @@ export class PromptGeneratorService { private async generatePrompts( count: number, - model: AnthropicModel, + model: string, systemPrompt: string, examplePrompt: string, type: 'timed' | 'note' @@ -97,7 +97,7 @@ export class PromptGeneratorService { private createCacheKey( count: number, - model: AnthropicModel, + model: string, systemPrompt: string, examplePrompt: string, type: string diff --git a/settings.ts b/settings.ts index bfb1ef3..803f532 100644 --- a/settings.ts +++ b/settings.ts @@ -1,9 +1,10 @@ // ABOUTME: Settings interface and SettingTab implementation for the Freewriting Prompts plugin // ABOUTME: Handles user configuration including API key, model selection, and prompt customization -import { App, ButtonComponent, Notice, PluginSettingTab, Setting } from 'obsidian'; +import { App, ButtonComponent, DropdownComponent, Notice, PluginSettingTab, Setting } from 'obsidian'; import FreewritingPromptsPlugin from './main'; -import { FreewritingPromptsSettings, ANTHROPIC_MODELS, AnthropicModel } from './types'; +import { FreewritingPromptsSettings } from './types'; +import { ModelOption } from './services/modelService'; export const DEFAULT_SETTINGS: FreewritingPromptsSettings = { apiKey: '', @@ -18,18 +19,23 @@ export const DEFAULT_SETTINGS: FreewritingPromptsSettings = { export class FreewritingPromptsSettingTab extends PluginSettingTab { plugin: FreewritingPromptsPlugin; + private modelDropdown: DropdownComponent | null = null; + private availableModels: ModelOption[] = []; constructor(app: App, plugin: FreewritingPromptsPlugin) { super(app, plugin); this.plugin = plugin; } - display(): void { + async display(): Promise { const { containerEl } = this; containerEl.empty(); containerEl.createEl('h2', { text: 'Freewriting Prompts' }); + // Load models asynchronously + await this.loadModels(); + // MARK: - API Configuration containerEl.createEl('h3', { text: 'API Configuration' }); @@ -44,6 +50,11 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); this.plugin.promptGenerator.updateApiKey(value); + + // Trigger model refresh when API key is entered + if (value.trim().length > 0) { + await this.refreshModels(); + } })) .then(setting => { // Make it a password field @@ -63,13 +74,12 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .setName('Claude Model') .setDesc('Which Claude model to use for generating prompts') .addDropdown(dropdown => { - ANTHROPIC_MODELS.forEach(model => { - dropdown.addOption(model, model); - }); + this.modelDropdown = dropdown; + this.populateModelDropdown(dropdown); dropdown .setValue(this.plugin.settings.model) .onChange(async (value) => { - this.plugin.settings.model = value as AnthropicModel; + this.plugin.settings.model = value; await this.plugin.saveSettings(); }); }); @@ -183,6 +193,69 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { })); } + // MARK: - Model Loading + + private async loadModels(): Promise { + try { + this.availableModels = await this.plugin.modelService.getAvailableModels(); + } catch (error) { + console.error('Error loading models:', error); + // Error already shown by ModelService via Notice + // availableModels will be empty array, dropdown will be disabled + } + } + + private populateModelDropdown(dropdown: DropdownComponent): void { + if (this.availableModels.length === 0) { + // No models available yet, disable dropdown + dropdown.addOption('', 'Loading models...'); + dropdown.setDisabled(true); + return; + } + + // Clear existing options + dropdown.selectEl.empty(); + + // Add all available models + this.availableModels.forEach(model => { + dropdown.addOption(model.id, model.displayName); + }); + + dropdown.setDisabled(false); + } + + private async refreshModels(): Promise { + try { + // Disable dropdown during refresh + if (this.modelDropdown) { + this.modelDropdown.setDisabled(true); + this.modelDropdown.selectEl.empty(); + this.modelDropdown.addOption('', 'Refreshing models...'); + } + + // Fetch new models + this.availableModels = await this.plugin.modelService.refreshModels(); + + // Update dropdown + if (this.modelDropdown) { + this.populateModelDropdown(this.modelDropdown); + + // Restore selected model if it still exists + const currentModel = this.plugin.settings.model; + const modelExists = this.availableModels.some(m => m.id === currentModel); + if (modelExists) { + this.modelDropdown.setValue(currentModel); + } + } + + // Save updated cache + await this.plugin.saveSettings(); + } catch (error) { + console.error('Error refreshing models:', error); + // Error already shown by ModelService via Notice + } + } + // MARK: - API Testing private async testApiKey(button: ButtonComponent): Promise { diff --git a/types.ts b/types.ts index 8319552..b83c723 100644 --- a/types.ts +++ b/types.ts @@ -3,7 +3,7 @@ export interface FreewritingPromptsSettings { apiKey: string; - model: AnthropicModel; + model: string; // Changed from AnthropicModel to string to support dynamic models timedCount: number; delaySeconds: number; noteCount: number; @@ -12,6 +12,10 @@ export interface FreewritingPromptsSettings { freewritingExamplePrompt: string; } +export interface FreewritingPromptsData extends FreewritingPromptsSettings { + modelCache?: ModelCache; +} + export interface AnthropicMessage { role: 'user' | 'assistant' | 'system'; content: string; @@ -46,6 +50,25 @@ export interface GeneratedPrompt { timestamp: Date; } +export interface ModelInfo { + id: string; + display_name?: string; + created_at: string; + type: string; +} + +export interface ModelsListResponse { + data: ModelInfo[]; + first_id: string; + has_more: boolean; + last_id: string; +} + +export interface ModelCache { + models: ModelInfo[]; + fetchedAt: number; +} + export const ANTHROPIC_MODELS = [ 'claude-opus-4-1-20250805', 'claude-opus-4-20250514', -- 2.36.6 From c06afe7a4a178b3bcfb48db0833b78264e176679 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:18:23 +0200 Subject: [PATCH 11/60] Updates project license badge to GPL v3 Replaces MIT license badge with GPL v3 license badge in README Ensures accurate representation of project licensing information --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6cae4c1..ff85bc0 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Freewriting Prompts [![GitHub release (latest by date)](https://img.shields.io/github/v/release/AlexKucera/freewriting-prompts?color=blue)](https://github.com/AlexKucera/freewriting-prompts/releases) -[![License: MIT](https://img.shields.io/github/license/AlexKucera/freewriting-prompts?color=yellow)](https://opensource.org/licenses/MIT) +[![License: GPL v3](https://img.shields.io/github/license/AlexKucera/freewriting-prompts?color=yellow)](https://www.gnu.org/licenses/gpl-3.0) [![Downloads](https://img.shields.io/github/downloads/AlexKucera/freewriting-prompts/total?color=green)](https://github.com/AlexKucera/freewriting-prompts/releases) [![CodeRabbit Reviews](https://img.shields.io/coderabbit/prs/github/AlexKucera/freewriting-prompts)](https://coderabbit.ai/) ![](https://img.shields.io/badge/mobile_supported-green?label=obsidian&labelColor=purple) -- 2.36.6 From 6875a7c06c5ab54dafbe61a9445896523bbd5a17 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:18:29 +0200 Subject: [PATCH 12/60] Adds user notification for ongoing timed prompts Prevents multiple simultaneous timed prompt generations by displaying a notice when an operation is already in progress Improves user experience by providing clear feedback during concurrent prompt generation attempts --- commands/timedPrompts.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index 8e8077e..9cb012a 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -18,6 +18,7 @@ export class TimedPromptsCommand { async execute(settings: FreewritingPromptsSettings): Promise { // Check if already in progress to prevent race conditions if (this.inProgress) { + new Notice('Timed prompts are already being generated. Please wait.'); return; } -- 2.36.6 From 4164471ed08eb388bbbe4e7fe7f78d329c2bb698 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:21:02 +0200 Subject: [PATCH 13/60] Adds fallback for unavailable AI models Handles scenario where previously selected AI model is no longer available Automatically selects the first available model and notifies the user when their current model is removed, improving user experience and preventing potential configuration errors --- settings.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/settings.ts b/settings.ts index 803f532..6fd9ee0 100644 --- a/settings.ts +++ b/settings.ts @@ -245,6 +245,11 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { const modelExists = this.availableModels.some(m => m.id === currentModel); if (modelExists) { this.modelDropdown.setValue(currentModel); + } else if (this.availableModels.length > 0) { + // Fall back to first available model if current one is gone + this.plugin.settings.model = this.availableModels[0].id; + this.modelDropdown.setValue(this.availableModels[0].id); + new Notice('Your selected model is no longer available. Defaulting to ' + this.availableModels[0].displayName); } } -- 2.36.6 From 766eb26df3d9bb22c052a1433e13e5049f9306b2 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:22:33 +0200 Subject: [PATCH 14/60] Improves model fetch error notification message Updates error notification to provide clearer feedback when API model retrieval fails Enhances user experience by making the fallback model list error message more descriptive and informative --- services/modelService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/modelService.ts b/services/modelService.ts index 44ebf63..29166f6 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -39,7 +39,7 @@ export class ModelService { return this.formatModels(response.data); } catch (error) { console.error('Failed to fetch models from API:', error); - new Notice('Fetching current models failed. Using hardcoded fallback list.'); + new Notice('Could not fetch latest models from API. Using default model list.'); return this.getFallbackModels(); } } -- 2.36.6 From 8e19f6bc8ff3f07001b756279692bd6275ce2376 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:23:29 +0200 Subject: [PATCH 15/60] Simplifies data loading and initialization logic Combines data loading for settings and model cache Reduces redundant data loading steps and improves initialization efficiency Supports dynamic model handling on the dynamic-models branch --- main.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/main.ts b/main.ts index 7a9969e..16f05d9 100644 --- a/main.ts +++ b/main.ts @@ -17,7 +17,9 @@ export default class FreewritingPromptsPlugin extends Plugin { noteCommand: NotePromptsCommand; async onload() { - await this.loadSettings(); + // Load data once and use it for both settings and model cache + const data = await this.loadData() as FreewritingPromptsData | null; + this.settings = Object.assign({}, DEFAULT_SETTINGS, data); // Initialize services this.promptGenerator = new PromptGeneratorService(this.settings); @@ -26,7 +28,6 @@ export default class FreewritingPromptsPlugin extends Plugin { this.noteCommand = new NotePromptsCommand(this.promptGenerator); // Load model cache - const data = await this.loadData() as FreewritingPromptsData | null; if (data?.modelCache) { this.modelService.loadCache(data.modelCache); } -- 2.36.6 From 435af4ccab81b70759ee430437918d3d34e55133 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:24:09 +0200 Subject: [PATCH 16/60] Adds required Claude model validation check Enforces Claude model selection as a mandatory setting Prevents configuration submission without specifying a valid Claude model to ensure proper API interaction and prevent potential errors --- services/promptGenerator.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index 5b3f3fd..d39e502 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -144,6 +144,10 @@ export class PromptGeneratorService { errors.push('API key is required'); } + if (!settings.model || settings.model.trim().length === 0) { + errors.push('Claude model is required'); + } + if (settings.timedCount < 1 || settings.timedCount > 50) { errors.push('Timed count must be between 1 and 50'); } -- 2.36.6 From 7932663d2a3064141d01085141be3637d16644a9 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:25:36 +0200 Subject: [PATCH 17/60] Adds type refinement for dynamic model selection Introduces ModelId type alias to clarify model ID intent Refines prompt generator type to support specific prompt types Improves type safety for model and prompt configuration --- services/promptGenerator.ts | 2 +- types.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index d39e502..58fa933 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -100,7 +100,7 @@ export class PromptGeneratorService { model: string, systemPrompt: string, examplePrompt: string, - type: string + type: 'timed' | 'note' ): string { const keyData = { count, diff --git a/types.ts b/types.ts index b83c723..a535450 100644 --- a/types.ts +++ b/types.ts @@ -1,9 +1,12 @@ // ABOUTME: Type definitions for the Freewriting Prompts plugin // ABOUTME: Defines interfaces for settings, API responses, and plugin configuration +// Type alias to document intent that this should be a Claude model ID +export type ModelId = string; + export interface FreewritingPromptsSettings { apiKey: string; - model: string; // Changed from AnthropicModel to string to support dynamic models + model: ModelId; // Changed from AnthropicModel to string to support dynamic models timedCount: number; delaySeconds: number; noteCount: number; -- 2.36.6 From e06b07eb26985d52783dcfb55e51de365d0e60f8 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:26:48 +0200 Subject: [PATCH 18/60] Adds API key validation and model sorting Improves model retrieval by adding API key validation check for both model fetching methods Adds fallback to predefined models when no API key is present Sorts model lists alphabetically by display name for consistent presentation Enhances robustness of model service handling --- services/modelService.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 29166f6..9fe2743 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -32,6 +32,11 @@ export class ModelService { return this.formatModels(this.modelCache.models); } + // If no API key, quietly return fallback + if (!this.anthropicClient.validateApiKey()) { + return this.getFallbackModels(); + } + // Try to fetch from API try { const response = await this.anthropicClient.fetchModels(); @@ -49,6 +54,11 @@ export class ModelService { * Used when user changes API key */ async refreshModels(): Promise { + // If no API key, quietly return fallback + if (!this.anthropicClient.validateApiKey()) { + return this.getFallbackModels(); + } + try { const response = await this.anthropicClient.fetchModels(); this.updateCache(response.data); @@ -114,7 +124,7 @@ export class ModelService { return models.map(model => ({ id: model.id, displayName: model.display_name || model.id - })); + })).sort((a, b) => a.displayName.localeCompare(b.displayName)); } /** @@ -124,6 +134,6 @@ export class ModelService { return ANTHROPIC_MODELS.map(id => ({ id, displayName: id - })); + })).sort((a, b) => a.displayName.localeCompare(b.displayName)); } } -- 2.36.6 From e8443a878d3a9a7beff6f821350c98ac4fba06aa Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:27:50 +0200 Subject: [PATCH 19/60] Improves model selection fallback handling Adds null check when selecting fallback model to prevent potential errors Ensures graceful handling when the current model becomes unavailable by verifying a fallback model exists before setting it --- settings.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/settings.ts b/settings.ts index 6fd9ee0..b59908d 100644 --- a/settings.ts +++ b/settings.ts @@ -245,15 +245,18 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { const modelExists = this.availableModels.some(m => m.id === currentModel); if (modelExists) { this.modelDropdown.setValue(currentModel); - } else if (this.availableModels.length > 0) { + } else { // Fall back to first available model if current one is gone - this.plugin.settings.model = this.availableModels[0].id; - this.modelDropdown.setValue(this.availableModels[0].id); - new Notice('Your selected model is no longer available. Defaulting to ' + this.availableModels[0].displayName); + const fallbackModel = this.availableModels[0]; + if (fallbackModel) { + this.modelDropdown.setValue(fallbackModel.id); + this.plugin.settings.model = fallbackModel.id; + new Notice('Your selected model is no longer available. Defaulting to ' + fallbackModel.displayName); + } } } - // Save updated cache + // Persist any selection changes await this.plugin.saveSettings(); } catch (error) { console.error('Error refreshing models:', error); -- 2.36.6 From 6ccfb9e023d36f5c504e82a297225b67f89ad596 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 11:29:33 +0200 Subject: [PATCH 20/60] Optimizes token usage for timed prompts Reduces max tokens for timed prompts to improve latency and cost-efficiency Introduces dynamic max_tokens configuration based on prompt type, using a smaller token limit for time-sensitive requests --- api/anthropicClient.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index b8bbaad..4abb333 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -39,9 +39,12 @@ export class AnthropicClient { } finalSystemPrompt += this.SYSTEM_PROMPT_SUFFIX; + // Use smaller max_tokens for timed prompts to reduce latency/cost + const maxTokens = type === 'timed' ? 256 : 1000; + const request: AnthropicRequest = { model, - max_tokens: 1000, + max_tokens: maxTokens, messages: [{ role: 'user', content: userMessage }], system: finalSystemPrompt }; -- 2.36.6 From 92e109e2e810deb3a0732a2d2091069b3e8a43bb Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 12:59:19 +0200 Subject: [PATCH 21/60] Fixes timed prompts generation race condition Reorders initialization of in-progress flag to prevent potential race conditions during timed prompt generation Ensures that the in-progress status is set before stopping existing sequences and generates prompts --- commands/timedPrompts.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index 9cb012a..c05c46a 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -21,11 +21,13 @@ export class TimedPromptsCommand { new Notice('Timed prompts are already being generated. Please wait.'); return; } + + this.inProgress = true; // Stop any existing timed sequence this.stop(); - this.inProgress = true; + try { // Generate prompts const prompts = await this.promptGenerator.generateTimedPrompts(settings); -- 2.36.6 From 361f946d879981b2724f4206b9286adfb06c8b51 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:00:02 +0200 Subject: [PATCH 22/60] Improves async model loading for settings UI Refactors model loading to prevent UI blocking Adds fallback mechanism for model selection Ensures smooth dropdown population and model persistence Handles cases where previously selected model may no longer be available --- settings.ts | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/settings.ts b/settings.ts index b59908d..ccbb609 100644 --- a/settings.ts +++ b/settings.ts @@ -33,9 +33,6 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { containerEl.createEl('h2', { text: 'Freewriting Prompts' }); - // Load models asynchronously - await this.loadModels(); - // MARK: - API Configuration containerEl.createEl('h3', { text: 'API Configuration' }); @@ -84,6 +81,9 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { }); }); + // Load models asynchronously without blocking UI + this.loadModelsAsync(); + // MARK: - Command Configuration containerEl.createEl('h3', { text: 'Command Configuration' }); @@ -205,6 +205,34 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { } } + /** + * Load models asynchronously without blocking UI rendering + * Updates dropdown when models are fetched + */ + private async loadModelsAsync(): Promise { + await this.loadModels(); + + // Update dropdown after models are loaded + if (this.modelDropdown) { + this.populateModelDropdown(this.modelDropdown); + + // Restore selected model if it still exists + const currentModel = this.plugin.settings.model; + const modelExists = this.availableModels.some(m => m.id === currentModel); + if (modelExists) { + this.modelDropdown.setValue(currentModel); + } else { + // Fall back to first available model if current one is gone + const fallbackModel = this.availableModels[0]; + if (fallbackModel) { + this.modelDropdown.setValue(fallbackModel.id); + this.plugin.settings.model = fallbackModel.id; + await this.plugin.saveSettings(); + } + } + } + } + private populateModelDropdown(dropdown: DropdownComponent): void { if (this.availableModels.length === 0) { // No models available yet, disable dropdown -- 2.36.6 From 03d2b1c93df48dd4cc12a717d9b549495a93cbbf Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:00:31 +0200 Subject: [PATCH 23/60] Adds robust model list response validation Improves models API response handling by adding structural validation Ensures that the API response contains an array of model data before processing Prevents potential runtime errors from unexpected response formats --- api/anthropicClient.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 4abb333..36dcd22 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -79,7 +79,13 @@ export class AnthropicClient { throw new Error(`Models API request failed: ${response.status}\n${response.text}`); } - return response.json as ModelsListResponse; + // Validate basic response structure + const data = response.json as any; + if (!data || !Array.isArray(data.data)) { + throw new Error('Invalid models API response structure'); + } + + return data as ModelsListResponse; } catch (error) { if (error instanceof Error) { throw error; -- 2.36.6 From e96ef652008195f3696e31810f7c4c91b7a475fb Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:09:10 +0200 Subject: [PATCH 24/60] Added DocStrings --- api/anthropicClient.ts | 124 +++++++++++++++++++++++++++++++++++ commands/notePrompts.ts | 88 +++++++++++++++++++++++++ commands/timedPrompts.ts | 90 ++++++++++++++++++++++++++ main.ts | 101 +++++++++++++++++++++++++++++ services/modelService.ts | 98 ++++++++++++++++++++++++---- services/promptGenerator.ts | 126 +++++++++++++++++++++++++++++++++++- settings.ts | 98 +++++++++++++++++++++++++++- types.ts | 89 ++++++++++++++++++++++++- 8 files changed, 797 insertions(+), 17 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 36dcd22..68d8d83 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -4,20 +4,66 @@ import { requestUrl } from 'obsidian'; import { AnthropicRequest, AnthropicResponse, ModelsListResponse } from '../types'; +/** + * Client for interacting with the Anthropic API to generate writing prompts. + * Handles authentication, request formatting, error handling, and response parsing. + * + * This client manages two key responsibilities: + * 1. Generating writing prompts using the Messages API + * 2. Fetching available Claude models using the Models API + * + * It includes type-specific prompt modifiers to ensure timed prompts are short + * and immediate while note prompts can be more elaborate and creative. + */ export class AnthropicClient { private apiKey: string; + /** Base URL for the Anthropic Messages API endpoint */ private messagesUrl = 'https://api.anthropic.com/v1/messages'; + /** Base URL for the Anthropic Models API endpoint */ private modelsUrl = 'https://api.anthropic.com/v1/models'; + + /** + * Suffix appended to all system prompts to enforce consistent output format. + * Ensures Claude returns only numbered prompts without additional commentary, + * which simplifies parsing and provides a predictable user experience. + */ private readonly SYSTEM_PROMPT_SUFFIX = '\n\nIMPORTANT OUTPUT REQUIREMENTS:\n- Return ONLY the numbered writing prompts, nothing else\n- Do not include any explanations, questions, or additional commentary\n- Do not ask if the user wants more prompts or different styles\n- Format: numbered list with one prompt per line (1. [prompt], 2. [prompt], etc.)'; + /** + * Additional instructions for timed prompts to make them extremely brief. + * Timed prompts appear as notifications and need to be answerable quickly, + * so we enforce a short, concrete style optimized for rapid freewriting. + */ private readonly TIMED_PROMPT_MODIFIER = '\n\nFOR TIMED PROMPTS - MAKE THEM EXTREMELY SHORT AND DIRECT:\n- Each prompt should be answerable in 1-5 words or a single sentence\n- Focus on immediate, concrete observations or quick thoughts\n- Avoid complex scenarios or deep philosophical questions\n- Examples: "What color is closest to you?", "Your favorite word today:", "First sound you hear:", "Describe your mood in one word", "Name something soft"\n- Keep prompts simple, immediate, and concrete'; + /** + * Creates a new Anthropic API client. + * @param apiKey - The Anthropic API key for authentication + */ constructor(apiKey: string) { this.apiKey = apiKey; } // MARK: - Public Methods + /** + * Generates writing prompts using the Claude API. + * + * This method constructs an appropriate prompt based on the type (timed vs note), + * applies relevant system instructions, and parses the response into an array + * of clean prompt strings. + * + * Timed prompts use fewer tokens (256) for faster generation and lower cost, + * while note prompts use more tokens (1000) for richer, more elaborate prompts. + * + * @param count - Number of prompts to generate + * @param model - Claude model ID to use (e.g., 'claude-3-5-haiku-latest') + * @param systemPrompt - Base system instructions for the AI + * @param examplePrompt - Example prompt to guide the style + * @param type - Whether this is for 'timed' notifications or 'note' insertion + * @returns Array of generated prompt strings + * @throws Error if API key is missing or API request fails + */ async generatePrompts( count: number, model: string, @@ -60,6 +106,16 @@ export class AnthropicClient { } } + /** + * Fetches the list of available Claude models from the Anthropic API. + * + * This is used to populate the model selection dropdown in settings with + * current available models rather than relying solely on hardcoded lists. + * The response is cached by ModelService with a 24-hour TTL. + * + * @returns Response containing array of available models with metadata + * @throws Error if API key is missing, request fails, or response is malformed + */ async fetchModels(): Promise { if (!this.apiKey) { throw new Error('API key is required'); @@ -96,6 +152,16 @@ export class AnthropicClient { // MARK: - Private Methods + /** + * Constructs the user message for prompt generation requests. + * + * If an example prompt is provided, it's included to guide the AI's style. + * The message emphasizes the exact output format needed for reliable parsing. + * + * @param count - Number of prompts requested + * @param examplePrompt - Optional example to demonstrate desired style + * @returns Formatted user message string + */ private createUserMessage(count: number, examplePrompt: string): string { const baseMessage = `Generate exactly ${count} creative writing prompts. Return ONLY the numbered prompts with no additional text or commentary.`; @@ -106,6 +172,16 @@ export class AnthropicClient { return `${baseMessage}\n\nProvide ${count} diverse writing prompts in this exact format:\n1. [prompt]\n2. [prompt]\n(etc.)`; } + /** + * Makes an HTTP request to the Anthropic Messages API. + * + * Handles authentication headers, request serialization, and basic error checking. + * Uses Obsidian's requestUrl for compatibility with the plugin environment. + * + * @param request - Structured request payload for the API + * @returns Parsed API response + * @throws Error if request fails or returns non-2xx status + */ private async makeRequest(request: AnthropicRequest): Promise { try { const response = await requestUrl({ @@ -132,6 +208,18 @@ export class AnthropicClient { } } + /** + * Parses writing prompts from the API response. + * + * Extracts text content, splits by newlines, removes numbering prefixes, + * and cleans whitespace to produce an array of ready-to-use prompt strings. + * + * This parsing assumes the AI follows the format specified in SYSTEM_PROMPT_SUFFIX. + * + * @param response - API response containing generated content + * @returns Array of cleaned prompt strings + * @throws Error if response is empty or contains no valid prompts + */ private parsePromptsFromResponse(response: AnthropicResponse): string[] { if (!response.content || response.content.length === 0) { throw new Error('No content received from API'); @@ -161,14 +249,39 @@ export class AnthropicClient { // MARK: - Configuration Methods + /** + * Updates the API key used for authentication. + * Called when the user changes their API key in settings. + * + * @param apiKey - New Anthropic API key + */ updateApiKey(apiKey: string): void { this.apiKey = apiKey; } + /** + * Validates that an API key is configured and non-empty. + * + * @returns true if API key exists and has content, false otherwise + */ validateApiKey(): boolean { return !!(this.apiKey && this.apiKey.trim().length > 0); } + /** + * Tests the configured API key by making a minimal request to Claude. + * + * This method sends a simple "ping" request to verify: + * - The API key is valid and authorized + * - The network connection works + * - The selected model is available + * + * It uses minimal tokens (max_tokens: 10) to keep costs negligible while + * still exercising the full authentication and request pipeline. + * + * @param model - Claude model ID to test with + * @returns Detailed test result including success status, timing, and error details + */ async testApiKey(model: string): Promise<{ success: boolean; message: string; @@ -218,6 +331,17 @@ export class AnthropicClient { } } + /** + * Parses errors from API test attempts into user-friendly messages. + * + * Categorizes errors by HTTP status code and error type to provide + * specific troubleshooting guidance. This helps users quickly identify + * whether the issue is with their API key, account, network, or the service. + * + * @param error - Caught error object (typically an Error instance) + * @param responseTime - How long the request took before failing + * @returns Structured error result with categorization and guidance + */ private parseTestError(error: unknown, responseTime: number): { success: boolean; message: string; diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index ee61408..40e2e63 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -5,11 +5,46 @@ import { App, Editor, MarkdownView, Notice } from 'obsidian'; import { PromptGeneratorService } from '../services/promptGenerator'; import { FreewritingPromptsSettings } from '../types'; +/** + * Command handler for inserting writing prompts directly into notes. + * + * This command generates prompts and inserts them at the cursor position in + * the active note as formatted markdown. Unlike timed prompts, these are + * persistent and remain in the note for reference. + * + * Key responsibilities: + * - Validates editor and view state before execution + * - Generates prompts via the prompt service + * - Formats prompts with timestamp and numbering + * - Inserts at cursor with intelligent newline handling + * - Positions cursor after inserted content + * + * The formatting includes a timestamp to help users track when prompts were + * added, and numbered list format for easy reference. + */ export class NotePromptsCommand { + /** + * Creates a new note prompts command handler. + * + * @param promptGenerator - Service for generating prompts from the API + */ constructor(private promptGenerator: PromptGeneratorService) {} // MARK: - Public Methods + /** + * Executes the note prompts insertion. + * + * This method: + * 1. Validates that editor and view are available + * 2. Generates prompts through the service + * 3. Formats and inserts prompts at the cursor position + * 4. Shows success feedback to the user + * + * @param settings - Current plugin settings for generation parameters + * @param editor - Active editor instance for text insertion + * @param view - Active markdown view for context + */ async execute( settings: FreewritingPromptsSettings, editor: Editor, @@ -42,6 +77,20 @@ export class NotePromptsCommand { // MARK: - Private Methods + /** + * Inserts formatted prompts into the note at the cursor position. + * + * This method handles several edge cases: + * - Adds newline before if cursor is on a line with content + * - Adds newline after if cursor is not at end of document + * - Positions cursor at the end of inserted content + * + * The intelligent newline handling ensures prompts don't run into existing + * text and maintains proper spacing in the document. + * + * @param editor - Editor instance for text manipulation + * @param prompts - Array of prompt strings to insert + */ private insertPromptsIntoNote(editor: Editor, prompts: string[]): void { const cursor = editor.getCursor(); const currentLine = editor.getLine(cursor.line); @@ -78,6 +127,24 @@ export class NotePromptsCommand { editor.setCursor(newCursorLine, newCursorCh); } + /** + * Formats prompts as markdown with timestamp header and numbered list. + * + * The format is: + * ``` + * ## Writing Prompts (Jan 15, 2025, 02:30 PM) + * + * 1. [First prompt] + * + * 2. [Second prompt] + * ``` + * + * The timestamp helps users track when prompts were generated, and the + * numbered list makes it easy to reference specific prompts. + * + * @param prompts - Array of prompt strings to format + * @returns Formatted markdown string ready for insertion + */ private formatPrompts(prompts: string[]): string { const timestamp = new Date().toLocaleDateString('en-US', { year: 'numeric', @@ -98,10 +165,31 @@ export class NotePromptsCommand { // MARK: - Utility Methods + /** + * Checks whether the command can be executed in the current context. + * + * Validates that: + * - Editor instance exists + * - Markdown view exists + * - An actual file is open (not just an empty pane) + * + * @param editor - Editor instance to validate + * @param view - Markdown view to validate + * @returns true if command can execute, false otherwise + */ static canExecute(editor: Editor, view: MarkdownView): boolean { return !!(editor && view && view.file); } + /** + * Retrieves the current execution context from the app. + * + * Helper method for getting the active editor and view without having + * them explicitly passed. Useful for manual command invocation. + * + * @param app - Obsidian app instance + * @returns Object containing editor and view, or nulls if not available + */ static getExecutionContext(app: App): { editor: Editor | null; view: MarkdownView | null } { const activeView = app.workspace.getActiveViewOfType(MarkdownView); diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index c05c46a..1d9607a 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -5,16 +5,57 @@ import { Notice } from 'obsidian'; import { PromptGeneratorService } from '../services/promptGenerator'; import { FreewritingPromptsSettings } from '../types'; +/** + * Command handler for displaying timed writing prompts as notifications. + * + * This command manages a sequence of prompts shown at regular intervals, useful + * for freewriting sessions where the writer wants periodic prompts to maintain + * creative flow. + * + * Key responsibilities: + * - Generates a queue of prompts upfront (prevents race conditions) + * - Displays prompts as timed Obsidian notifications + * - Manages window.setInterval for timed display + * - Prevents concurrent executions with inProgress flag + * - Provides proper cleanup to prevent memory leaks + * + * The notification duration is calibrated to avoid overlap - each notification + * disappears 500ms before the next one appears for a clean transition. + */ export class TimedPromptsCommand { + /** Active interval ID from window.setInterval, null when not running */ private activeInterval: number | null = null; + /** Queue of prompts to display, loaded at command start */ private promptQueue: string[] = []; + /** Index of the currently displayed or next-to-display prompt */ private currentIndex = 0; + /** Flag preventing concurrent command execution */ private inProgress = false; + /** + * Creates a new timed prompts command handler. + * + * @param promptGenerator - Service for generating prompts from the API + */ constructor(private promptGenerator: PromptGeneratorService) {} // MARK: - Public Methods + /** + * Executes the timed prompts sequence. + * + * This method: + * 1. Prevents race conditions by checking inProgress flag + * 2. Stops any existing timed sequence + * 3. Generates all prompts upfront to avoid async issues during intervals + * 4. Shows the first prompt immediately + * 5. Starts an interval to show remaining prompts + * + * The inProgress flag prevents issues if the user triggers the command + * multiple times quickly while prompt generation is in progress. + * + * @param settings - Current plugin settings for generation parameters + */ async execute(settings: FreewritingPromptsSettings): Promise { // Check if already in progress to prevent race conditions if (this.inProgress) { @@ -57,6 +98,13 @@ export class TimedPromptsCommand { } } + /** + * Stops the currently running timed prompts sequence. + * + * Cleans up the interval timer and resets all state. This is important + * for preventing memory leaks and ensuring the next execution starts fresh. + * Safe to call even when no sequence is running. + */ stop(): void { if (this.activeInterval !== null) { clearInterval(this.activeInterval); @@ -67,12 +115,26 @@ export class TimedPromptsCommand { this.inProgress = false; } + /** + * Checks whether a timed prompts sequence is currently running. + * + * @returns true if prompts are being displayed on an interval, false otherwise + */ isRunning(): boolean { return this.activeInterval !== null; } // MARK: - Private Methods + /** + * Starts the interval timer for displaying subsequent prompts. + * + * The timer increments the current index and displays the next prompt + * until the queue is exhausted. Automatically stops and shows a completion + * notice when all prompts have been displayed. + * + * @param delaySeconds - Seconds to wait between each prompt display + */ private startInterval(delaySeconds: number): void { this.activeInterval = window.setInterval(() => { this.currentIndex++; @@ -87,6 +149,19 @@ export class TimedPromptsCommand { }, delaySeconds * 1000); } + /** + * Displays the current prompt as an Obsidian notice. + * + * The notification includes: + * - Current position in sequence (e.g., "3/10") + * - The prompt text + * - Custom CSS class for potential styling + * + * Notification duration is calibrated to avoid overlap with the next prompt, + * disappearing 500ms before the next one arrives for smooth transitions. + * + * @param delaySeconds - Delay setting used to calculate notification duration + */ private showCurrentPrompt(delaySeconds: number): void { if (this.currentIndex < this.promptQueue.length) { const prompt = this.promptQueue[this.currentIndex]; @@ -112,6 +187,14 @@ export class TimedPromptsCommand { // MARK: - Status Methods + /** + * Retrieves the current status of the timed prompts sequence. + * + * Provides information for UI feedback (like status bar displays) about + * the current state of the prompt sequence. + * + * @returns Object containing running state and progress information + */ getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } { const totalPrompts = this.promptQueue.length; const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts); @@ -123,6 +206,13 @@ export class TimedPromptsCommand { }; } + /** + * Gets the prompts that haven't been displayed yet. + * + * Useful for debugging or if users want to preview upcoming prompts. + * + * @returns Array of remaining prompt strings, empty if sequence is complete + */ getRemainingPrompts(): string[] { if (this.currentIndex >= this.promptQueue.length) { return []; diff --git a/main.ts b/main.ts index 16f05d9..3e1775e 100644 --- a/main.ts +++ b/main.ts @@ -9,13 +9,43 @@ import { ModelService } from './services/modelService'; import { TimedPromptsCommand } from './commands/timedPrompts'; import { NotePromptsCommand } from './commands/notePrompts'; +/** + * Main plugin class for Freewriting Prompts. + * + * This plugin helps writers overcome creative blocks by generating AI-powered + * writing prompts using Claude. It provides two main features: + * 1. Timed prompts: Shows prompts as notifications at regular intervals + * 2. Note prompts: Inserts prompts directly into the current note + * + * Architecture: + * - Services: Core business logic (prompt generation, model management) + * - Commands: User-facing actions (timed prompts, note prompts) + * - API Client: Low-level Anthropic API communication + * - Settings: User configuration UI and persistence + * + * The plugin manages the full lifecycle including initialization, cleanup, + * settings persistence (including model cache), and command registration. + */ export default class FreewritingPromptsPlugin extends Plugin { + /** Current plugin settings */ settings: FreewritingPromptsSettings; + /** Service for generating writing prompts */ promptGenerator: PromptGeneratorService; + /** Service for managing available Claude models */ modelService: ModelService; + /** Command handler for timed prompt notifications */ timedCommand: TimedPromptsCommand; + /** Command handler for note prompt insertion */ noteCommand: NotePromptsCommand; + /** + * Called when the plugin loads. + * + * Initializes all services and commands, loads settings and model cache + * from disk, and registers commands with Obsidian. This method ensures + * the model cache is loaded before ModelService tries to use it, avoiding + * an unnecessary API call on startup. + */ async onload() { // Load data once and use it for both settings and model cache const data = await this.loadData() as FreewritingPromptsData | null; @@ -39,6 +69,16 @@ export default class FreewritingPromptsPlugin extends Plugin { this.addSettingTab(new FreewritingPromptsSettingTab(this.app, this)); } + /** + * Called when the plugin unloads. + * + * Performs cleanup to prevent memory leaks and ensure proper state: + * - Stops any running timed prompts (clears intervals) + * - Clears the in-memory prompt cache + * + * Model cache is NOT cleared here because it's persisted to disk and + * should be available on next load. + */ onunload() { // Stop any running timed prompts if (this.timedCommand) { @@ -53,10 +93,23 @@ export default class FreewritingPromptsPlugin extends Plugin { // MARK: - Settings Management + /** + * Loads plugin settings from disk. + * + * Merges saved settings with defaults to ensure any new settings added + * in plugin updates have sensible default values. + */ async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } + /** + * Saves plugin settings to disk. + * + * Includes both user settings and the model cache to avoid re-fetching + * models on every startup. Updates the prompt generator with the new API + * key if it changed. + */ async saveSettings() { // Save settings with model cache const data: FreewritingPromptsData = { @@ -73,6 +126,16 @@ export default class FreewritingPromptsPlugin extends Plugin { // MARK: - Command Registration + /** + * Registers all plugin commands with Obsidian. + * + * Three commands are registered: + * 1. 'timed-prompts': Starts a timed prompt sequence + * 2. 'note-prompts': Inserts prompts into the current note + * 3. 'stop-timed-prompts': Stops the active timed sequence + * + * Commands are available in the command palette and can be bound to hotkeys. + */ private registerCommands() { // Timed prompts command this.addCommand({ @@ -104,6 +167,17 @@ export default class FreewritingPromptsPlugin extends Plugin { // MARK: - Command Implementations + /** + * Executes the timed prompts command. + * + * This method: + * 1. Checks if timed prompts are already running + * 2. Validates settings before making API calls + * 3. Delegates to the TimedPromptsCommand for execution + * + * Shows user-friendly error messages for common issues like missing + * API key or invalid settings. + */ private async executeTimedPrompts(): Promise { // Check if timed prompts are already running if (this.timedCommand.isRunning()) { @@ -126,6 +200,20 @@ export default class FreewritingPromptsPlugin extends Plugin { } } + /** + * Executes the note prompts command. + * + * This method: + * 1. Validates editor and view are available + * 2. Validates settings before making API calls + * 3. Delegates to the NotePromptsCommand for execution + * + * This is an editor command, so Obsidian ensures editor and view exist, + * but we double-check for safety. + * + * @param editor - Active editor instance + * @param view - Active markdown view + */ private async executeNotePrompts(editor: Editor, view: MarkdownView): Promise { // Check if we can execute the command if (!NotePromptsCommand.canExecute(editor, view)) { @@ -148,6 +236,12 @@ export default class FreewritingPromptsPlugin extends Plugin { } } + /** + * Stops the currently running timed prompts sequence. + * + * Checks if prompts are actually running before attempting to stop + * to provide appropriate feedback messages. + */ private stopTimedPrompts(): void { if (this.timedCommand.isRunning()) { this.timedCommand.stop(); @@ -159,6 +253,13 @@ export default class FreewritingPromptsPlugin extends Plugin { // MARK: - Public API for Settings + /** + * Gets the current status of the timed prompts sequence. + * + * This is used by the settings tab or status bar to show current progress. + * + * @returns Object containing running state and progress information + */ getTimedStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } { return this.timedCommand.getStatus(); } diff --git a/services/modelService.ts b/services/modelService.ts index 9fe2743..6ca7c27 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -5,16 +5,41 @@ import { Notice } from 'obsidian'; import { AnthropicClient } from '../api/anthropicClient'; import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types'; +/** + * Simplified model representation for UI display purposes. + * Used to populate dropdown menus with user-friendly model names. + */ export interface ModelOption { + /** Model identifier (e.g., 'claude-3-5-haiku-latest') */ id: string; + /** Human-readable display name for the UI */ displayName: string; } +/** + * Service responsible for managing the list of available Claude models. + * + * Key responsibilities: + * - Fetches current model list from Anthropic API + * - Caches results for 24 hours to minimize API calls + * - Provides fallback to hardcoded model list when API is unavailable + * - Handles graceful degradation when API key is not configured + * + * The 24-hour cache TTL balances freshness with API efficiency - models don't + * change frequently enough to warrant more aggressive polling, but we want + * users to see new models within a reasonable timeframe. + */ export class ModelService { private anthropicClient: AnthropicClient; private modelCache: ModelCache | null = null; + /** Cache time-to-live in milliseconds (24 hours) */ private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours + /** + * Creates a new model service instance. + * + * @param anthropicClient - Client for making API requests to Anthropic + */ constructor(anthropicClient: AnthropicClient) { this.anthropicClient = anthropicClient; } @@ -22,9 +47,17 @@ export class ModelService { // MARK: - Public Methods /** - * Get available models with caching and fallback logic - * Returns models from cache if valid, otherwise fetches from API - * Falls back to hardcoded list if API fails + * Retrieves available Claude models with intelligent caching and fallback. + * + * This method implements a three-tier strategy: + * 1. Return cached models if valid (within 24-hour TTL) + * 2. Fetch fresh models from API if cache is stale or empty + * 3. Fall back to hardcoded ANTHROPIC_MODELS if API fails + * + * If no API key is configured, quietly returns fallback without showing errors, + * since this is expected during initial plugin setup. + * + * @returns Array of model options formatted for UI display */ async getAvailableModels(): Promise { // Check if we have a valid cache @@ -50,8 +83,13 @@ export class ModelService { } /** - * Force refresh the model list from API - * Used when user changes API key + * Forces a refresh of the model list from the API, bypassing cache. + * + * This is called when the user enters a new API key in settings, ensuring + * they immediately see the correct models available for their account. + * Falls back to hardcoded models if the API request fails. + * + * @returns Array of current available models */ async refreshModels(): Promise { // If no API key, quietly return fallback @@ -71,21 +109,33 @@ export class ModelService { } /** - * Load cache from plugin data + * Loads cached model data from plugin persistent storage. + * + * Called during plugin initialization to restore the previous session's + * model list, avoiding an immediate API call on every startup. + * + * @param cache - Previously saved cache data, or null if none exists */ loadCache(cache: ModelCache | null): void { this.modelCache = cache; } /** - * Get current cache for saving to plugin data + * Retrieves current cache for persistence to disk. + * + * Called during plugin save operations to preserve the model cache + * across Obsidian restarts, maintaining the 24-hour TTL. + * + * @returns Current cache state, or null if no cache exists */ getCache(): ModelCache | null { return this.modelCache; } /** - * Clear the cache (for testing or manual refresh) + * Clears the cached model list, forcing a fresh fetch on next access. + * + * Useful for testing or troubleshooting cache-related issues. */ clearCache(): void { this.modelCache = null; @@ -94,7 +144,13 @@ export class ModelService { // MARK: - Private Methods /** - * Check if the current cache is still valid (within TTL) + * Checks whether the current cache is still valid based on TTL. + * + * Cache is considered valid if it exists and was fetched less than + * 24 hours ago. This prevents excessive API calls while ensuring + * reasonable freshness of model data. + * + * @returns true if cache exists and is within TTL, false otherwise */ private isCacheValid(): boolean { if (!this.modelCache) { @@ -107,7 +163,11 @@ export class ModelService { } /** - * Update cache with new model data + * Updates the cache with freshly fetched model data. + * + * Sets the fetchedAt timestamp to now, starting the 24-hour TTL countdown. + * + * @param models - Array of model information from the API */ private updateCache(models: ModelInfo[]): void { this.modelCache = { @@ -117,8 +177,14 @@ export class ModelService { } /** - * Format ModelInfo array to ModelOption array for dropdown - * Uses display_name if available, otherwise falls back to id + * Transforms API model data into UI-friendly format. + * + * Prefers display_name when available for better UX, falls back to + * model ID if display_name is missing. Results are sorted alphabetically + * for easier scanning in the dropdown. + * + * @param models - Raw model info from API + * @returns Formatted options ready for dropdown display */ private formatModels(models: ModelInfo[]): ModelOption[] { return models.map(model => ({ @@ -128,7 +194,13 @@ export class ModelService { } /** - * Get fallback models from hardcoded list + * Provides fallback model list when API is unavailable. + * + * Uses the hardcoded ANTHROPIC_MODELS constant which should be periodically + * updated to include newly released models. This ensures the plugin remains + * functional even during API outages or when no API key is configured. + * + * @returns Array of fallback model options */ private getFallbackModels(): ModelOption[] { return ANTHROPIC_MODELS.map(id => ({ diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index 58fa933..36a0769 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -5,22 +5,58 @@ import { Notice } from 'obsidian'; import { AnthropicClient } from '../api/anthropicClient'; import { FreewritingPromptsSettings, GeneratedPrompt } from '../types'; +/** + * Service that coordinates prompt generation between commands and the API client. + * + * This service layer provides: + * - High-level methods for different prompt types (timed vs note) + * - In-memory caching with 10-minute TTL to avoid redundant API calls + * - Settings validation before attempting generation + * - User feedback via Obsidian notices + * - Error handling and propagation + * + * The 10-minute cache is relatively short because: + * 1. Users expect fresh prompts when they explicitly request them + * 2. The cache prevents rapid-fire duplicate requests during a single session + * 3. Memory usage is minimal (cache is just strings with timestamps) + */ export class PromptGeneratorService { private client: AnthropicClient; + /** In-memory cache mapping request parameters to generated prompts */ private cache: Map = new Map(); + /** Cache expiry time in milliseconds (10 minutes) */ private readonly cacheExpiryMs = 10 * 60 * 1000; // 10 minutes - // Expose client for API testing in settings + /** + * Exposes the underlying API client for direct access. + * Used by settings tab to test API key connectivity. + */ get anthropicClient(): AnthropicClient { return this.client; } + /** + * Creates a new prompt generator service. + * + * @param settings - Plugin settings containing API key and configuration + */ constructor(settings: FreewritingPromptsSettings) { this.client = new AnthropicClient(settings.apiKey); } // MARK: - Public Methods + /** + * Generates prompts optimized for timed notifications. + * + * These prompts are short and answerable quickly since they appear as + * timed notifications during freewriting sessions. Uses the timedExamplePrompt + * to guide style and applies special system instructions for brevity. + * + * @param settings - Current plugin settings + * @returns Array of short, focused prompts for rapid response + * @throws Error if API key is invalid or generation fails + */ async generateTimedPrompts(settings: FreewritingPromptsSettings): Promise { return this.generatePrompts( settings.timedCount, @@ -31,6 +67,17 @@ export class PromptGeneratorService { ); } + /** + * Generates prompts for insertion into notes. + * + * These prompts can be more elaborate and creative since they're inserted + * as text into a note rather than appearing as brief notifications. Uses + * the freewritingExamplePrompt to guide style. + * + * @param settings - Current plugin settings + * @returns Array of creative prompts suitable for note insertion + * @throws Error if API key is invalid or generation fails + */ async generateNotePrompts(settings: FreewritingPromptsSettings): Promise { return this.generatePrompts( settings.noteCount, @@ -41,17 +88,52 @@ export class PromptGeneratorService { ); } + /** + * Updates the API key for the underlying client. + * + * Called when the user changes their API key in settings. Clears the cache + * since previous cached prompts may have been generated with a different key. + * + * @param apiKey - New Anthropic API key + */ updateApiKey(apiKey: string): void { this.client.updateApiKey(apiKey); this.clearCache(); // Clear cache when API key changes } + /** + * Clears all cached prompts. + * + * Forces fresh generation on next request. Useful when users want to + * ensure they're getting completely new prompts rather than cached ones. + */ clearCache(): void { this.cache.clear(); } // MARK: - Private Methods + /** + * Core prompt generation method with caching logic. + * + * Implements the full generation flow: + * 1. Validates API key configuration + * 2. Checks cache for matching prompts within TTL + * 3. Calls API if cache miss or expired + * 4. Stores results in cache with timestamp + * 5. Shows user feedback via notices + * + * The cache key is derived from all generation parameters to ensure + * cached prompts match the current settings exactly. + * + * @param count - Number of prompts to generate + * @param model - Claude model ID to use + * @param systemPrompt - Base system instructions + * @param examplePrompt - Example to guide style + * @param type - Prompt type ('timed' or 'note') affecting format and length + * @returns Array of generated prompt strings + * @throws Error if API key is missing or API call fails + */ private async generatePrompts( count: number, model: string, @@ -95,6 +177,20 @@ export class PromptGeneratorService { } } + /** + * Creates a unique cache key from generation parameters. + * + * The key is a JSON string containing all parameters that affect output. + * This ensures we only serve cached prompts when ALL settings match, + * preventing incorrect reuse when the user changes any configuration. + * + * @param count - Number of prompts + * @param model - Model ID + * @param systemPrompt - System instructions + * @param examplePrompt - Example prompt + * @param type - Prompt type + * @returns JSON string uniquely identifying this parameter combination + */ private createCacheKey( count: number, model: string, @@ -112,6 +208,19 @@ export class PromptGeneratorService { return JSON.stringify(keyData); } + /** + * Retrieves cached prompts if they exist and are still valid. + * + * Checks both existence and age of cached prompts. Returns null if: + * - No cache entry exists for this key + * - Cache entry is empty (defensive guard) + * - Cache is older than 10 minutes (expired) + * + * Expired entries are automatically removed from the cache map. + * + * @param cacheKey - Cache key to look up + * @returns Array of cached prompts if valid, null otherwise + */ private getCachedPrompts(cacheKey: string): GeneratedPrompt[] | null { const cached = this.cache.get(cacheKey); if (!cached) { @@ -137,6 +246,21 @@ export class PromptGeneratorService { // MARK: - Validation Methods + /** + * Validates plugin settings before attempting prompt generation. + * + * Checks all settings that affect prompt generation to provide early + * feedback before making API calls. Validates: + * - API key is present + * - Model ID is specified + * - Numeric settings are within acceptable ranges + * + * This validation prevents API errors and gives users clear guidance + * about what needs to be fixed in their configuration. + * + * @param settings - Settings to validate + * @returns Object containing validity status and array of error messages + */ validateSettings(settings: FreewritingPromptsSettings): { isValid: boolean; errors: string[] } { const errors: string[] = []; diff --git a/settings.ts b/settings.ts index ccbb609..6bdf3b6 100644 --- a/settings.ts +++ b/settings.ts @@ -6,27 +6,75 @@ import FreewritingPromptsPlugin from './main'; import { FreewritingPromptsSettings } from './types'; import { ModelOption } from './services/modelService'; +/** + * Default plugin settings applied on first installation. + * + * These defaults are chosen to: + * - Use the most cost-effective model (Haiku) for testing + * - Provide reasonable timing for timed prompts (6 seconds) + * - Include example prompts that demonstrate expected styles + * - Maintain reasonable limits on prompt counts + */ export const DEFAULT_SETTINGS: FreewritingPromptsSettings = { + /** Empty by default - user must provide their own API key */ apiKey: '', + /** Haiku is the fastest and most cost-effective model for prompt generation */ model: 'claude-3-5-haiku-latest' as const, + /** 10 prompts provides a good freewriting session length */ timedCount: 10, + /** 6 seconds allows time to read and respond without feeling rushed */ delaySeconds: 6, + /** 3 prompts is enough for a note without being overwhelming */ noteCount: 3, + /** Base system prompt guiding the AI's creative writing style */ systemPrompt: 'You are a creative writing assistant. Generate engaging, thought-provoking writing prompts that inspire creativity and help writers overcome blocks. Focus on variety, originality, and emotional depth.', + /** Example demonstrating short, immediate style for timed prompts */ timedExamplePrompt: 'The interesting thing about a rose is…', + /** Example demonstrating more elaborate style for note prompts */ freewritingExamplePrompt: 'Describe a world where colors have been outlawed and only exist in secret underground galleries.' }; +/** + * Settings UI tab for the Freewriting Prompts plugin. + * + * This class builds the settings interface with several key sections: + * - API Configuration: API key, model selection, connection testing + * - Command Configuration: Counts and timing for different prompt types + * - Prompt Customization: System prompt and examples to guide style + * - Actions: Cache clearing and other utility functions + * + * Key UX considerations: + * - Model dropdown loads asynchronously to avoid blocking UI + * - API key is masked as a password field + * - Model refresh happens automatically when API key is entered + * - Fallback to hardcoded models if API is unavailable + * - Detailed test results help troubleshoot connection issues + */ export class FreewritingPromptsSettingTab extends PluginSettingTab { plugin: FreewritingPromptsPlugin; + /** Reference to model dropdown for dynamic updates */ private modelDropdown: DropdownComponent | null = null; + /** Cached list of available models for the dropdown */ private availableModels: ModelOption[] = []; + /** + * Creates a new settings tab instance. + * + * @param app - Obsidian app instance + * @param plugin - Plugin instance for accessing services and settings + */ constructor(app: App, plugin: FreewritingPromptsPlugin) { super(app, plugin); this.plugin = plugin; } + /** + * Renders the settings UI. + * + * This method builds all settings sections and initiates async loading + * of model data without blocking the UI. The model dropdown starts with + * a "Loading models..." placeholder and updates when data arrives. + */ async display(): Promise { const { containerEl } = this; containerEl.empty(); @@ -195,6 +243,13 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { // MARK: - Model Loading + /** + * Loads available models from the API. + * + * This is the core model-fetching method that calls the ModelService. + * Errors are logged but not shown to the user here - they're shown by + * the ModelService itself via Notice popups. + */ private async loadModels(): Promise { try { this.availableModels = await this.plugin.modelService.getAvailableModels(); @@ -206,8 +261,14 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { } /** - * Load models asynchronously without blocking UI rendering - * Updates dropdown when models are fetched + * Loads models asynchronously without blocking UI rendering. + * + * This method is called after the UI is displayed to avoid blocking + * the settings tab from appearing. The dropdown starts in a "Loading..." + * state and updates when models arrive. + * + * If the current model is no longer available (e.g., deprecated), falls + * back to the first available model and updates settings. */ private async loadModelsAsync(): Promise { await this.loadModels(); @@ -233,6 +294,15 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { } } + /** + * Populates the model dropdown with available models. + * + * If no models are available yet, shows a "Loading models..." placeholder + * and disables the dropdown. Once models load, this is called again to + * populate the real options. + * + * @param dropdown - Dropdown component to populate + */ private populateModelDropdown(dropdown: DropdownComponent): void { if (this.availableModels.length === 0) { // No models available yet, disable dropdown @@ -252,6 +322,16 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { dropdown.setDisabled(false); } + /** + * Forces a refresh of the model list from the API. + * + * This is called when the user enters a new API key to ensure they see + * models available for their specific account. Shows a "Refreshing..." + * state during the fetch. + * + * If the current model is no longer available after refresh, falls back + * to the first available model and notifies the user. + */ private async refreshModels(): Promise { try { // Disable dropdown during refresh @@ -294,6 +374,20 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { // MARK: - API Testing + /** + * Tests the configured API key by making a minimal request to Claude. + * + * This provides immediate feedback about whether: + * - The API key is valid + * - The network connection works + * - The selected model is accessible + * - Performance is reasonable (response time) + * + * Shows detailed success or failure information via Notice, including + * troubleshooting guidance for common error scenarios. + * + * @param button - Button component to update with loading state + */ private async testApiKey(button: ButtonComponent): Promise { const originalText = button.buttonEl.textContent || 'Test Connection'; diff --git a/types.ts b/types.ts index a535450..5b4315b 100644 --- a/types.ts +++ b/types.ts @@ -1,77 +1,160 @@ // ABOUTME: Type definitions for the Freewriting Prompts plugin // ABOUTME: Defines interfaces for settings, API responses, and plugin configuration -// Type alias to document intent that this should be a Claude model ID +/** + * Type alias representing a Claude model identifier. + * Used to document the intent that a string should be a valid Claude model ID. + */ export type ModelId = string; +/** + * Plugin configuration settings that control prompt generation behavior. + * These settings are persisted to disk and can be modified through the settings UI. + */ export interface FreewritingPromptsSettings { + /** Anthropic API key for authenticating with Claude API */ apiKey: string; + /** Claude model ID to use for prompt generation (e.g., 'claude-3-5-haiku-latest') */ model: ModelId; // Changed from AnthropicModel to string to support dynamic models + /** Number of prompts to generate for timed notifications (1-50) */ timedCount: number; + /** Delay in seconds between each timed prompt notification (1-300) */ delaySeconds: number; + /** Number of prompts to append to a note (1-20) */ noteCount: number; + /** System-level instructions that guide the AI's prompt generation behavior */ systemPrompt: string; + /** Example prompt that demonstrates the desired style for timed prompts */ timedExamplePrompt: string; + /** Example prompt that demonstrates the desired style for note-inserted prompts */ freewritingExamplePrompt: string; } +/** + * Extended settings data that includes both user configuration and cached model information. + * This is the structure saved to and loaded from disk to persist state across sessions. + */ export interface FreewritingPromptsData extends FreewritingPromptsSettings { + /** Optional cached model list with 24-hour TTL to reduce API calls */ modelCache?: ModelCache; } +/** + * Represents a single message in the conversation with Claude. + * Used to construct the messages array sent to the Anthropic API. + */ export interface AnthropicMessage { + /** Role identifier indicating who sent the message */ role: 'user' | 'assistant' | 'system'; + /** The actual content/text of the message */ content: string; } +/** + * Request payload structure for the Anthropic Messages API. + * Defines all parameters needed to generate a completion from Claude. + */ export interface AnthropicRequest { + /** Model identifier (e.g., 'claude-3-5-haiku-latest') */ model: string; + /** Maximum number of tokens to generate in the response */ max_tokens: number; + /** Array of conversation messages between user and assistant */ messages: AnthropicMessage[]; + /** Optional system prompt that provides context and instructions */ system?: string; } +/** + * Response structure returned by the Anthropic Messages API. + * Contains the generated text, metadata, and token usage information. + */ export interface AnthropicResponse { + /** Array of content blocks containing the generated text */ content: Array<{ + /** The actual generated text */ text: string; + /** Content type identifier */ type: 'text'; }>; + /** Unique identifier for this API response */ id: string; + /** Model that generated the response */ model: string; + /** Role of the responder (always 'assistant' for API responses) */ role: 'assistant'; + /** Reason the generation stopped (e.g., 'end_turn', 'max_tokens') */ stop_reason: string; + /** Custom stop sequence that triggered completion, if any */ stop_sequence: null; + /** Response type identifier */ type: 'message'; + /** Token usage statistics for billing and monitoring */ usage: { + /** Number of tokens in the input prompt */ input_tokens: number; + /** Number of tokens generated in the response */ output_tokens: number; }; } +/** + * Represents a generated writing prompt with its creation timestamp. + * Used for caching prompts to avoid unnecessary API calls within the cache TTL. + */ export interface GeneratedPrompt { + /** The actual prompt text generated by Claude */ text: string; + /** When this prompt was generated (used for cache expiry) */ timestamp: Date; } +/** + * Information about a single Claude model returned from the Models API. + * Used to populate the model selection dropdown with current available models. + */ export interface ModelInfo { + /** Unique model identifier (e.g., 'claude-3-5-haiku-latest') */ id: string; + /** Human-readable model name for display purposes */ display_name?: string; + /** ISO timestamp of when the model was created */ created_at: string; + /** Model type classification */ type: string; } +/** + * Response structure from the Anthropic Models List API. + * Provides paginated list of available Claude models. + */ export interface ModelsListResponse { + /** Array of available model information */ data: ModelInfo[]; + /** ID of the first model in the list (for pagination) */ first_id: string; + /** Whether more models are available on subsequent pages */ has_more: boolean; + /** ID of the last model in the list (for pagination) */ last_id: string; } +/** + * Cached model list with timestamp for TTL-based expiry. + * Models are cached for 24 hours to reduce API calls while staying reasonably current. + */ export interface ModelCache { + /** Array of cached model information */ models: ModelInfo[]; + /** Unix timestamp (milliseconds) when this cache was created */ fetchedAt: number; } +/** + * Hardcoded fallback list of known Claude models. + * Used when the Models API is unavailable or the API key is not configured. + * This list should be updated periodically as new models are released. + */ export const ANTHROPIC_MODELS = [ 'claude-opus-4-1-20250805', 'claude-opus-4-20250514', @@ -81,4 +164,8 @@ export const ANTHROPIC_MODELS = [ 'claude-3-haiku-20240307' ] as const; +/** + * Type representing one of the hardcoded fallback model identifiers. + * This is a union type of all strings in the ANTHROPIC_MODELS array. + */ export type AnthropicModel = typeof ANTHROPIC_MODELS[number]; \ No newline at end of file -- 2.36.6 From def8bbcfe5dd6eae45cb422916b37898f35f923c Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:11:06 +0200 Subject: [PATCH 25/60] Improves Anthropic models API response validation Enhances type checking and validation for API response structure Adds more robust type validation to ensure: - Correct response object structure - Presence of required model fields - Type safety for model data retrieval Prevents potential runtime errors by implementing stricter type checks --- api/anthropicClient.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 68d8d83..bcabcca 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -136,11 +136,19 @@ export class AnthropicClient { } // Validate basic response structure - const data = response.json as any; - if (!data || !Array.isArray(data.data)) { + const data = response.json as unknown; + if (!data || typeof data !== 'object' || !('data' in data) || !Array.isArray((data as { data: unknown }).data)) { throw new Error('Invalid models API response structure'); } + // Validate that each model has required fields + const modelsData = (data as { data: unknown[] }).data; + if (!modelsData.every((model: unknown) => + model && typeof model === 'object' && 'id' in model && typeof (model as { id: unknown }).id === 'string' + )) { + throw new Error('Invalid model structure in API response'); + } + return data as ModelsListResponse; } catch (error) { if (error instanceof Error) { -- 2.36.6 From f9fefceac1e0467a9b80f72d4360a82d9727e5cf Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:12:32 +0200 Subject: [PATCH 26/60] Adds pagination support for Anthropic models API Enhances models fetching to handle paginated API responses Implements robust pagination mechanism to retrieve all available models - Continues fetching pages while 'has_more' is true - Accumulates models across multiple API calls - Preserves first and last page identifiers - Ensures complete model list retrieval Improves error handling and response validation --- api/anthropicClient.ts | 96 ++++++++++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 28 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index bcabcca..12540ff 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -2,7 +2,7 @@ // ABOUTME: Handles API requests, error handling, and response parsing import { requestUrl } from 'obsidian'; -import { AnthropicRequest, AnthropicResponse, ModelsListResponse } from '../types'; +import { AnthropicRequest, AnthropicResponse, ModelInfo, ModelsListResponse } from '../types'; /** * Client for interacting with the Anthropic API to generate writing prompts. @@ -109,11 +109,13 @@ export class AnthropicClient { /** * Fetches the list of available Claude models from the Anthropic API. * - * This is used to populate the model selection dropdown in settings with - * current available models rather than relying solely on hardcoded lists. + * This method implements pagination to ensure all available models are retrieved. + * It continues fetching pages while has_more is true, using the after parameter + * with the last_id from each response to request subsequent pages. + * * The response is cached by ModelService with a 24-hour TTL. * - * @returns Response containing array of available models with metadata + * @returns Response containing array of all available models with final pagination metadata * @throws Error if API key is missing, request fails, or response is malformed */ async fetchModels(): Promise { @@ -122,34 +124,72 @@ export class AnthropicClient { } try { - const response = await requestUrl({ - url: this.modelsUrl, - method: 'GET', - headers: { - 'x-api-key': this.apiKey, - 'anthropic-version': '2023-06-01' + // Accumulate all models across pages + const allModels: ModelInfo[] = []; + let hasMore = true; + let afterId: string | undefined = undefined; + let firstId = ''; + let lastId = ''; + + // Fetch all pages + while (hasMore) { + // Build URL with pagination parameter if needed + const url = afterId ? `${this.modelsUrl}?after=${afterId}` : this.modelsUrl; + + const response = await requestUrl({ + url, + method: 'GET', + headers: { + 'x-api-key': this.apiKey, + 'anthropic-version': '2023-06-01' + } + }); + + if (response.status < 200 || response.status >= 300) { + throw new Error(`Models API request failed: ${response.status}\n${response.text}`); } - }); - if (response.status < 200 || response.status >= 300) { - throw new Error(`Models API request failed: ${response.status}\n${response.text}`); + // Validate basic response structure + const data = response.json as unknown; + if (!data || typeof data !== 'object' || !('data' in data) || !Array.isArray((data as { data: unknown }).data)) { + throw new Error('Invalid models API response structure'); + } + + // Validate that each model has required fields + const modelsData = (data as { data: unknown[] }).data; + if (!modelsData.every((model: unknown) => + model && typeof model === 'object' && 'id' in model && typeof (model as { id: unknown }).id === 'string' + )) { + throw new Error('Invalid model structure in API response'); + } + + const pageResponse = data as ModelsListResponse; + + // Accumulate models from this page + allModels.push(...pageResponse.data); + + // Store first_id from the first page + if (!firstId) { + firstId = pageResponse.first_id; + } + + // Update pagination state + lastId = pageResponse.last_id; + hasMore = pageResponse.has_more; + + // Set up for next iteration + if (hasMore) { + afterId = lastId; + } } - // Validate basic response structure - const data = response.json as unknown; - if (!data || typeof data !== 'object' || !('data' in data) || !Array.isArray((data as { data: unknown }).data)) { - throw new Error('Invalid models API response structure'); - } - - // Validate that each model has required fields - const modelsData = (data as { data: unknown[] }).data; - if (!modelsData.every((model: unknown) => - model && typeof model === 'object' && 'id' in model && typeof (model as { id: unknown }).id === 'string' - )) { - throw new Error('Invalid model structure in API response'); - } - - return data as ModelsListResponse; + // Return combined response with all models + return { + data: allModels, + first_id: firstId, + has_more: false, // We've fetched all pages + last_id: lastId + }; } catch (error) { if (error instanceof Error) { throw error; -- 2.36.6 From ee7faef92bd7543876a57be06b39ba7e49562033 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:13:49 +0200 Subject: [PATCH 27/60] Adds debounce mechanism for API key refresh Implements debounce timer to prevent excessive API calls when updating API key Prevents rapid repeated model refreshes by: - Adding a 500ms delay timer - Clearing previous timers to avoid multiple concurrent requests - Cleaning up timers when settings tab is hidden Improves performance and reduces unnecessary API load during key entry --- settings.ts | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/settings.ts b/settings.ts index 6bdf3b6..b7db14e 100644 --- a/settings.ts +++ b/settings.ts @@ -56,6 +56,10 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { private modelDropdown: DropdownComponent | null = null; /** Cached list of available models for the dropdown */ private availableModels: ModelOption[] = []; + /** Debounce timer for API key changes to avoid excessive API calls */ + private apiKeyDebounceTimer: number | null = null; + /** Debounce delay in milliseconds */ + private readonly API_KEY_DEBOUNCE_MS = 500; /** * Creates a new settings tab instance. @@ -68,6 +72,17 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin = plugin; } + /** + * Cleanup method to clear any pending timers. + * Called when settings tab is closed or destroyed. + */ + hide(): void { + if (this.apiKeyDebounceTimer !== null) { + window.clearTimeout(this.apiKeyDebounceTimer); + this.apiKeyDebounceTimer = null; + } + } + /** * Renders the settings UI. * @@ -96,9 +111,18 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { await this.plugin.saveSettings(); this.plugin.promptGenerator.updateApiKey(value); - // Trigger model refresh when API key is entered + // Clear any existing debounce timer + if (this.apiKeyDebounceTimer !== null) { + window.clearTimeout(this.apiKeyDebounceTimer); + this.apiKeyDebounceTimer = null; + } + + // Debounce model refresh to avoid excessive API calls on every keystroke if (value.trim().length > 0) { - await this.refreshModels(); + this.apiKeyDebounceTimer = window.setTimeout(async () => { + await this.refreshModels(); + this.apiKeyDebounceTimer = null; + }, this.API_KEY_DEBOUNCE_MS); } })) .then(setting => { -- 2.36.6 From da6056bf0d31609e9d734e74da9990c3a21e6daf Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:27:14 +0200 Subject: [PATCH 28/60] Improves prompt insertion logic and timestamp formatting Refines text insertion handling for writing prompts: - Collapses text selection before insertion - Adds more intelligent newline management - Uses Intl.DateTimeFormat for consistent timestamp generation Enhances edge case handling for cursor and text positioning --- commands/notePrompts.ts | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index 40e2e63..cc3e842 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -81,8 +81,9 @@ export class NotePromptsCommand { * Inserts formatted prompts into the note at the cursor position. * * This method handles several edge cases: - * - Adds newline before if cursor is on a line with content - * - Adds newline after if cursor is not at end of document + * - Collapses any text selection before insertion + * - Adds newline before if there's text before the cursor + * - Adds newline after if there's text after the cursor or more lines below * - Positions cursor at the end of inserted content * * The intelligent newline handling ensures prompts don't run into existing @@ -92,29 +93,28 @@ export class NotePromptsCommand { * @param prompts - Array of prompt strings to insert */ private insertPromptsIntoNote(editor: Editor, prompts: string[]): void { - const cursor = editor.getCursor(); - const currentLine = editor.getLine(cursor.line); + // Normalize to an insertion point (collapse any selection) + const from = editor.getCursor('from'); + const to = editor.getCursor('to'); + const hasSelection = from.line !== to.line || from.ch !== to.ch; + if (hasSelection) { + editor.setSelection(from, from); + } + const cursor = editor.getCursor(); // refreshed after collapse + const currentLine = editor.getLine(cursor.line) ?? ''; - // Determine if we need to add a newline before our content - const needsNewlineBefore = currentLine.trim().length > 0; + const hasTextBefore = cursor.ch > 0 && currentLine.slice(0, cursor.ch).trim().length > 0; + const hasTextAfter = cursor.ch < currentLine.length && currentLine.slice(cursor.ch).trim().length > 0; // Format the prompts const formattedPrompts = this.formatPrompts(prompts); // Prepare the content to insert - let contentToInsert = ''; - - if (needsNewlineBefore) { - contentToInsert += '\n'; - } - - contentToInsert += formattedPrompts; - - // If we're not at the end of the document, add a trailing newline const lastLine = editor.lastLine(); - if (cursor.line < lastLine) { - contentToInsert += '\n'; - } + let contentToInsert = ''; + if (hasTextBefore) contentToInsert += '\n'; + contentToInsert += formattedPrompts; + if (hasTextAfter || cursor.line < lastLine) contentToInsert += '\n'; // Insert the content at the cursor position editor.replaceSelection(contentToInsert); @@ -146,13 +146,13 @@ export class NotePromptsCommand { * @returns Formatted markdown string ready for insertion */ private formatPrompts(prompts: string[]): string { - const timestamp = new Date().toLocaleDateString('en-US', { + const timestamp = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' - }); + }).format(new Date()); let formatted = `## Writing Prompts (${timestamp})\n\n`; -- 2.36.6 From 456a2226ea496b47927f2c98e3ce1940b9af40b4 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:29:15 +0200 Subject: [PATCH 29/60] Updates ESLint configuration to latest standards Migrates ESLint configuration to new flat config format Upgrades TypeScript and ESLint dependencies to latest versions Removes legacy .eslintignore and .eslintrc files Consolidates linting configuration into a single eslint.config.mjs file Improves project code quality and linting consistency --- .eslintignore | 3 - .eslintrc | 23 - eslint.config.mjs | 47 ++ package-lock.json | 1253 +++++++++++++++++++++------------------------ package.json | 17 +- 5 files changed, 649 insertions(+), 694 deletions(-) delete mode 100644 .eslintignore delete mode 100644 .eslintrc create mode 100644 eslint.config.mjs diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index e019f3c..0000000 --- a/.eslintignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ - -main.js diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 0807290..0000000 --- a/.eslintrc +++ /dev/null @@ -1,23 +0,0 @@ -{ - "root": true, - "parser": "@typescript-eslint/parser", - "env": { "node": true }, - "plugins": [ - "@typescript-eslint" - ], - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended" - ], - "parserOptions": { - "sourceType": "module" - }, - "rules": { - "no-unused-vars": "off", - "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }], - "@typescript-eslint/ban-ts-comment": "off", - "no-prototype-builtins": "off", - "@typescript-eslint/no-empty-function": "off" - } - } \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..bdd509c --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,47 @@ +import eslint from '@eslint/js'; +import tseslint from 'typescript-eslint'; + +export default tseslint.config( + // Ignore patterns (replaces .eslintignore) + { + ignores: [ + 'node_modules/**', + 'main.js', + '*.config.js', + '*.config.mjs' + ] + }, + // Base ESLint recommended rules + eslint.configs.recommended, + // TypeScript ESLint recommended rules + ...tseslint.configs.recommended, + // Project-specific configuration + { + files: ['**/*.ts'], + languageOptions: { + parser: tseslint.parser, + parserOptions: { + sourceType: 'module', + ecmaVersion: 2020 + }, + globals: { + // Node.js globals + console: 'readonly', + process: 'readonly', + __dirname: 'readonly', + __filename: 'readonly', + Buffer: 'readonly', + setImmediate: 'readonly', + clearImmediate: 'readonly' + } + }, + rules: { + // Disable base rule in favor of TypeScript version + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }], + '@typescript-eslint/ban-ts-comment': 'off', + 'no-prototype-builtins': 'off', + '@typescript-eslint/no-empty-function': 'off' + } + } +); diff --git a/package-lock.json b/package-lock.json index 234984d..49ea9f8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,22 +1,23 @@ { "name": "obsidian-freewriting-prompts", - "version": "1.0.0", + "version": "1.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "obsidian-freewriting-prompts", - "version": "1.0.0", - "license": "MIT", + "version": "1.1.1", + "license": "GPL-3.0-only", "devDependencies": { + "@eslint/js": "^9.17.0", "@types/node": "^16.11.6", - "@typescript-eslint/eslint-plugin": "5.29.0", - "@typescript-eslint/parser": "5.29.0", "builtin-modules": "3.3.0", "esbuild": "0.17.3", + "eslint": "^9.17.0", "obsidian": "latest", "tslib": "2.4.0", - "typescript": "4.7.4" + "typescript": "5.7.3", + "typescript-eslint": "^8.18.2" } }, "node_modules/@codemirror/state": { @@ -424,7 +425,6 @@ "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "eslint-visitor-keys": "^3.4.3" }, @@ -444,23 +444,62 @@ "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, + "node_modules/@eslint/config-array": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz", + "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.1.tgz", + "integrity": "sha512-csZAzkNhsgwb0I/UAV6/RGFTbiakPCf0ZrGmrIxQpYvGZ00PhTkSnyKNolphgIvmnJeGw6rcGVEXfTzUnFuEvw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.16.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.16.0.tgz", + "integrity": "sha512-nmC8/totwobIiFcGkDza3GIKfAw1+hLiYVrh3I1nIomQ8PEr5cxg34jnkmGawul/ep52wGRAcyeDCNtWKSOj4Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.1.tgz", + "integrity": "sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", + "espree": "^10.0.1", + "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", @@ -468,38 +507,71 @@ "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, "node_modules/@eslint/js": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", - "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", + "version": "9.38.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.38.0.tgz", + "integrity": "sha512-UZ1VpFvXf9J06YG9xQBdnzU+kthors6KjhMAl6f4gH4usHyh31rUf2DLGInT8RFYIReYXNSydgPY0V2LuWgl7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" } }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", - "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", - "deprecated": "Use @eslint/config-array instead", + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.0.tgz", + "integrity": "sha512-sB5uyeq+dwCWyPi31B2gQlVlo+j5brPlWx4yZBrEaRo/nhdDE8Xke1gsGgtiBdaBTxuTkceLVuVt/pclrasb0A==", "dev": true, "license": "Apache-2.0", - "peer": true, "dependencies": { - "@humanwhocodes/object-schema": "^2.0.3", - "debug": "^4.3.1", - "minimatch": "^3.0.5" + "@eslint/core": "^0.16.0", + "levn": "^0.4.1" }, "engines": { - "node": ">=10.10.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" } }, "node_modules/@humanwhocodes/module-importer": { @@ -508,7 +580,6 @@ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", "dev": true, "license": "Apache-2.0", - "peer": true, "engines": { "node": ">=12.22" }, @@ -517,14 +588,19 @@ "url": "https://github.com/sponsors/nzakas" } }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", "dev": true, - "license": "BSD-3-Clause", - "peer": true + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } }, "node_modules/@marijn/find-cluster-break": { "version": "1.0.2", @@ -613,205 +689,200 @@ "@types/estree": "*" } }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.29.0.tgz", - "integrity": "sha512-kgTsISt9pM53yRFQmLZ4npj99yGl3x3Pl7z4eA66OuTzAGC4bQB5H5fuLwPnqTKU3yyrrg4MIhjF17UYnL4c0w==", + "node_modules/@typescript-eslint/project-service": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.46.2.tgz", + "integrity": "sha512-PULOLZ9iqwI7hXcmL4fVfIsBi6AN9YxRc0frbvmg8f+4hQAjQ5GYNKK0DIArNo+rOKmR/iBYwkpBmnIwin4wBg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "5.29.0", - "@typescript-eslint/type-utils": "5.29.0", - "@typescript-eslint/utils": "5.29.0", - "debug": "^4.3.4", - "functional-red-black-tree": "^1.0.1", - "ignore": "^5.2.0", - "regexpp": "^3.2.0", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^5.0.0", - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.29.0.tgz", - "integrity": "sha512-ruKWTv+x0OOxbzIw9nW5oWlUopvP/IQDjB5ZqmTglLIoDTctLlAJpAQFpNPJP/ZI7hTT9sARBosEfaKbcFuECw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/scope-manager": "5.29.0", - "@typescript-eslint/types": "5.29.0", - "@typescript-eslint/typescript-estree": "5.29.0", + "@typescript-eslint/tsconfig-utils": "^8.46.2", + "@typescript-eslint/types": "^8.46.2", "debug": "^4.3.4" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "typescript": ">=4.8.4 <6.0.0" } }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.29.0.tgz", - "integrity": "sha512-etbXUT0FygFi2ihcxDZjz21LtC+Eps9V2xVx09zFoN44RRHPrkMflidGMI+2dUs821zR1tDS6Oc9IXxIjOUZwA==", + "node_modules/@typescript-eslint/project-service/node_modules/@typescript-eslint/types": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.46.2.tgz", + "integrity": "sha512-lNCWCbq7rpg7qDsQrd3D6NyWYu+gkTENkG5IKYhUIcxSb59SQC/hEQ+MrG4sTgBVghTonNWq42bA/d4yYumldQ==", "dev": true, "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "5.29.0", - "@typescript-eslint/visitor-keys": "5.29.0" - }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript-eslint/type-utils": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.29.0.tgz", - "integrity": "sha512-JK6bAaaiJozbox3K220VRfCzLa9n0ib/J+FHIwnaV3Enw/TO267qe0pM1b1QrrEuy6xun374XEAsRlA86JJnyg==", + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.46.2.tgz", + "integrity": "sha512-a7QH6fw4S57+F5y2FIxxSDyi5M4UfGF+Jl1bCGd7+L4KsaUY80GsiF/t0UoRFDHAguKlBaACWJRmdrc6Xfkkag==", "dev": true, "license": "MIT", - "dependencies": { - "@typescript-eslint/utils": "5.29.0", - "debug": "^4.3.4", - "tsutils": "^3.21.0" - }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/types": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.29.0.tgz", - "integrity": "sha512-X99VbqvAXOMdVyfFmksMy3u8p8yoRGITgU1joBJPzeYa0rhdf5ok9S56/itRoUSh99fiDoMtarSIJXo7H/SnOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.29.0.tgz", - "integrity": "sha512-mQvSUJ/JjGBdvo+1LwC+GY2XmSYjK1nAaVw2emp/E61wEVYEyibRHCqm1I1vEKbXCpUKuW4G7u9ZCaZhJbLoNQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/types": "5.29.0", - "@typescript-eslint/visitor-keys": "5.29.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "typescript": ">=4.8.4 <6.0.0" } }, "node_modules/@typescript-eslint/utils": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.29.0.tgz", - "integrity": "sha512-3Eos6uP1nyLOBayc/VUdKZikV90HahXE5Dx9L5YlSd/7ylQPXhLk1BYb29SDgnBnTp+jmSZUU0QxUiyHgW4p7A==", + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.46.2.tgz", + "integrity": "sha512-sExxzucx0Tud5tE0XqR0lT0psBQvEpnpiul9XbGUB1QwpWJJAps1O/Z7hJxLGiZLBKMCutjTzDgmd1muEhBnVg==", "dev": true, "license": "MIT", "dependencies": { - "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.29.0", - "@typescript-eslint/types": "5.29.0", - "@typescript-eslint/typescript-estree": "5.29.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.46.2", + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/typescript-estree": "8.46.2" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" } }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.29.0.tgz", - "integrity": "sha512-Hpb/mCWsjILvikMQoZIE3voc9wtQcS0A9FUw3h8bhr9UxBdtI/tw1ZDZUOXHXLOVMedKCH5NxyzATwnU78bWCQ==", + "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/scope-manager": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.46.2.tgz", + "integrity": "sha512-LF4b/NmGvdWEHD2H4MsHD8ny6JpiVNDzrSZr3CsckEgCbAGZbYM4Cqxvi9L+WqDMT+51Ozy7lt2M+d0JLEuBqA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "5.29.0", - "eslint-visitor-keys": "^3.3.0" + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/visitor-keys": "8.46.2" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", - "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", + "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/types": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.46.2.tgz", + "integrity": "sha512-lNCWCbq7rpg7qDsQrd3D6NyWYu+gkTENkG5IKYhUIcxSb59SQC/hEQ+MrG4sTgBVghTonNWq42bA/d4yYumldQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/typescript-estree": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.46.2.tgz", + "integrity": "sha512-f7rW7LJ2b7Uh2EiQ+7sza6RDZnajbNbemn54Ob6fRwQbgcIn+GWfyuHDHRYgRoZu1P4AayVScrRW+YfbTvPQoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.46.2", + "@typescript-eslint/tsconfig-utils": "8.46.2", + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/visitor-keys": "8.46.2", + "debug": "^4.3.4", + "fast-glob": "^3.3.2", + "is-glob": "^4.0.3", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/@typescript-eslint/visitor-keys": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.46.2.tgz", + "integrity": "sha512-tUFMXI4gxzzMXt4xpGJEsBsTox0XbNQ1y94EwlD/CuZwFcQP79xfQqMhau9HsRc/J0cAPA/HZt1dZPtGn9V/7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.46.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@typescript-eslint/utils/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", "dev": true, "license": "ISC", - "peer": true + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, "node_modules/acorn": { "version": "8.15.0", @@ -819,7 +890,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -833,7 +903,6 @@ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } @@ -844,7 +913,6 @@ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -856,24 +924,12 @@ "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, "node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "color-convert": "^2.0.1" }, @@ -889,26 +945,14 @@ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true, - "license": "Python-2.0", - "peer": true - }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } + "license": "Python-2.0" }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/brace-expansion": { "version": "1.1.12", @@ -916,7 +960,6 @@ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -954,7 +997,6 @@ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=6" } @@ -965,7 +1007,6 @@ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -983,7 +1024,6 @@ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "color-name": "~1.1.4" }, @@ -996,16 +1036,14 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/crelt": { "version": "1.0.6", @@ -1021,7 +1059,6 @@ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -1054,35 +1091,7 @@ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } + "license": "MIT" }, "node_modules/esbuild": { "version": "0.17.3", @@ -1128,7 +1137,6 @@ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -1137,104 +1145,80 @@ } }, "node_modules/eslint": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", - "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "version": "9.38.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.38.0.tgz", + "integrity": "sha512-t5aPOpmtJcZcz5UJyY2GbvpDlsK5E8JqRqoKtfiKE3cNh437KIqfJr3A3AKf5k64NPx6d0G3dno6XDY05PqPtw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.1", - "@humanwhocodes/config-array": "^0.13.0", + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.1", + "@eslint/config-helpers": "^0.4.1", + "@eslint/core": "^0.16.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.38.0", + "@eslint/plugin-kit": "^0.4.0", + "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", "ajv": "^6.12.4", "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", + "cross-spawn": "^7.0.6", "debug": "^4.3.2", - "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", + "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" + "optionator": "^0.9.3" }, "bin": { "eslint": "bin/eslint.js" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } } }, "node_modules/eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", "dev": true, "license": "BSD-2-Clause", "dependencies": { "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" + "estraverse": "^5.2.0" }, "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^2.0.0" - }, - "engines": { - "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=5" - } - }, - "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=10" + "url": "https://opencollective.com/eslint" } }, "node_modules/eslint-visitor-keys": { @@ -1250,49 +1234,45 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint/node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", "dev": true, - "license": "BSD-2-Clause", - "peer": true, - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, + "license": "Apache-2.0", "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "peer": true, - "engines": { - "node": ">=4.0" - } - }, "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { - "acorn": "^8.9.0", + "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" + "eslint-visitor-keys": "^4.2.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -1304,7 +1284,6 @@ "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", "dev": true, "license": "BSD-3-Clause", - "peer": true, "dependencies": { "estraverse": "^5.1.0" }, @@ -1312,17 +1291,6 @@ "node": ">=0.10" } }, - "node_modules/esquery/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "peer": true, - "engines": { - "node": ">=4.0" - } - }, "node_modules/esrecurse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", @@ -1336,7 +1304,7 @@ "node": ">=4.0" } }, - "node_modules/esrecurse/node_modules/estraverse": { + "node_modules/estraverse": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", @@ -1346,23 +1314,12 @@ "node": ">=4.0" } }, - "node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -1372,8 +1329,7 @@ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/fast-glob": { "version": "3.3.3", @@ -1410,16 +1366,14 @@ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/fastq": { "version": "1.19.1", @@ -1432,17 +1386,16 @@ } }, "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "flat-cache": "^3.0.4" + "flat-cache": "^4.0.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16.0.0" } }, "node_modules/fill-range": { @@ -1464,7 +1417,6 @@ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" @@ -1477,19 +1429,17 @@ } }, "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" + "keyv": "^4.5.4" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16" } }, "node_modules/flatted": { @@ -1497,46 +1447,7 @@ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", "dev": true, - "license": "ISC", - "peer": true - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC", - "peer": true - }, - "node_modules/functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==", - "dev": true, - "license": "MIT" - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "peer": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } + "license": "ISC" }, "node_modules/glob-parent": { "version": "6.0.2", @@ -1544,7 +1455,6 @@ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "is-glob": "^4.0.3" }, @@ -1553,38 +1463,13 @@ } }, "node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "type-fest": "^0.20.2" - }, "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - }, - "engines": { - "node": ">=10" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -1595,8 +1480,7 @@ "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/has-flag": { "version": "4.0.0", @@ -1604,7 +1488,6 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -1625,7 +1508,6 @@ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -1643,32 +1525,10 @@ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.8.19" } }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", - "peer": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC", - "peer": true - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -1702,24 +1562,12 @@ "node": ">=0.12.0" } }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/js-yaml": { "version": "4.1.0", @@ -1727,7 +1575,6 @@ "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "argparse": "^2.0.1" }, @@ -1740,24 +1587,21 @@ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/keyv": { "version": "4.5.4", @@ -1765,7 +1609,6 @@ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "json-buffer": "3.0.1" } @@ -1776,7 +1619,6 @@ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" @@ -1791,7 +1633,6 @@ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "p-locate": "^5.0.0" }, @@ -1807,8 +1648,7 @@ "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/merge2": { "version": "1.4.1", @@ -1840,7 +1680,6 @@ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -1870,8 +1709,7 @@ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/obsidian": { "version": "1.8.7", @@ -1888,24 +1726,12 @@ "@codemirror/view": "^6.0.0" } }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "peer": true, - "dependencies": { - "wrappy": "1" - } - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", @@ -1924,7 +1750,6 @@ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "yocto-queue": "^0.1.0" }, @@ -1941,7 +1766,6 @@ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "p-limit": "^3.0.2" }, @@ -1958,7 +1782,6 @@ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "callsites": "^3.0.0" }, @@ -1972,39 +1795,16 @@ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true, "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true, - "license": "MIT", "engines": { "node": ">=8" } @@ -2028,7 +1828,6 @@ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 0.8.0" } @@ -2039,7 +1838,6 @@ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=6" } @@ -2065,26 +1863,12 @@ ], "license": "MIT" }, - "node_modules/regexpp": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - } - }, "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=4" } @@ -2100,24 +1884,6 @@ "node": ">=0.10.0" } }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "dev": true, - "license": "ISC", - "peer": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -2161,7 +1927,6 @@ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "shebang-regex": "^3.0.0" }, @@ -2175,31 +1940,6 @@ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true, "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, "engines": { "node": ">=8" } @@ -2210,7 +1950,6 @@ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" }, @@ -2232,7 +1971,6 @@ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -2240,14 +1978,6 @@ "node": ">=8" } }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -2261,6 +1991,19 @@ "node": ">=8.0" } }, + "node_modules/ts-api-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/tslib": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", @@ -2268,36 +2011,12 @@ "dev": true, "license": "0BSD" }, - "node_modules/tsutils": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", - "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", - "dev": true, - "license": "MIT", - "dependencies": { - "tslib": "^1.8.1" - }, - "engines": { - "node": ">= 6" - }, - "peerDependencies": { - "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" - } - }, - "node_modules/tsutils/node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true, - "license": "0BSD" - }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "prelude-ls": "^1.2.1" }, @@ -2305,24 +2024,10 @@ "node": ">= 0.8.0" } }, - "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "peer": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/typescript": { - "version": "4.7.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", - "integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", "dev": true, "license": "Apache-2.0", "bin": { @@ -2330,7 +2035,239 @@ "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.46.2.tgz", + "integrity": "sha512-vbw8bOmiuYNdzzV3lsiWv6sRwjyuKJMQqWulBOU7M0RrxedXledX8G8kBbQeiOYDnTfiXz0Y4081E1QMNB6iQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.46.2", + "@typescript-eslint/parser": "8.46.2", + "@typescript-eslint/typescript-estree": "8.46.2", + "@typescript-eslint/utils": "8.46.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.46.2.tgz", + "integrity": "sha512-ZGBMToy857/NIPaaCucIUQgqueOiq7HeAKkhlvqVV4lm089zUFW6ikRySx2v+cAhKeUCPuWVHeimyk6Dw1iY3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.46.2", + "@typescript-eslint/type-utils": "8.46.2", + "@typescript-eslint/utils": "8.46.2", + "@typescript-eslint/visitor-keys": "8.46.2", + "graphemer": "^1.4.0", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.46.2", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/parser": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.46.2.tgz", + "integrity": "sha512-BnOroVl1SgrPLywqxyqdJ4l3S2MsKVLDVxZvjI1Eoe8ev2r3kGDo+PcMihNmDE+6/KjkTubSJnmqGZZjQSBq/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.46.2", + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/typescript-estree": "8.46.2", + "@typescript-eslint/visitor-keys": "8.46.2", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/scope-manager": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.46.2.tgz", + "integrity": "sha512-LF4b/NmGvdWEHD2H4MsHD8ny6JpiVNDzrSZr3CsckEgCbAGZbYM4Cqxvi9L+WqDMT+51Ozy7lt2M+d0JLEuBqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/visitor-keys": "8.46.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/type-utils": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.46.2.tgz", + "integrity": "sha512-HbPM4LbaAAt/DjxXaG9yiS9brOOz6fabal4uvUmaUYe6l3K1phQDMQKBRUrr06BQkxkvIZVVHttqiybM9nJsLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/typescript-estree": "8.46.2", + "@typescript-eslint/utils": "8.46.2", + "debug": "^4.3.4", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/types": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.46.2.tgz", + "integrity": "sha512-lNCWCbq7rpg7qDsQrd3D6NyWYu+gkTENkG5IKYhUIcxSb59SQC/hEQ+MrG4sTgBVghTonNWq42bA/d4yYumldQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/typescript-estree": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.46.2.tgz", + "integrity": "sha512-f7rW7LJ2b7Uh2EiQ+7sza6RDZnajbNbemn54Ob6fRwQbgcIn+GWfyuHDHRYgRoZu1P4AayVScrRW+YfbTvPQoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.46.2", + "@typescript-eslint/tsconfig-utils": "8.46.2", + "@typescript-eslint/types": "8.46.2", + "@typescript-eslint/visitor-keys": "8.46.2", + "debug": "^4.3.4", + "fast-glob": "^3.3.2", + "is-glob": "^4.0.3", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/@typescript-eslint/visitor-keys": { + "version": "8.46.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.46.2.tgz", + "integrity": "sha512-tUFMXI4gxzzMXt4xpGJEsBsTox0XbNQ1y94EwlD/CuZwFcQP79xfQqMhau9HsRc/J0cAPA/HZt1dZPtGn9V/7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.46.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/typescript-eslint/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/typescript-eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/typescript-eslint/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/typescript-eslint/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/uri-js": { @@ -2339,7 +2276,6 @@ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { "punycode": "^2.1.0" } @@ -2358,7 +2294,6 @@ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "isexe": "^2.0.0" }, @@ -2375,26 +2310,16 @@ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC", - "peer": true - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, diff --git a/package.json b/package.json index 06649bd..7453192 100644 --- a/package.json +++ b/package.json @@ -8,17 +8,26 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json" }, - "keywords": ["obsidian", "plugin", "writing", "prompts", "ai", "claude", "freewriting"], + "keywords": [ + "obsidian", + "plugin", + "writing", + "prompts", + "ai", + "claude", + "freewriting" + ], "author": "Alexander Kucera", "license": "GPL-3.0-only", "devDependencies": { + "@eslint/js": "^9.17.0", "@types/node": "^16.11.6", - "@typescript-eslint/eslint-plugin": "5.29.0", - "@typescript-eslint/parser": "5.29.0", "builtin-modules": "3.3.0", "esbuild": "0.17.3", + "eslint": "^9.17.0", "obsidian": "latest", "tslib": "2.4.0", - "typescript": "4.7.4" + "typescript": "5.7.3", + "typescript-eslint": "^8.18.2" } } -- 2.36.6 From db641cfe9d09a4e3d5fcc48f316cb1c63e49dce6 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:33:50 +0200 Subject: [PATCH 30/60] Updates ANTHROPIC_MODELS with latest model versions Refreshes hardcoded fallback model list with recent Claude AI model releases Adds newest model versions: - Sonnet 4.5 - Haiku 4.5 - Opus 4.1 Reorganizes model list for clarity, keeping legacy models for backward compatibility --- types.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types.ts b/types.ts index 5b4315b..32dfd64 100644 --- a/types.ts +++ b/types.ts @@ -154,12 +154,22 @@ export interface ModelCache { * Hardcoded fallback list of known Claude models. * Used when the Models API is unavailable or the API key is not configured. * This list should be updated periodically as new models are released. + * + * Organized by family (newest to oldest): + * - Sonnet 4.5 (latest, released Sept 29, 2025) + * - Haiku 4.5 (released Oct 1, 2025) + * - Opus 4.1 (released Aug 5, 2025) + * - Legacy models (Sonnet 4, 3.7, Opus 4, Haiku 3.5, Haiku 3) */ export const ANTHROPIC_MODELS = [ + // Current Models (using -latest aliases for stability) + 'claude-sonnet-4-5-20250929', + 'claude-haiku-4-5-20251001', 'claude-opus-4-1-20250805', - 'claude-opus-4-20250514', + // Legacy Models 'claude-sonnet-4-20250514', 'claude-3-7-sonnet-latest', + 'claude-opus-4-20250514', 'claude-3-5-haiku-latest', 'claude-3-haiku-20240307' ] as const; -- 2.36.6 From c698a193450ddc75285a8749f65d691eb994384f Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:36:26 +0200 Subject: [PATCH 31/60] Improves timed prompt notification duration calculation Refines notification display duration for timed prompts to handle both short and long delay intervals Adjusts duration calculation to: - Cap notifications at 500ms for very short delays - Subtract 500ms from longer delays to prevent prompt overlap - Ensures smoother user experience during prompt sequences --- commands/timedPrompts.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index 1d9607a..39bb338 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -169,8 +169,9 @@ export class TimedPromptsCommand { const totalPrompts = this.promptQueue.length; // Calculate notification duration: slightly less than delay to avoid overlap - // Subtract 500ms to allow for fade-out before next prompt appears - const notificationDuration = Math.max(1000, (delaySeconds * 1000) - 500); + // For very short delays (<=1s), cap at 500ms; otherwise end 500ms before next tick + const delayMs = delaySeconds * 1000; + const notificationDuration = delayMs > 1000 ? (delayMs - 500) : 500; const notice = new Notice( `Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`, -- 2.36.6 From cc1b452872257b7000b435f92383412618aad139 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:36:33 +0200 Subject: [PATCH 32/60] Extracts note command execute validation logic Refactors active note validation into a dedicated static method for improved readability and reusability Enhances code maintainability by centralizing the check for valid editor and view --- commands/notePrompts.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index cc3e842..2e72fe1 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -50,7 +50,7 @@ export class NotePromptsCommand { editor: Editor, view: MarkdownView ): Promise { - if (!editor || !view) { + if (!NotePromptsCommand.canExecute(editor, view)) { new Notice('No active note found. Please open a note first.'); return; } -- 2.36.6 From e5c7a523c52154035bad43116105b2b4eed18eff Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:38:28 +0200 Subject: [PATCH 33/60] Improves Anthropic API client robustness Enhances API client with more reliable pagination and response handling: - Uses URLSearchParams for clearer parameter management - Increases pagination limit to 1000 to reduce API calls - Adds more robust content parsing for multi-block responses - Implements stricter API health check validation Ensures more predictable and resilient API interactions --- api/anthropicClient.ts | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 12540ff..f0ed36d 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -133,8 +133,14 @@ export class AnthropicClient { // Fetch all pages while (hasMore) { - // Build URL with pagination parameter if needed - const url = afterId ? `${this.modelsUrl}?after=${afterId}` : this.modelsUrl; + // Build URL with pagination parameters + // Use limit=1000 (Anthropic's max) to minimize round trips + const params = new URLSearchParams(); + params.set('limit', '1000'); + if (afterId) { + params.set('after', afterId); + } + const url = `${this.modelsUrl}?${params.toString()}`; const response = await requestUrl({ url, @@ -273,7 +279,12 @@ export class AnthropicClient { throw new Error('No content received from API'); } - const text = response.content[0].text; + // Parse all text blocks, not just the first one + // Anthropic API can return multiple content blocks + const text = response.content + .filter(c => c && c.type === 'text' && typeof c.text === 'string') + .map(c => c.text) + .join('\n'); const lines = text.split('\n') .map(line => line.trim()) .filter(line => line.length > 0); @@ -362,9 +373,16 @@ export class AnthropicClient { const response = await this.makeRequest(testRequest); const responseTime = Date.now() - startTime; + // Validate that the assistant actually returned "ping" + // This ensures the API is working correctly, not just returning a 2xx status + const returnedText = (response.content?.[0]?.text || '').trim().toLowerCase(); + const isValid = returnedText === 'ping'; + return { - success: true, - message: 'API key is valid and working correctly', + success: isValid, + message: isValid + ? 'API key is valid and working correctly' + : 'API responded but returned unexpected content', details: { model: response.model, responseTime, -- 2.36.6 From b76f08513736c93283fa6c27c9b9d2ae15c714da Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:40:42 +0200 Subject: [PATCH 34/60] Improves model fetching with deduplication and notice control Adds a session-based flag to prevent repeated fallback notices during API failures Implements model list deduplication to handle potential duplicate entries Prevents spamming users with repeated error notifications Resets notice flag on successful model fetches to allow future warnings --- services/modelService.ts | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 6ca7c27..4492b3c 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -34,6 +34,8 @@ export class ModelService { private modelCache: ModelCache | null = null; /** Cache time-to-live in milliseconds (24 hours) */ private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours + /** Track whether we've shown the fallback notice this session to avoid spam */ + private hasShownFallbackNotice = false; /** * Creates a new model service instance. @@ -74,10 +76,16 @@ export class ModelService { try { const response = await this.anthropicClient.fetchModels(); this.updateCache(response.data); + // Reset notice flag on successful fetch + this.hasShownFallbackNotice = false; return this.formatModels(response.data); } catch (error) { console.error('Failed to fetch models from API:', error); - new Notice('Could not fetch latest models from API. Using default model list.'); + // Only show notice once per session to avoid spamming during offline periods + if (!this.hasShownFallbackNotice) { + new Notice('Could not fetch latest models from API. Using default model list.'); + this.hasShownFallbackNotice = true; + } return this.getFallbackModels(); } } @@ -100,10 +108,16 @@ export class ModelService { try { const response = await this.anthropicClient.fetchModels(); this.updateCache(response.data); + // Reset notice flag on successful fetch + this.hasShownFallbackNotice = false; return this.formatModels(response.data); } catch (error) { console.error('Failed to refresh models from API:', error); - new Notice('Fetching current models failed. Using hardcoded fallback list.'); + // Only show notice once per session to avoid spamming during repeated failures + if (!this.hasShownFallbackNotice) { + new Notice('Fetching current models failed. Using hardcoded fallback list.'); + this.hasShownFallbackNotice = true; + } return this.getFallbackModels(); } } @@ -165,13 +179,21 @@ export class ModelService { /** * Updates the cache with freshly fetched model data. * - * Sets the fetchedAt timestamp to now, starting the 24-hour TTL countdown. + * Deduplicates models by ID to guard against accidental duplicates + * across pagination responses. Sets the fetchedAt timestamp to now, + * starting the 24-hour TTL countdown. * * @param models - Array of model information from the API */ private updateCache(models: ModelInfo[]): void { + // Deduplicate by id using Map + const byId = new Map(); + for (const model of models) { + byId.set(model.id, model); + } + this.modelCache = { - models, + models: Array.from(byId.values()), fetchedAt: Date.now() }; } -- 2.36.6 From 61788b39adcf4605a826d6c844da0b068bdd28b6 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:41:44 +0200 Subject: [PATCH 35/60] Enforces precise prompt generation count Trims generated prompts to requested count Ensures consistent user experience by slicing array if model over-generates Prevents potential cache key mismatches due to inconsistent prompt counts --- services/promptGenerator.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index 36a0769..46ae7da 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -155,7 +155,13 @@ export class PromptGeneratorService { try { new Notice('Generating prompts...'); - const prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type); + let prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type); + + // Enforce requested count - models can occasionally over-generate + // This ensures deterministic UX and correct cache key matching + if (prompts.length > count) { + prompts = prompts.slice(0, count); + } const generatedPrompts: GeneratedPrompt[] = prompts.map(text => ({ text, -- 2.36.6 From 53e61abd3b47e44a4306c78a352bff0789a74dbb Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:44:45 +0200 Subject: [PATCH 36/60] Optimize settings and API key management Improves settings loading and saving by preventing model cache merging and tracking API key changes Prevents type drift in settings by destructuring saved data Adds tracking of last API key to avoid unnecessary prompt generator updates Ensures only meaningful settings are merged with defaults Reduces redundant operations and improves plugin performance --- main.ts | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/main.ts b/main.ts index 3e1775e..aef3700 100644 --- a/main.ts +++ b/main.ts @@ -37,6 +37,8 @@ export default class FreewritingPromptsPlugin extends Plugin { timedCommand: TimedPromptsCommand; /** Command handler for note prompt insertion */ noteCommand: NotePromptsCommand; + /** Tracks last saved API key to avoid unnecessary cache clears */ + private lastApiKey?: string; /** * Called when the plugin loads. @@ -49,7 +51,13 @@ export default class FreewritingPromptsPlugin extends Plugin { async onload() { // Load data once and use it for both settings and model cache const data = await this.loadData() as FreewritingPromptsData | null; - this.settings = Object.assign({}, DEFAULT_SETTINGS, data); + + // Destructure to prevent modelCache from being merged into settings (type drift) + const { modelCache, ...savedSettings } = data ?? {}; + this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings); + + // Track initial API key to detect changes on save + this.lastApiKey = this.settings.apiKey; // Initialize services this.promptGenerator = new PromptGeneratorService(this.settings); @@ -58,8 +66,8 @@ export default class FreewritingPromptsPlugin extends Plugin { this.noteCommand = new NotePromptsCommand(this.promptGenerator); // Load model cache - if (data?.modelCache) { - this.modelService.loadCache(data.modelCache); + if (modelCache) { + this.modelService.loadCache(modelCache); } // Register commands @@ -93,16 +101,6 @@ export default class FreewritingPromptsPlugin extends Plugin { // MARK: - Settings Management - /** - * Loads plugin settings from disk. - * - * Merges saved settings with defaults to ensure any new settings added - * in plugin updates have sensible default values. - */ - async loadSettings() { - this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); - } - /** * Saves plugin settings to disk. * @@ -118,9 +116,11 @@ export default class FreewritingPromptsPlugin extends Plugin { }; await this.saveData(data); - // Update the prompt generator with new settings - if (this.promptGenerator) { + // Update the prompt generator only if API key actually changed + // This avoids clearing the prompt cache unnecessarily on every save + if (this.promptGenerator && this.lastApiKey !== this.settings.apiKey) { this.promptGenerator.updateApiKey(this.settings.apiKey); + this.lastApiKey = this.settings.apiKey; } } -- 2.36.6 From 52ea9de4c0c39f2fd57cfc5b4c5e026d7f28b956 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:46:25 +0200 Subject: [PATCH 37/60] Improves model fallback and settings handling Enhances model selection resilience by adding detailed fallback notifications Adds model ID check before changing default model to prevent unnecessary updates Improves user experience with more informative model unavailability notices Removes redundant API key update and settings save operations Supports dynamic model management on model refresh --- settings.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/settings.ts b/settings.ts index b7db14e..b3c7819 100644 --- a/settings.ts +++ b/settings.ts @@ -109,7 +109,8 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .onChange(async (value) => { this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); - this.plugin.promptGenerator.updateApiKey(value); + // Note: updateApiKey is called by saveSettings only if key changed + // This avoids clearing the prompt cache twice // Clear any existing debounce timer if (this.apiKeyDebounceTimer !== null) { @@ -309,10 +310,11 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { } else { // Fall back to first available model if current one is gone const fallbackModel = this.availableModels[0]; - if (fallbackModel) { + if (fallbackModel && this.plugin.settings.model !== fallbackModel.id) { this.modelDropdown.setValue(fallbackModel.id); this.plugin.settings.model = fallbackModel.id; await this.plugin.saveSettings(); + new Notice(`Your selected model is no longer available. Defaulting to ${fallbackModel.displayName} (${fallbackModel.id})`); } } } @@ -380,16 +382,15 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { } else { // Fall back to first available model if current one is gone const fallbackModel = this.availableModels[0]; - if (fallbackModel) { + if (fallbackModel && this.plugin.settings.model !== fallbackModel.id) { this.modelDropdown.setValue(fallbackModel.id); this.plugin.settings.model = fallbackModel.id; - new Notice('Your selected model is no longer available. Defaulting to ' + fallbackModel.displayName); + new Notice(`Your selected model is no longer available. Defaulting to ${fallbackModel.displayName} (${fallbackModel.id})`); + // Save only if model actually changed + await this.plugin.saveSettings(); } } } - - // Persist any selection changes - await this.plugin.saveSettings(); } catch (error) { console.error('Error refreshing models:', error); // Error already shown by ModelService via Notice -- 2.36.6 From 893aae5bca94c0288e6360395e5cda25091d3d8e Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:48:25 +0200 Subject: [PATCH 38/60] Improves timed prompts command concurrency handling Enhances execution flow to prevent race conditions during async prompt generation Refines inProgress flag management to ensure reliable concurrent execution: - Sets flag before async work begins - Guarantees flag reset in finally block - Prevents potential state inconsistencies during rapid command triggers Clarifies code comments explaining concurrency protection mechanism --- commands/timedPrompts.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index 39bb338..b807a0f 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -51,8 +51,10 @@ export class TimedPromptsCommand { * 4. Shows the first prompt immediately * 5. Starts an interval to show remaining prompts * - * The inProgress flag prevents issues if the user triggers the command - * multiple times quickly while prompt generation is in progress. + * The inProgress flag prevents concurrent executions during async prompt + * generation. It's set to true before any async work begins and reset to + * false in the finally block after all work completes, ensuring reliable + * concurrency protection. * * @param settings - Current plugin settings for generation parameters */ @@ -62,10 +64,11 @@ export class TimedPromptsCommand { new Notice('Timed prompts are already being generated. Please wait.'); return; } - + + // Set flag BEFORE any async work to prevent concurrent execution this.inProgress = true; - // Stop any existing timed sequence + // Stop any existing timed sequence (does NOT reset inProgress) this.stop(); @@ -94,6 +97,8 @@ export class TimedPromptsCommand { console.error('Error executing timed prompts command:', error); // Error handling is done in the service layer } finally { + // Reset flag after all work completes (success or failure) + // This ensures the flag is always reset and prevents stuck state this.inProgress = false; } } @@ -104,6 +109,9 @@ export class TimedPromptsCommand { * Cleans up the interval timer and resets all state. This is important * for preventing memory leaks and ensuring the next execution starts fresh. * Safe to call even when no sequence is running. + * + * Note: Does NOT reset inProgress flag - that's managed by execute() to + * prevent race conditions during async prompt generation. */ stop(): void { if (this.activeInterval !== null) { @@ -112,7 +120,7 @@ export class TimedPromptsCommand { } this.promptQueue = []; this.currentIndex = 0; - this.inProgress = false; + // inProgress is NOT reset here - only execute() manages this flag } /** -- 2.36.6 From afa725df7ffc489177959adbcc153c984e6352b8 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:35:01 +0200 Subject: [PATCH 39/60] Enhances ESLint configuration for TypeScript project Updates ESLint configuration to: - Use latest globals for Node.js and browser environments - Enable type-aware TypeScript ESLint rules - Improve parser and ecmaVersion settings - Add explicit TypeScript ESLint plugin Increases code quality and type safety for the project --- eslint.config.mjs | 20 +++++++++++--------- package-lock.json | 20 +++++++++++++++++--- package.json | 1 + 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index bdd509c..9494561 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,3 +1,4 @@ +import globals from 'globals'; import eslint from '@eslint/js'; import tseslint from 'typescript-eslint'; @@ -7,6 +8,7 @@ export default tseslint.config( ignores: [ 'node_modules/**', 'main.js', + 'dist/**', '*.config.js', '*.config.mjs' ] @@ -15,6 +17,8 @@ export default tseslint.config( eslint.configs.recommended, // TypeScript ESLint recommended rules ...tseslint.configs.recommended, + // Type-aware rules (requires tsconfig.json) + ...tseslint.configs.recommendedTypeChecked, // Project-specific configuration { files: ['**/*.ts'], @@ -22,19 +26,17 @@ export default tseslint.config( parser: tseslint.parser, parserOptions: { sourceType: 'module', - ecmaVersion: 2020 + ecmaVersion: 'latest', + project: ['./tsconfig.json'] }, globals: { - // Node.js globals - console: 'readonly', - process: 'readonly', - __dirname: 'readonly', - __filename: 'readonly', - Buffer: 'readonly', - setImmediate: 'readonly', - clearImmediate: 'readonly' + ...globals.node, + ...globals.browser } }, + plugins: { + '@typescript-eslint': tseslint.plugin + }, rules: { // Disable base rule in favor of TypeScript version 'no-unused-vars': 'off', diff --git a/package-lock.json b/package-lock.json index 49ea9f8..5f9e8c2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "builtin-modules": "3.3.0", "esbuild": "0.17.3", "eslint": "^9.17.0", + "globals": "^16.4.0", "obsidian": "latest", "tslib": "2.4.0", "typescript": "5.7.3", @@ -513,6 +514,19 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@eslint/js": { "version": "9.38.0", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.38.0.tgz", @@ -1463,9 +1477,9 @@ } }, "node_modules/globals": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", - "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.4.0.tgz", + "integrity": "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index 7453192..a4f192a 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "builtin-modules": "3.3.0", "esbuild": "0.17.3", "eslint": "^9.17.0", + "globals": "^16.4.0", "obsidian": "latest", "tslib": "2.4.0", "typescript": "5.7.3", -- 2.36.6 From c9adf05a82f3c6cf0c61f51fe9f314cac0ae3096 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:37:45 +0200 Subject: [PATCH 40/60] Improves model fetching resilience and performance Adds deduplication of concurrent API calls to prevent redundant requests Enhances error handling by preferring stale cache over hardcoded fallback models Introduces new getStaleCacheModels method to provide more robust model retrieval Prevents multiple simultaneous model fetch attempts with in-flight request tracking --- services/modelService.ts | 44 ++++++++++++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index 4492b3c..d6d0db5 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -36,6 +36,8 @@ export class ModelService { private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours /** Track whether we've shown the fallback notice this session to avoid spam */ private hasShownFallbackNotice = false; + /** In-flight fetch promise to deduplicate concurrent API calls */ + private inFlight: Promise | null = null; /** * Creates a new model service instance. @@ -72,13 +74,21 @@ export class ModelService { return this.getFallbackModels(); } - // Try to fetch from API + // Try to fetch from API (deduplicate concurrent calls) + if (!this.inFlight) { + this.inFlight = (async () => { + const response = await this.anthropicClient.fetchModels(); + this.updateCache(response.data); + // Reset notice flag on successful fetch + this.hasShownFallbackNotice = false; + return this.formatModels(response.data); + })().finally(() => { + this.inFlight = null; + }); + } + try { - const response = await this.anthropicClient.fetchModels(); - this.updateCache(response.data); - // Reset notice flag on successful fetch - this.hasShownFallbackNotice = false; - return this.formatModels(response.data); + return await this.inFlight; } catch (error) { console.error('Failed to fetch models from API:', error); // Only show notice once per session to avoid spamming during offline periods @@ -86,7 +96,8 @@ export class ModelService { new Notice('Could not fetch latest models from API. Using default model list.'); this.hasShownFallbackNotice = true; } - return this.getFallbackModels(); + // Prefer stale cache over hardcoded fallback if available + return this.getStaleCacheModels() ?? this.getFallbackModels(); } } @@ -118,7 +129,8 @@ export class ModelService { new Notice('Fetching current models failed. Using hardcoded fallback list.'); this.hasShownFallbackNotice = true; } - return this.getFallbackModels(); + // Prefer stale cache over hardcoded fallback if available + return this.getStaleCacheModels() ?? this.getFallbackModels(); } } @@ -176,6 +188,22 @@ export class ModelService { return age < this.CACHE_TTL_MS; } + /** + * Returns cached models if present, regardless of TTL. + * + * This is used as a fallback when API fetch fails - a slightly stale cache + * is often better than falling back to the hardcoded model list, which may + * be more outdated than the cached data. + * + * @returns Array of cached model options, or null if no cache exists + */ + private getStaleCacheModels(): ModelOption[] | null { + if (!this.modelCache) { + return null; + } + return this.formatModels(this.modelCache.models); + } + /** * Updates the cache with freshly fetched model data. * -- 2.36.6 From 13645af300b3a85842a5419b8176fb73107d67d5 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:41:53 +0200 Subject: [PATCH 41/60] Improves data loading with robust error handling Adds comprehensive error handling for plugin data loading to prevent potential startup failures Implements graceful fallback to default settings when data loading fails or is corrupted Ensures plugin can initialize even with invalid or missing persistent data Separates model cache extraction to prevent type drift and improve data integrity --- main.ts | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/main.ts b/main.ts index aef3700..06039b2 100644 --- a/main.ts +++ b/main.ts @@ -2,7 +2,7 @@ // ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle import { Editor, MarkdownView, Notice, Plugin } from 'obsidian'; -import { FreewritingPromptsSettings, FreewritingPromptsData } from './types'; +import { FreewritingPromptsSettings, FreewritingPromptsData, ModelCache } from './types'; import { DEFAULT_SETTINGS, FreewritingPromptsSettingTab } from './settings'; import { PromptGeneratorService } from './services/promptGenerator'; import { ModelService } from './services/modelService'; @@ -50,11 +50,25 @@ export default class FreewritingPromptsPlugin extends Plugin { */ async onload() { // Load data once and use it for both settings and model cache - const data = await this.loadData() as FreewritingPromptsData | null; - - // Destructure to prevent modelCache from being merged into settings (type drift) - const { modelCache, ...savedSettings } = data ?? {}; - this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings); + // Guard against corrupted persisted data to prevent plugin load failure + let modelCache: ModelCache | undefined; + try { + const data = await this.loadData() as FreewritingPromptsData | null; + if (data) { + // Destructure to prevent modelCache from being merged into settings (type drift) + const { modelCache: cache, ...savedSettings } = data; + modelCache = cache; + this.settings = Object.assign({}, DEFAULT_SETTINGS, savedSettings); + } else { + // No data loaded, use defaults + this.settings = { ...DEFAULT_SETTINGS }; + modelCache = undefined; + } + } catch (error) { + console.error('Failed to load settings; using defaults.', error); + this.settings = { ...DEFAULT_SETTINGS }; + modelCache = undefined; + } // Track initial API key to detect changes on save this.lastApiKey = this.settings.apiKey; -- 2.36.6 From 8e6441ff7d96b5b51b2f08e60dac77a1dd95b817 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:42:04 +0200 Subject: [PATCH 42/60] Improves timestamp localization for note prompts Uses the user's preferred language locale for timestamp formatting, enhancing regional customization and user experience Allows automatic fallback to 'en-US' if navigator language is unavailable --- commands/notePrompts.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index 2e72fe1..d703d42 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -146,7 +146,9 @@ export class NotePromptsCommand { * @returns Formatted markdown string ready for insertion */ private formatPrompts(prompts: string[]): string { - const timestamp = new Intl.DateTimeFormat('en-US', { + // Use user's locale for timestamp formatting to respect regional preferences + const locale = navigator?.language ?? 'en-US'; + const timestamp = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short', day: 'numeric', -- 2.36.6 From a93c887cad66dc1592abda1c4ac3c39c69302133 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:46:59 +0200 Subject: [PATCH 43/60] Optimizes settings handling with debounce and async improvements Introduces debounce mechanism for settings saves to reduce unnecessary disk writes Refactors settings change handlers to: - Improve performance by debouncing save operations - Simplify async method handling - Prevent excessive API calls and disk writes - Add more robust handling of model loading and settings updates Enhances user experience by minimizing unnecessary background operations --- settings.ts | 80 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 54 insertions(+), 26 deletions(-) diff --git a/settings.ts b/settings.ts index b3c7819..bbd4650 100644 --- a/settings.ts +++ b/settings.ts @@ -58,8 +58,12 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { private availableModels: ModelOption[] = []; /** Debounce timer for API key changes to avoid excessive API calls */ private apiKeyDebounceTimer: number | null = null; + /** Debounce timer for settings saves to reduce disk writes */ + private settingsSaveTimer: number | null = null; /** Debounce delay in milliseconds */ private readonly API_KEY_DEBOUNCE_MS = 500; + /** Debounce delay for settings saves in milliseconds */ + private readonly SETTINGS_SAVE_DEBOUNCE_MS = 500; /** * Creates a new settings tab instance. @@ -81,6 +85,24 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { window.clearTimeout(this.apiKeyDebounceTimer); this.apiKeyDebounceTimer = null; } + if (this.settingsSaveTimer !== null) { + window.clearTimeout(this.settingsSaveTimer); + this.settingsSaveTimer = null; + } + } + + /** + * Debounces settings saves to reduce disk writes on rapid changes. + * Clears any pending save and schedules a new one after the debounce delay. + */ + private debounceSaveSettings(): void { + if (this.settingsSaveTimer !== null) { + window.clearTimeout(this.settingsSaveTimer); + } + this.settingsSaveTimer = window.setTimeout(() => { + void this.plugin.saveSettings(); + this.settingsSaveTimer = null; + }, this.SETTINGS_SAVE_DEBOUNCE_MS); } /** @@ -90,7 +112,7 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { * of model data without blocking the UI. The model dropdown starts with * a "Loading models..." placeholder and updates when data arrives. */ - async display(): Promise { + display(): void { const { containerEl } = this; containerEl.empty(); @@ -106,11 +128,8 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .addText(text => text .setPlaceholder('sk-ant-...') .setValue(this.plugin.settings.apiKey) - .onChange(async (value) => { + .onChange((value) => { this.plugin.settings.apiKey = value; - await this.plugin.saveSettings(); - // Note: updateApiKey is called by saveSettings only if key changed - // This avoids clearing the prompt cache twice // Clear any existing debounce timer if (this.apiKeyDebounceTimer !== null) { @@ -118,13 +137,20 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.apiKeyDebounceTimer = null; } - // Debounce model refresh to avoid excessive API calls on every keystroke - if (value.trim().length > 0) { - this.apiKeyDebounceTimer = window.setTimeout(async () => { - await this.refreshModels(); + // Debounce both saving and model refresh to reduce disk writes and API calls + this.apiKeyDebounceTimer = window.setTimeout(() => { + void (async () => { + await this.plugin.saveSettings(); + // Note: updateApiKey is called by saveSettings only if key changed + // This avoids clearing the prompt cache twice + + // Refresh models if API key has content + if (value.trim().length > 0) { + await this.refreshModels(); + } this.apiKeyDebounceTimer = null; - }, this.API_KEY_DEBOUNCE_MS); - } + })(); + }, this.API_KEY_DEBOUNCE_MS); })) .then(setting => { // Make it a password field @@ -136,8 +162,8 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .setDesc('Test your API key to verify it works correctly') .addButton(button => button .setButtonText('Test Connection') - .onClick(async () => { - await this.testApiKey(button); + .onClick(() => { + void this.testApiKey(button); })); new Setting(containerEl) @@ -146,16 +172,18 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .addDropdown(dropdown => { this.modelDropdown = dropdown; this.populateModelDropdown(dropdown); - dropdown - .setValue(this.plugin.settings.model) - .onChange(async (value) => { - this.plugin.settings.model = value; - await this.plugin.saveSettings(); - }); + // Only set value if models are loaded to avoid setting non-existent options + if (this.availableModels.length > 0) { + dropdown.setValue(this.plugin.settings.model); + } + dropdown.onChange(async (value) => { + this.plugin.settings.model = value; + await this.plugin.saveSettings(); + }); }); // Load models asynchronously without blocking UI - this.loadModelsAsync(); + void this.loadModelsAsync(); // MARK: - Command Configuration @@ -213,9 +241,9 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .addTextArea(text => text .setPlaceholder('You are a creative writing assistant...') .setValue(this.plugin.settings.systemPrompt) - .onChange(async (value) => { + .onChange((value) => { this.plugin.settings.systemPrompt = value; - await this.plugin.saveSettings(); + this.debounceSaveSettings(); })) .then(setting => { setting.controlEl.querySelector('textarea')?.setAttribute('rows', '3'); @@ -227,9 +255,9 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .addTextArea(text => text .setPlaceholder('Write about a character who...') .setValue(this.plugin.settings.timedExamplePrompt) - .onChange(async (value) => { + .onChange((value) => { this.plugin.settings.timedExamplePrompt = value; - await this.plugin.saveSettings(); + this.debounceSaveSettings(); })) .then(setting => { setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2'); @@ -241,9 +269,9 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { .addTextArea(text => text .setPlaceholder('Describe a world where...') .setValue(this.plugin.settings.freewritingExamplePrompt) - .onChange(async (value) => { + .onChange((value) => { this.plugin.settings.freewritingExamplePrompt = value; - await this.plugin.saveSettings(); + this.debounceSaveSettings(); })) .then(setting => { setting.controlEl.querySelector('textarea')?.setAttribute('rows', '2'); -- 2.36.6 From 329c12ab4b86af296e7fe2a419c2d542613525e3 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:50:20 +0200 Subject: [PATCH 44/60] Refactors Anthropic API client configuration Centralizes API base URL and version configuration for improved maintainability Adds constants for API base URL and version to prevent potential drift Normalizes API version header usage across request methods Improves ping validation to handle variations in response text Supports more robust and consistent API client configuration --- api/anthropicClient.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index f0ed36d..b57dfdc 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -17,10 +17,14 @@ import { AnthropicRequest, AnthropicResponse, ModelInfo, ModelsListResponse } fr */ export class AnthropicClient { private apiKey: string; + /** Anthropic API base URL - centralized to avoid drift */ + private readonly API_BASE = 'https://api.anthropic.com/v1'; + /** Anthropic API version - centralized for consistency across all requests */ + private readonly API_VERSION = '2023-06-01'; /** Base URL for the Anthropic Messages API endpoint */ - private messagesUrl = 'https://api.anthropic.com/v1/messages'; + private messagesUrl = `${this.API_BASE}/messages`; /** Base URL for the Anthropic Models API endpoint */ - private modelsUrl = 'https://api.anthropic.com/v1/models'; + private modelsUrl = `${this.API_BASE}/models`; /** * Suffix appended to all system prompts to enforce consistent output format. @@ -147,7 +151,7 @@ export class AnthropicClient { method: 'GET', headers: { 'x-api-key': this.apiKey, - 'anthropic-version': '2023-06-01' + 'anthropic-version': this.API_VERSION } }); @@ -244,7 +248,7 @@ export class AnthropicClient { headers: { 'Content-Type': 'application/json', 'x-api-key': this.apiKey, - 'anthropic-version': '2023-06-01' + 'anthropic-version': this.API_VERSION }, body: JSON.stringify(request) }); @@ -375,8 +379,10 @@ export class AnthropicClient { // Validate that the assistant actually returned "ping" // This ensures the API is working correctly, not just returning a 2xx status + // Normalize to tolerate punctuation and quotes (e.g., "ping.", ""ping"") const returnedText = (response.content?.[0]?.text || '').trim().toLowerCase(); - const isValid = returnedText === 'ping'; + const normalized = returnedText.replace(/^[^a-z]+|[^a-z]+$/g, '').replace(/\s+/g, ''); + const isValid = normalized === 'ping'; return { success: isValid, -- 2.36.6 From ea14071d229ae674202088f3542d3fe319184308 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:51:35 +0200 Subject: [PATCH 45/60] Improves notification duration calculation for timed prompts Refines notification display timing logic to prevent flickering and ensure smoother user experience Adjusts notification duration calculation for short delays, using a more nuanced approach that: - Caps notification time at 900ms or delay-100ms for very short intervals - Maintains existing behavior for longer delays --- commands/timedPrompts.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index b807a0f..849f1d8 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -177,9 +177,10 @@ export class TimedPromptsCommand { const totalPrompts = this.promptQueue.length; // Calculate notification duration: slightly less than delay to avoid overlap - // For very short delays (<=1s), cap at 500ms; otherwise end 500ms before next tick + // For very short delays (<=1s), use 900ms or delay-100ms (whichever is smaller) + // to prevent flicker; otherwise end 500ms before next tick const delayMs = delaySeconds * 1000; - const notificationDuration = delayMs > 1000 ? (delayMs - 500) : 500; + const notificationDuration = delayMs > 1000 ? (delayMs - 500) : Math.min(900, delayMs - 100); const notice = new Notice( `Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`, -- 2.36.6 From 902d2b1b9ae03207e7c05253916f500ad98bb447 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:53:06 +0200 Subject: [PATCH 46/60] Refines Anthropic model type and list definitions Updates model type to use ModelId type for stronger type safety Improves hardcoded model list with TODO for keeping it current Removes outdated comments and simplifies model list annotations Prepares for more dynamic model handling with explicit update guidance --- types.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/types.ts b/types.ts index 32dfd64..0f931ba 100644 --- a/types.ts +++ b/types.ts @@ -56,7 +56,7 @@ export interface AnthropicMessage { */ export interface AnthropicRequest { /** Model identifier (e.g., 'claude-3-5-haiku-latest') */ - model: string; + model: ModelId; /** Maximum number of tokens to generate in the response */ max_tokens: number; /** Array of conversation messages between user and assistant */ @@ -153,20 +153,18 @@ export interface ModelCache { /** * Hardcoded fallback list of known Claude models. * Used when the Models API is unavailable or the API key is not configured. - * This list should be updated periodically as new models are released. * - * Organized by family (newest to oldest): - * - Sonnet 4.5 (latest, released Sept 29, 2025) - * - Haiku 4.5 (released Oct 1, 2025) - * - Opus 4.1 (released Aug 5, 2025) - * - Legacy models (Sonnet 4, 3.7, Opus 4, Haiku 3.5, Haiku 3) + * TODO: Keep this list updated with current models from: + * https://docs.anthropic.com/en/docs/about-claude/models + * + * Prefer "-latest" aliases where available for automatic updates. */ export const ANTHROPIC_MODELS = [ - // Current Models (using -latest aliases for stability) + // Current generation models (use -latest aliases where available) 'claude-sonnet-4-5-20250929', 'claude-haiku-4-5-20251001', 'claude-opus-4-1-20250805', - // Legacy Models + // Legacy models 'claude-sonnet-4-20250514', 'claude-3-7-sonnet-latest', 'claude-opus-4-20250514', -- 2.36.6 From b57fe8cd8945a7063f38fe388faf71238b48be1e Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:55:05 +0200 Subject: [PATCH 47/60] Adds deduplication for concurrent prompt generation Prevents duplicate API calls by tracking in-flight requests Ensures consistent prompt generation under high concurrency Mitigates potential race conditions in prompt retrieval Improves performance and reliability of prompt generation service --- services/promptGenerator.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/services/promptGenerator.ts b/services/promptGenerator.ts index 46ae7da..6cb3e96 100644 --- a/services/promptGenerator.ts +++ b/services/promptGenerator.ts @@ -24,6 +24,8 @@ export class PromptGeneratorService { private client: AnthropicClient; /** In-memory cache mapping request parameters to generated prompts */ private cache: Map = new Map(); + /** In-flight requests to prevent duplicate concurrent API calls */ + private inFlight: Map> = new Map(); /** Cache expiry time in milliseconds (10 minutes) */ private readonly cacheExpiryMs = 10 * 60 * 1000; // 10 minutes @@ -153,9 +155,17 @@ export class PromptGeneratorService { return cachedPrompts.map(p => p.text); } + // Deduplicate concurrent requests with identical parameters + const existing = this.inFlight.get(cacheKey); + if (existing) { + return existing; + } + try { new Notice('Generating prompts...'); - let prompts = await this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type); + const pending = this.client.generatePrompts(count, model, systemPrompt, examplePrompt, type); + this.inFlight.set(cacheKey, pending); + let prompts = await pending; // Enforce requested count - models can occasionally over-generate // This ensures deterministic UX and correct cache key matching @@ -180,6 +190,8 @@ export class PromptGeneratorService { new Notice('Unknown error occurred while generating prompts'); } throw error; + } finally { + this.inFlight.delete(cacheKey); } } -- 2.36.6 From 3f53bb5a309be43a8e01f420888a19285fb128b7 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 16:56:38 +0200 Subject: [PATCH 48/60] Improves model list pagination with safety measures Adds robust pagination handling for Anthropic model retrieval: - Implements duplicate model filtering - Adds iteration limit to prevent infinite loops - Introduces cursor advancement validation - Fixes potential API pagination edge cases Ensures more reliable and predictable model list retrieval --- api/anthropicClient.ts | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index b57dfdc..43a1983 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -130,19 +130,30 @@ export class AnthropicClient { try { // Accumulate all models across pages const allModels: ModelInfo[] = []; + // Track seen model IDs to filter duplicates + const seenIds = new Set(); let hasMore = true; let afterId: string | undefined = undefined; let firstId = ''; let lastId = ''; + // Loop safety: prevent runaway pagination + let iterations = 0; + const maxIterations = 1000; - // Fetch all pages + // Fetch all pages with safety guards while (hasMore) { + // Guard against infinite loops + iterations++; + if (iterations > maxIterations) { + throw new Error(`Pagination exceeded maximum iterations (${maxIterations}). Possible API issue.`); + } + // Build URL with pagination parameters // Use limit=1000 (Anthropic's max) to minimize round trips const params = new URLSearchParams(); params.set('limit', '1000'); if (afterId) { - params.set('after', afterId); + params.set('after_id', afterId); } const url = `${this.modelsUrl}?${params.toString()}`; @@ -175,8 +186,13 @@ export class AnthropicClient { const pageResponse = data as ModelsListResponse; - // Accumulate models from this page - allModels.push(...pageResponse.data); + // Accumulate models from this page, filtering out duplicates + for (const model of pageResponse.data) { + if (!seenIds.has(model.id)) { + seenIds.add(model.id); + allModels.push(model); + } + } // Store first_id from the first page if (!firstId) { @@ -184,9 +200,17 @@ export class AnthropicClient { } // Update pagination state + const previousAfterId: string | undefined = afterId; lastId = pageResponse.last_id; hasMore = pageResponse.has_more; + // Guard against cursor not advancing (would cause infinite loop) + if (!lastId || lastId === previousAfterId) { + // Cursor didn't advance - break to prevent infinite loop + console.warn('Pagination cursor did not advance. Stopping pagination.'); + break; + } + // Set up for next iteration if (hasMore) { afterId = lastId; -- 2.36.6 From 4c03bed948abbf8269c56f5eabe8e3ded6406b03 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 25 Oct 2025 10:44:53 +0200 Subject: [PATCH 49/60] Refactors model fetching with deduplication strategy Extracts common model fetching logic into shared method to prevent duplicate API calls Improves error handling and caching for model retrieval by: - Creating a centralized fetchWithDeduplication method - Adding model type filtering in cache update - Resetting fallback notice flag during cache clearing Enhances reliability of model list retrieval across multiple service methods --- services/modelService.ts | 102 ++++++++++++++++++++++----------------- 1 file changed, 59 insertions(+), 43 deletions(-) diff --git a/services/modelService.ts b/services/modelService.ts index d6d0db5..17cab8d 100644 --- a/services/modelService.ts +++ b/services/modelService.ts @@ -74,31 +74,8 @@ export class ModelService { return this.getFallbackModels(); } - // Try to fetch from API (deduplicate concurrent calls) - if (!this.inFlight) { - this.inFlight = (async () => { - const response = await this.anthropicClient.fetchModels(); - this.updateCache(response.data); - // Reset notice flag on successful fetch - this.hasShownFallbackNotice = false; - return this.formatModels(response.data); - })().finally(() => { - this.inFlight = null; - }); - } - - try { - return await this.inFlight; - } catch (error) { - console.error('Failed to fetch models from API:', error); - // Only show notice once per session to avoid spamming during offline periods - if (!this.hasShownFallbackNotice) { - new Notice('Could not fetch latest models from API. Using default model list.'); - this.hasShownFallbackNotice = true; - } - // Prefer stale cache over hardcoded fallback if available - return this.getStaleCacheModels() ?? this.getFallbackModels(); - } + // Use shared fetch path with deduplication + return this.fetchWithDeduplication('Could not fetch latest models from API. Using default model list.'); } /** @@ -108,6 +85,9 @@ export class ModelService { * they immediately see the correct models available for their account. * Falls back to hardcoded models if the API request fails. * + * Uses the same in-flight deduplication as getAvailableModels to prevent + * concurrent refreshModels and getAvailableModels calls from both hitting the API. + * * @returns Array of current available models */ async refreshModels(): Promise { @@ -116,22 +96,8 @@ export class ModelService { return this.getFallbackModels(); } - try { - const response = await this.anthropicClient.fetchModels(); - this.updateCache(response.data); - // Reset notice flag on successful fetch - this.hasShownFallbackNotice = false; - return this.formatModels(response.data); - } catch (error) { - console.error('Failed to refresh models from API:', error); - // Only show notice once per session to avoid spamming during repeated failures - if (!this.hasShownFallbackNotice) { - new Notice('Fetching current models failed. Using hardcoded fallback list.'); - this.hasShownFallbackNotice = true; - } - // Prefer stale cache over hardcoded fallback if available - return this.getStaleCacheModels() ?? this.getFallbackModels(); - } + // Use shared fetch path with deduplication + return this.fetchWithDeduplication('Fetching current models failed. Using hardcoded fallback list.'); } /** @@ -161,14 +127,57 @@ export class ModelService { /** * Clears the cached model list, forcing a fresh fetch on next access. * + * Also resets the fallback notice flag to allow showing error messages + * again after manual cache reset. This prevents stale "notice already shown" + * state across cache resets. + * * Useful for testing or troubleshooting cache-related issues. */ clearCache(): void { this.modelCache = null; + this.hasShownFallbackNotice = false; } // MARK: - Private Methods + /** + * Shared fetch method with in-flight deduplication. + * + * This method is used by both getAvailableModels and refreshModels to prevent + * concurrent calls from making duplicate API requests. If a fetch is already + * in progress, subsequent calls will wait for and return the same promise. + * + * @param errorNoticeMessage - Message to show user if fetch fails + * @returns Array of model options from the API or fallback + */ + private async fetchWithDeduplication(errorNoticeMessage: string): Promise { + // Try to fetch from API (deduplicate concurrent calls) + if (!this.inFlight) { + this.inFlight = (async () => { + const response = await this.anthropicClient.fetchModels(); + this.updateCache(response.data); + // Reset notice flag on successful fetch + this.hasShownFallbackNotice = false; + return this.formatModels(response.data); + })().finally(() => { + this.inFlight = null; + }); + } + + try { + return await this.inFlight; + } catch (error) { + console.error('Failed to fetch models from API:', error); + // Only show notice once per session to avoid spamming + if (!this.hasShownFallbackNotice) { + new Notice(errorNoticeMessage); + this.hasShownFallbackNotice = true; + } + // Prefer stale cache over hardcoded fallback if available + return this.getStaleCacheModels() ?? this.getFallbackModels(); + } + } + /** * Checks whether the current cache is still valid based on TTL. * @@ -208,15 +217,22 @@ export class ModelService { * Updates the cache with freshly fetched model data. * * Deduplicates models by ID to guard against accidental duplicates - * across pagination responses. Sets the fetchedAt timestamp to now, + * across pagination responses. Filters to include only model-like entries + * (type contains "model") to exclude non-chat API entries if they appear + * in future API responses. Sets the fetchedAt timestamp to now, * starting the 24-hour TTL countdown. * * @param models - Array of model information from the API */ private updateCache(models: ModelInfo[]): void { - // Deduplicate by id using Map + // Deduplicate by id using Map and filter to model-like entries only const byId = new Map(); for (const model of models) { + // Filter out non-model entries (e.g., if API starts returning other types) + // Keep entries where type contains "model" (case-insensitive) + if (model.type && !/model/i.test(model.type)) { + continue; + } byId.set(model.id, model); } -- 2.36.6 From 1c1cba6ce53ba16e3f014caea311becfd83ae455 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 25 Oct 2025 10:46:20 +0200 Subject: [PATCH 50/60] Enhances model selection and caching in settings Improves model dropdown handling with debounced settings save Adds model list cache clearing functionality Handles edge cases for model availability and selection Introduces more robust error handling for model dropdowns Provides user control over model list refreshing --- settings.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/settings.ts b/settings.ts index bbd4650..d876d6e 100644 --- a/settings.ts +++ b/settings.ts @@ -176,9 +176,9 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { if (this.availableModels.length > 0) { dropdown.setValue(this.plugin.settings.model); } - dropdown.onChange(async (value) => { + dropdown.onChange((value) => { this.plugin.settings.model = value; - await this.plugin.saveSettings(); + this.debounceSaveSettings(); }); }); @@ -292,6 +292,18 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { const notice = new Notice('Cache cleared'); setTimeout(() => notice.hide(), 2000); })); + + new Setting(containerEl) + .setName('Clear Model List Cache') + .setDesc('Clear cached Claude model list to force a fresh fetch from the API') + .addButton(button => button + .setButtonText('Clear Models Cache') + .onClick(() => { + this.plugin.modelService.clearCache(); + // Show a temporary notice + const notice = new Notice('Model list cache cleared'); + setTimeout(() => notice.hide(), 2000); + })); } // MARK: - Model Loading @@ -338,7 +350,12 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { } else { // Fall back to first available model if current one is gone const fallbackModel = this.availableModels[0]; - if (fallbackModel && this.plugin.settings.model !== fallbackModel.id) { + if (!fallbackModel) { + // Edge case: both API and fallback returned empty + this.modelDropdown.setDisabled(true); + this.modelDropdown.selectEl.empty(); + this.modelDropdown.addOption('', 'No models available'); + } else if (this.plugin.settings.model !== fallbackModel.id) { this.modelDropdown.setValue(fallbackModel.id); this.plugin.settings.model = fallbackModel.id; await this.plugin.saveSettings(); -- 2.36.6 From 2b9c8fbc5b0d519ab1436369849e1fe44039bfe7 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 25 Oct 2025 10:47:04 +0200 Subject: [PATCH 51/60] Prevents cross-key model cache leakage Clears model cache when API key changes to ensure accurate model list access Prevents potential issues with stale model entitlements when switching API keys programmatically --- main.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/main.ts b/main.ts index 06039b2..528f30a 100644 --- a/main.ts +++ b/main.ts @@ -135,6 +135,9 @@ export default class FreewritingPromptsPlugin extends Plugin { if (this.promptGenerator && this.lastApiKey !== this.settings.apiKey) { this.promptGenerator.updateApiKey(this.settings.apiKey); this.lastApiKey = this.settings.apiKey; + // Clear model cache to ensure model list reflects new account entitlements + // This prevents cross-key cache leakage if settings are changed programmatically + this.modelService?.clearCache(); } } -- 2.36.6 From fca191b850fc175896d5780415499dae9a116721 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 25 Oct 2025 10:48:02 +0200 Subject: [PATCH 52/60] Simplifies note prompt selection and timestamp formatting Refactors cursor handling to use setCursor instead of setSelection when collapsing selections Improves timestamp generation by using environment's default locale automatically instead of manually specifying language Enhances code clarity and simplifies locale handling for timestamp formatting --- commands/notePrompts.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index d703d42..2bbd3d8 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -98,7 +98,7 @@ export class NotePromptsCommand { const to = editor.getCursor('to'); const hasSelection = from.line !== to.line || from.ch !== to.ch; if (hasSelection) { - editor.setSelection(from, from); + editor.setCursor(from); } const cursor = editor.getCursor(); // refreshed after collapse const currentLine = editor.getLine(cursor.line) ?? ''; @@ -146,9 +146,8 @@ export class NotePromptsCommand { * @returns Formatted markdown string ready for insertion */ private formatPrompts(prompts: string[]): string { - // Use user's locale for timestamp formatting to respect regional preferences - const locale = navigator?.language ?? 'en-US'; - const timestamp = new Intl.DateTimeFormat(locale, { + // Let Intl pick the default environment locale automatically + const timestamp = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric', -- 2.36.6 From fc04d3f1af2e53427a2519950108591604b4db1e Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 25 Oct 2025 10:49:01 +0200 Subject: [PATCH 53/60] Improves model listing and prompt parsing logic Adds sorting for model dropdown to ensure consistent user experience across sessions Enhances prompt extraction by supporting more list prefix formats, improving robustness of text parsing --- api/anthropicClient.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 43a1983..a800984 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -217,9 +217,14 @@ export class AnthropicClient { } } + // Sort models for stable dropdown UX across sessions/pages + const sorted = allModels.slice().sort((a, b) => + (a.display_name ?? a.id).localeCompare(b.display_name ?? b.id) + ); + // Return combined response with all models return { - data: allModels, + data: sorted, first_id: firstId, has_more: false, // We've fetched all pages last_id: lastId @@ -320,8 +325,8 @@ export class AnthropicClient { const prompts: string[] = []; for (const line of lines) { - // Remove numbering (1., 2., etc.) and clean up the prompt - const cleaned = line.replace(/^\d+\.\s*/, '').trim(); + // Remove list prefixes: numbered (1., 1)), bullets (-, *, •) + const cleaned = line.replace(/^\s*(?:\d+[.)]|[-*•])\s*/, '').trim(); if (cleaned.length > 0) { prompts.push(cleaned); } -- 2.36.6 From d31cec03834e9df8929a688fea4b678d344eeefd Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 25 Oct 2025 10:49:40 +0200 Subject: [PATCH 54/60] Improves prompt notification duration calculation Enhances notification display logic to prevent flicker and ensure minimum visibility - Adds floor of 0 for delay milliseconds to prevent negative values - Ensures minimum notification duration of 300ms to improve user experience - Maintains existing logic for longer delay times --- commands/timedPrompts.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index 849f1d8..c7593dc 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -178,9 +178,10 @@ export class TimedPromptsCommand { // Calculate notification duration: slightly less than delay to avoid overlap // For very short delays (<=1s), use 900ms or delay-100ms (whichever is smaller) - // to prevent flicker; otherwise end 500ms before next tick - const delayMs = delaySeconds * 1000; - const notificationDuration = delayMs > 1000 ? (delayMs - 500) : Math.min(900, delayMs - 100); + // Clamp to minimum 300ms to prevent flicker/invisible notices + const delayMs = Math.max(0, delaySeconds * 1000); + const notificationDuration = + delayMs > 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100)); const notice = new Notice( `Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`, -- 2.36.6 From d5af2a08ce041fbc0bb376b0d958733c31f0c48f Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 31 Oct 2025 13:17:36 +0100 Subject: [PATCH 55/60] Improves ping response validation robustness Enhances API ping check to handle multiple text content blocks Modifies response text extraction to: - Process all text content blocks - Support multiple text segments - Normalize and validate ping response more comprehensively Increases reliability of API connection verification --- api/anthropicClient.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index a800984..02601c6 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -408,8 +408,14 @@ export class AnthropicClient { // Validate that the assistant actually returned "ping" // This ensures the API is working correctly, not just returning a 2xx status + // Check all content blocks (not just first) in case of multiple text blocks // Normalize to tolerate punctuation and quotes (e.g., "ping.", ""ping"") - const returnedText = (response.content?.[0]?.text || '').trim().toLowerCase(); + const returnedText = (response.content || []) + .filter(c => c && c.type === 'text' && typeof c.text === 'string') + .map(c => c.text) + .join(' ') + .trim() + .toLowerCase(); const normalized = returnedText.replace(/^[^a-z]+|[^a-z]+$/g, '').replace(/\s+/g, ''); const isValid = normalized === 'ping'; -- 2.36.6 From bdb4949c1b2532ff1c15f5410ffcae8a9e72c092 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 31 Oct 2025 13:19:28 +0100 Subject: [PATCH 56/60] Adds input constraints to settings numeric fields Improves user input validation for settings by: - Adding min/max range limits to numeric settings - Enforcing input type as number for better UX - Ensures settings inputs have appropriate constraints Validates timed count, delay, and note prompt settings with specific numeric ranges --- settings.ts | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/settings.ts b/settings.ts index d876d6e..c379f63 100644 --- a/settings.ts +++ b/settings.ts @@ -201,7 +201,16 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin.settings.timedCount = count; await this.plugin.saveSettings(); } - })); + })) + .then(setting => { + const input = setting.controlEl.querySelector('input'); + if (input) { + input.setAttribute('type', 'number'); + input.setAttribute('min', '1'); + input.setAttribute('max', '50'); + input.setAttribute('step', '1'); + } + }); new Setting(containerEl) .setName('Delay Between Prompts') @@ -215,7 +224,16 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin.settings.delaySeconds = delay; await this.plugin.saveSettings(); } - })); + })) + .then(setting => { + const input = setting.controlEl.querySelector('input'); + if (input) { + input.setAttribute('type', 'number'); + input.setAttribute('min', '1'); + input.setAttribute('max', '300'); + input.setAttribute('step', '1'); + } + }); new Setting(containerEl) .setName('Note Prompts Count') @@ -229,7 +247,16 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin.settings.noteCount = count; await this.plugin.saveSettings(); } - })); + })) + .then(setting => { + const input = setting.controlEl.querySelector('input'); + if (input) { + input.setAttribute('type', 'number'); + input.setAttribute('min', '1'); + input.setAttribute('max', '20'); + input.setAttribute('step', '1'); + } + }); // MARK: - Prompt Customization @@ -303,6 +330,8 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { // Show a temporary notice const notice = new Notice('Model list cache cleared'); setTimeout(() => notice.hide(), 2000); + // Persist the cleared cache so it doesn't restore on restart + void this.plugin.saveSettings(); })); } -- 2.36.6 From 9ee37cd08732068f56b2f283809c15dc6fe9508a Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 31 Oct 2025 13:20:31 +0100 Subject: [PATCH 57/60] Sanitizes writing prompts for consistent formatting Prevents potential formatting issues by ensuring prompts are single-line and trimmed Collapses multiple whitespaces and trims prompt text to maintain clean, uniform list rendering in markdown output --- commands/notePrompts.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/commands/notePrompts.ts b/commands/notePrompts.ts index 2bbd3d8..b7fe991 100644 --- a/commands/notePrompts.ts +++ b/commands/notePrompts.ts @@ -158,7 +158,10 @@ export class NotePromptsCommand { let formatted = `## Writing Prompts (${timestamp})\n\n`; prompts.forEach((prompt, index) => { - formatted += `${index + 1}. ${prompt}\n\n`; + // Sanitize to single line: collapse whitespace and trim + // Prevents malformed prompts with newlines from breaking list formatting + const oneLine = String(prompt).replace(/\s+/g, ' ').trim(); + formatted += `${index + 1}. ${oneLine}\n\n`; }); return formatted; -- 2.36.6 From 9b8ff3181aba03386174722e9d2e87e8171ce1f7 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 31 Oct 2025 13:21:00 +0100 Subject: [PATCH 58/60] Refines notification timing for timed prompts Adjusts notification display duration calculation for more predictable behavior Improves timing logic for prompts with different delay intervals: - Ensures notifications end 500ms before next tick for delays >1s - Maintains minimum 300ms display time to prevent flickering - Keeps existing logic for short delay intervals --- commands/timedPrompts.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index c7593dc..d7135bc 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -177,11 +177,12 @@ export class TimedPromptsCommand { const totalPrompts = this.promptQueue.length; // Calculate notification duration: slightly less than delay to avoid overlap - // For very short delays (<=1s), use 900ms or delay-100ms (whichever is smaller) + // For delays >1s, end 500ms before next tick + // For delays <=1s, use 900ms or delay-100ms (whichever is smaller) // Clamp to minimum 300ms to prevent flicker/invisible notices const delayMs = Math.max(0, delaySeconds * 1000); const notificationDuration = - delayMs > 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100)); + delayMs >= 1000 ? (delayMs - 500) : Math.max(300, Math.min(900, delayMs - 100)); const notice = new Notice( `Writing Prompt ${promptNumber}/${totalPrompts}:\n\n${prompt}`, -- 2.36.6 From 5bf804b266c73e6cdc01adc0822b5a6b262e2bf4 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 31 Oct 2025 13:35:49 +0100 Subject: [PATCH 59/60] Fixes pagination ID consistency in model sorting Recomputes pagination first and last IDs after sorting models to ensure consistent ID references match the sorted array order. Prevents potential misalignment between sorted model list and pagination metadata --- api/anthropicClient.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 02601c6..597b51c 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -222,12 +222,17 @@ export class AnthropicClient { (a.display_name ?? a.id).localeCompare(b.display_name ?? b.id) ); + // Recompute pagination IDs from sorted array to maintain consistency + // with returned data (original IDs were from unsorted API responses) + const sortedFirstId = sorted.length > 0 ? sorted[0].id : firstId; + const sortedLastId = sorted.length > 0 ? sorted[sorted.length - 1].id : lastId; + // Return combined response with all models return { data: sorted, - first_id: firstId, + first_id: sortedFirstId, has_more: false, // We've fetched all pages - last_id: lastId + last_id: sortedLastId }; } catch (error) { if (error instanceof Error) { -- 2.36.6 From 4cb2308bd62772f50fc8e7171c2492babbea0870 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 31 Oct 2025 13:36:03 +0100 Subject: [PATCH 60/60] Refines timed prompt notification duration logic Adjusts notification duration calculation to improve timing precision for different delay intervals Ensures consistent minimum notification display time while preventing potential overlap or flickering --- commands/timedPrompts.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/commands/timedPrompts.ts b/commands/timedPrompts.ts index d7135bc..00abc1c 100644 --- a/commands/timedPrompts.ts +++ b/commands/timedPrompts.ts @@ -177,8 +177,8 @@ export class TimedPromptsCommand { const totalPrompts = this.promptQueue.length; // Calculate notification duration: slightly less than delay to avoid overlap - // For delays >1s, end 500ms before next tick - // For delays <=1s, use 900ms or delay-100ms (whichever is smaller) + // For delays >=1s, end 500ms before next tick + // For delays <1s, use 900ms or delay-100ms (whichever is smaller) // Clamp to minimum 300ms to prevent flicker/invisible notices const delayMs = Math.max(0, delaySeconds * 1000); const notificationDuration = -- 2.36.6