Enhances code documentation and structure for plugin
Adds comprehensive documentation for all major classes and methods in the Freewriting Cleanup plugin Improves code readability by: - Adding detailed JSDoc comments explaining purpose and functionality - Clarifying method behaviors and input/output expectations - Providing inline context for complex operations Standardizes error handling and adds more robust validation across services
This commit is contained in:
7 files changed
+584
-24
No files matched your search
@@ -5,20 +5,47 @@ import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
||||
|
||||
/**
|
||||
* Service for orchestrating text cleanup operations
|
||||
*
|
||||
* Coordinates validation, API requests, and result formatting for freewriting
|
||||
* cleanup. Acts as the main business logic layer between the command layer
|
||||
* and the API client.
|
||||
*/
|
||||
export class CleanupService {
|
||||
private client: AnthropicClient;
|
||||
|
||||
// Expose client for ModelService
|
||||
/**
|
||||
* Exposes the Anthropic client for ModelService
|
||||
*
|
||||
* @returns The underlying Anthropic API client
|
||||
*/
|
||||
get anthropicClient(): AnthropicClient {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new cleanup service
|
||||
*
|
||||
* @param apiKey - Anthropic API key for authentication
|
||||
*/
|
||||
constructor(apiKey: string) {
|
||||
this.client = new AnthropicClient(apiKey);
|
||||
}
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
/**
|
||||
* Cleans up freewriting text using Claude AI
|
||||
*
|
||||
* Validates input text, makes API request through client, and returns
|
||||
* structured result with metadata. Shows user notices for timing feedback.
|
||||
*
|
||||
* @param text - The freewriting text to clean up
|
||||
* @param settings - Plugin settings including model, prompts, and commentary options
|
||||
* @returns Cleanup result with original text, cleaned text, optional commentary, and usage stats
|
||||
* @throws Error if text is empty, too long, API key is invalid, or API request fails
|
||||
*/
|
||||
async cleanupText(text: string, settings: FreewritingCleanupSettings): Promise<CleanupResult> {
|
||||
// Validate input
|
||||
if (!text || text.trim().length === 0) {
|
||||
@@ -69,6 +96,15 @@ export class CleanupService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the API connection using current settings
|
||||
*
|
||||
* Validates API key and makes a test request to verify connectivity.
|
||||
* Returns detailed result for user feedback in settings UI.
|
||||
*
|
||||
* @param settings - Plugin settings containing API key and model
|
||||
* @returns Test result with success status, message, and optional timing details
|
||||
*/
|
||||
async testConnection(settings: FreewritingCleanupSettings): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
@@ -97,6 +133,15 @@ export class CleanupService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats cleanup result for insertion into editor
|
||||
*
|
||||
* Creates markdown-formatted output with separators between sections.
|
||||
* Includes cleaned text and optional commentary section.
|
||||
*
|
||||
* @param result - Cleanup result to format
|
||||
* @returns Formatted string ready for editor insertion
|
||||
*/
|
||||
formatCleanupResult(result: CleanupResult): string {
|
||||
let formatted = `\n\n---\n\nAI Cleanup:\n\n${result.cleanedText}`;
|
||||
|
||||
@@ -109,10 +154,27 @@ export class CleanupService {
|
||||
|
||||
// MARK: - Configuration Methods
|
||||
|
||||
/**
|
||||
* Updates the API key used by the underlying client
|
||||
*
|
||||
* Called when user changes API key in settings to update the client
|
||||
* without recreating the service instance.
|
||||
*
|
||||
* @param apiKey - New Anthropic API key
|
||||
*/
|
||||
updateApiKey(apiKey: string): void {
|
||||
this.client.updateApiKey(apiKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates plugin settings for completeness
|
||||
*
|
||||
* Checks that all required settings are present and valid. Used to
|
||||
* provide user feedback before attempting operations.
|
||||
*
|
||||
* @param settings - Plugin settings to validate
|
||||
* @returns Validation result with boolean flag and list of errors
|
||||
*/
|
||||
validateSettings(settings: FreewritingCleanupSettings): {
|
||||
isValid: boolean;
|
||||
errors: string[];
|
||||
@@ -139,15 +201,39 @@ export class CleanupService {
|
||||
|
||||
// MARK: - Utility Methods
|
||||
|
||||
/**
|
||||
* Gets the character count of text
|
||||
*
|
||||
* @param text - Text to count characters in
|
||||
* @returns Number of characters
|
||||
*/
|
||||
static getCharacterCount(text: string): number {
|
||||
return text.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimates token count from character count
|
||||
*
|
||||
* Uses rough approximation of 1 token per 4 characters for English text.
|
||||
* This is used for user feedback before making API requests.
|
||||
*
|
||||
* @param text - Text to estimate tokens for
|
||||
* @returns Estimated token count
|
||||
*/
|
||||
static estimateTokenCount(text: string): number {
|
||||
// Rough estimation: 1 token ≈ 4 characters for English text
|
||||
return Math.ceil(text.length / 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if text is within API limits
|
||||
*
|
||||
* Validates text against both character and token limits defined by
|
||||
* Anthropic API. Returns detailed information for user feedback.
|
||||
*
|
||||
* @param text - Text to validate
|
||||
* @returns Object with limit validation flags and counts
|
||||
*/
|
||||
static isWithinLimits(text: string): {
|
||||
withinCharacterLimit: boolean;
|
||||
withinTokenLimit: boolean;
|
||||
|
||||
+79
-16
@@ -5,16 +5,34 @@ import { Notice } from 'obsidian';
|
||||
import { AnthropicClient } from '../api/anthropicClient';
|
||||
import { ModelInfo, ModelCache, ANTHROPIC_MODELS } from '../types';
|
||||
|
||||
/**
|
||||
* Simplified model option for UI display
|
||||
*/
|
||||
export interface ModelOption {
|
||||
/** Model identifier used in API requests */
|
||||
id: string;
|
||||
/** User-friendly display name for dropdowns */
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for managing available Claude models
|
||||
*
|
||||
* Fetches model lists from the Anthropic API with 24-hour caching to minimize
|
||||
* API calls. Falls back to hardcoded model list when API is unavailable or
|
||||
* API key is not configured. This implementation ensures the UI always has
|
||||
* model options available even during offline use or before API key setup.
|
||||
*/
|
||||
export class ModelService {
|
||||
private anthropicClient: AnthropicClient;
|
||||
private modelCache: ModelCache | null = null;
|
||||
private readonly CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
/**
|
||||
* Creates a new model service
|
||||
*
|
||||
* @param anthropicClient - Anthropic API client for fetching models
|
||||
*/
|
||||
constructor(anthropicClient: AnthropicClient) {
|
||||
this.anthropicClient = anthropicClient;
|
||||
}
|
||||
@@ -22,9 +40,14 @@ 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 or API key is missing
|
||||
* Gets available models with caching and fallback logic
|
||||
*
|
||||
* Returns models from cache if valid (< 24 hours old), otherwise fetches
|
||||
* fresh data from the API. Automatically falls back to hardcoded model list
|
||||
* if API key is missing or API request fails. This ensures the settings UI
|
||||
* always has model options available.
|
||||
*
|
||||
* @returns Array of model options for UI display
|
||||
*/
|
||||
async getAvailableModels(): Promise<ModelOption[]> {
|
||||
// Check if we have a valid cache
|
||||
@@ -66,8 +89,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
|
||||
*
|
||||
* Bypasses cache and fetches fresh model data from Anthropic. Used when
|
||||
* the user changes their API key or manually requests a refresh. Falls back
|
||||
* to hardcoded models if the API is unavailable.
|
||||
*
|
||||
* @returns Array of model options for UI display
|
||||
*/
|
||||
async refreshModels(): Promise<ModelOption[]> {
|
||||
// If no API key, immediately return and cache fallback
|
||||
@@ -103,29 +131,43 @@ export class ModelService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cache from plugin data
|
||||
* Loads model cache from plugin data
|
||||
*
|
||||
* Restores previously cached model data when the plugin initializes.
|
||||
* This allows the plugin to avoid an API call on startup if cache is
|
||||
* still valid.
|
||||
*
|
||||
* @param cache - Cached model data from plugin storage
|
||||
*/
|
||||
loadCache(cache: ModelCache | null): void {
|
||||
this.modelCache = cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current cache for saving to plugin data
|
||||
* Gets current cache for persisting to plugin data
|
||||
*
|
||||
* @returns Current model cache or null if no cache exists
|
||||
*/
|
||||
getCache(): ModelCache | null {
|
||||
return this.modelCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cache (for testing or manual refresh)
|
||||
* Clears the cache to force fresh fetch on next request
|
||||
*
|
||||
* Used for testing or when manual refresh is needed
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.modelCache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fallback model options (public API for UI components)
|
||||
* Returns hardcoded model list as ModelOption array
|
||||
* Gets fallback model options for UI components
|
||||
*
|
||||
* Public API that returns the hardcoded model list formatted as
|
||||
* ModelOption array. Used by settings UI when API is unavailable.
|
||||
*
|
||||
* @returns Array of hardcoded model options
|
||||
*/
|
||||
getFallbackOptions(): ModelOption[] {
|
||||
return this.getFallbackModels();
|
||||
@@ -134,7 +176,13 @@ export class ModelService {
|
||||
// MARK: - Private Methods
|
||||
|
||||
/**
|
||||
* Check if the current cache is still valid (within TTL)
|
||||
* Checks if the current cache is still valid
|
||||
*
|
||||
* Cache is considered valid if it exists and is less than 24 hours old.
|
||||
* This implementation reduces unnecessary API calls while keeping model
|
||||
* data reasonably current.
|
||||
*
|
||||
* @returns True if cache exists and is within TTL
|
||||
*/
|
||||
private isCacheValid(): boolean {
|
||||
if (!this.modelCache) {
|
||||
@@ -147,7 +195,11 @@ export class ModelService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Update cache with new model data
|
||||
* Updates cache with new model data
|
||||
*
|
||||
* Stores fetched models along with current timestamp for TTL tracking.
|
||||
*
|
||||
* @param models - Array of model information from API
|
||||
*/
|
||||
private updateCache(models: ModelInfo[]): void {
|
||||
this.modelCache = {
|
||||
@@ -157,9 +209,14 @@ export class ModelService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Format ModelInfo array to ModelOption array for dropdown
|
||||
* Uses display_name from API for user-friendly model names
|
||||
* Sorted by displayName for consistent UX across cache/API ordering
|
||||
* Formats ModelInfo array to ModelOption array for dropdowns
|
||||
*
|
||||
* Converts API model data to simplified format for UI display. Uses
|
||||
* display_name from API for user-friendly model names. Results are
|
||||
* sorted alphabetically for consistent UX regardless of API ordering.
|
||||
*
|
||||
* @param models - Array of model information from API
|
||||
* @returns Formatted and sorted model options
|
||||
*/
|
||||
private formatModels(models: ModelInfo[]): ModelOption[] {
|
||||
return models
|
||||
@@ -171,7 +228,13 @@ export class ModelService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fallback models from hardcoded list
|
||||
* Gets fallback models from hardcoded list
|
||||
*
|
||||
* Returns the static model list defined in types.ts, formatted as
|
||||
* ModelOption array. Used when API is unavailable or before API key
|
||||
* is configured.
|
||||
*
|
||||
* @returns Array of hardcoded model options
|
||||
*/
|
||||
private getFallbackModels(): ModelOption[] {
|
||||
return ANTHROPIC_MODELS.map(id => ({
|
||||
|
||||
Reference in new issue
Block a user