UNPKG

extended-dynamic-forms

Version:

Extended React JSON Schema Form (RJSF) v6 with custom components, widgets, templates, layouts, and form events

261 lines (259 loc) 8.36 kB
import { ChoiceOption, LoadingState, ErrorState, CacheConfig, ChoiceDataProvider } from '../ChoiceWidget.types'; /** * Retry configuration for handling failed requests */ export interface RetryConfig { /** Maximum number of retry attempts (default: 3) */ maxAttempts: number; /** Base delay between retries in milliseconds (default: 1000) */ baseDelayMs: number; /** Maximum delay between retries in milliseconds (default: 10000) */ maxDelayMs: number; /** Backoff multiplier for exponential backoff (default: 2) */ backoffMultiplier: number; /** Whether to add jitter to retry delays (default: true) */ jitter: boolean; } /** * Default retry configuration */ export declare const DEFAULT_RETRY_CONFIG: RetryConfig; /** * Performance metrics for monitoring data source operations */ export interface DataSourceMetrics { /** Total number of requests made */ requestCount: number; /** Number of successful requests */ successCount: number; /** Number of failed requests */ errorCount: number; /** Number of cache hits */ cacheHitCount: number; /** Number of cache misses */ cacheMissCount: number; /** Average response time in milliseconds */ averageResponseTimeMs: number; /** Last request timestamp */ lastRequestTimestamp?: number; /** Last error timestamp */ lastErrorTimestamp?: number; } /** * Event callbacks for data source operations */ export interface DataSourceEventCallbacks { /** Called when data loading starts */ onLoadingStart?: (provider: DataSourceProvider) => void; /** Called when data loading completes successfully */ onLoadingComplete?: (provider: DataSourceProvider, data: ChoiceOption[]) => void; /** Called when an error occurs */ onError?: (provider: DataSourceProvider, error: Error) => void; /** Called when cache is hit */ onCacheHit?: (provider: DataSourceProvider, key: string) => void; /** Called when cache is missed */ onCacheMiss?: (provider: DataSourceProvider, key: string) => void; /** Called when cache is cleared */ onCacheCleared?: (provider: DataSourceProvider, key?: string) => void; } /** * Abstract base class for data source providers * * Provides common functionality for all data source implementations including: * - Caching with configurable TTL * - Loading state management * - Error handling with retry logic * - Performance metrics * - Memory-efficient cache cleanup * * @example * ```typescript * class ApiDataSourceProvider extends DataSourceProvider { * protected async fetchData(): Promise<ChoiceOption[]> { * const response = await fetch(this.config.url); * return this.mapResponse(await response.json()); * } * } * ``` */ export declare abstract class DataSourceProvider implements ChoiceDataProvider { private static memoryCache; private static cacheCleanupInterval?; private static instanceCount; protected cache: CacheConfig; protected retryConfig: RetryConfig; protected loadingState: LoadingState; protected errorState: ErrorState; protected metrics: DataSourceMetrics; protected eventCallbacks?: DataSourceEventCallbacks; protected instanceId: string; protected isDestroyed: boolean; /** * Whether this provider supports caching */ readonly supportsCaching = true; /** * Whether this provider supports real-time updates * Subclasses should override this if they support real-time updates */ readonly supportsRealTime: boolean; /** * Constructor for DataSourceProvider * * @param cacheConfig - Cache configuration options * @param retryConfig - Retry configuration options * @param eventCallbacks - Event callback functions */ constructor(cacheConfig?: Partial<CacheConfig>, retryConfig?: Partial<RetryConfig>, eventCallbacks?: DataSourceEventCallbacks); /** * Fetch options from the data source * * This is the main public method that handles caching, loading states, * error handling, and retry logic. * * @returns Promise resolving to array of choice options * @throws Error if provider is destroyed or max retries exceeded */ fetchOptions(): Promise<ChoiceOption[]>; /** * Get current loading state */ getLoadingState(): LoadingState; /** * Get current error state */ getErrorState(): ErrorState; /** * Get performance metrics */ getMetrics(): DataSourceMetrics; /** * Clear specific cache entry or all cache entries * * @param key - Cache key to clear, or undefined to clear all */ clearCache(key?: string): void; /** * Clear error state */ clearError(): void; /** * Reset metrics to initial state */ resetMetrics(): void; /** * Check if cache contains valid data for the given key * * @param key - Cache key to check * @returns true if cache contains valid data */ hasCachedData(key?: string): boolean; /** * Cleanup resources and destroy the provider * * Should be called when the provider is no longer needed * to prevent memory leaks and cleanup resources. */ cleanup(): void; /** * Fetch data from the actual data source * * Subclasses must implement this method to fetch data from their * specific data source (API, file, database, etc.) * * @returns Promise resolving to array of choice options */ protected abstract fetchData(): Promise<ChoiceOption[]>; /** * Generate a unique cache key for this data source * * Subclasses should implement this to generate a unique cache key * based on their configuration (URL, parameters, etc.) * * @returns Cache key string or null if caching should be disabled */ protected abstract getCacheKey(): string | null; /** * Cleanup subclass-specific resources * * Subclasses can override this to cleanup their specific resources * (abort controllers, event listeners, etc.) */ protected cleanupResources(): void; /** * Set loading state and notify callbacks * * @param isLoading - Whether currently loading * @param message - Optional loading message * @param progress - Optional progress percentage (0-100) */ protected setLoadingState(isLoading: boolean, message?: string, progress?: number): void; /** * Validate fetched data and transform if necessary * * @param data - Raw data to validate * @returns Validated and transformed choice options * @throws Error if data is invalid */ protected validateAndTransformData(data: ChoiceOption[]): ChoiceOption[]; /** * Log debug messages (only in development) * * @param message - Debug message to log * @param data - Optional data to include in log */ protected logDebug(message: string, data?: unknown): void; /** * Log error messages * * @param message - Error message to log * @param error - Optional error object */ protected logError(message: string, error?: Error): void; /** * Fetch data with retry logic and exponential backoff */ private fetchWithRetry; /** * Get cached data if valid */ private getCachedData; /** * Set cached data with TTL */ private setCachedData; /** * Handle errors and update error state */ private handleError; /** * Update performance metrics */ private updateMetrics; /** * Start periodic cache cleanup */ private startCacheCleanup; /** * Stop periodic cache cleanup */ private stopCacheCleanup; /** * Run cache cleanup to remove expired entries */ private runCacheCleanup; } /** * Utility function to create a simple hash for cache keys * * @param input - String to hash * @returns Simple hash string */ export declare function createSimpleHash(input: string): string; /** * Utility function to validate choice options array * * @param options - Options array to validate * @returns Validation errors or null if valid */ export declare function validateChoiceOptions(options: unknown): string[] | null;