UNPKG

extended-dynamic-forms

Version:

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

311 lines (309 loc) 8.52 kB
import { DataSourceProvider, DataSourceEventCallbacks } from './DataSourceProvider'; import { ChoiceOption, WebSocketDataSourceConfig, WebSocketMessage, CacheConfig } from '../ChoiceWidget.types'; /** * Configuration interface for WebSocketDataSource */ export interface WebSocketDataSourceOptions { /** Cache configuration (for offline support) */ cache?: Partial<CacheConfig>; /** Event callbacks for monitoring operations */ eventCallbacks?: DataSourceEventCallbacks; } /** * Connection states for WebSocket */ export declare enum WebSocketConnectionState { DISCONNECTED = "disconnected", CONNECTING = "connecting", CONNECTED = "connected", RECONNECTING = "reconnecting", FAILED = "failed" } /** * WebSocket data source provider for real-time option updates * * Provides real-time data synchronization through WebSocket connections. * Supports automatic reconnection, heartbeat monitoring, and offline caching. * * Key features: * - Real-time option updates from server * - Automatic reconnection with exponential backoff * - Heartbeat monitoring for connection health * - Request-response pattern with message correlation * - Search request debouncing * - Offline cache for resilience * - Authentication support (Bearer, Query, Header) * * @example Basic usage: * ```typescript * const config: WebSocketDataSourceConfig = { * type: 'websocket', * url: 'ws://localhost:8080/choices', * auth: { * type: 'bearer', * credentials: 'your-token' * } * }; * * const provider = new WebSocketDataSource(config); * const options = await provider.fetchOptions(); * ``` * * @example Real-time search: * ```typescript * const config: WebSocketDataSourceConfig = { * type: 'websocket', * url: 'ws://localhost:8080/choices', * messageHandling: { * enableRealtimeSearch: true, * searchDebounceMs: 300 * } * }; * * const provider = new WebSocketDataSource(config); * provider.setSearchParams({ search: 'query' }); * const results = await provider.fetchOptions(); * ``` */ export declare class WebSocketDataSource extends DataSourceProvider { private readonly config; private websocket; private connectionState; private reconnectAttempts; private heartbeatInterval; private responseTimeout; private searchTimeout; private pendingRequests; private currentOptions; private currentSearchParams; /** * Whether this provider supports real-time updates * WebSocket providers always support real-time updates */ readonly supportsRealTime = true; /** * Creates a new WebSocketDataSource instance * * @param config - WebSocket data source configuration * @param options - Additional configuration options * @throws Error if configuration is invalid */ constructor(config: WebSocketDataSourceConfig, options?: WebSocketDataSourceOptions); /** * Fetch options from WebSocket data source * * Establishes connection if needed and requests current options. * Returns cached data immediately if available and fresh. * * @returns Promise resolving to choice options * @throws Error if connection fails or request times out */ protected fetchData(): Promise<ChoiceOption[]>; /** * Generate cache key for WebSocket data source * * @returns Cache key string including URL and search parameters */ protected getCacheKey(): string | null; /** * Set search parameters for real-time search * * @param params - Search parameters to apply */ setSearchParams(params: Record<string, string | number | boolean>): void; /** * Clear search parameters */ clearSearchParams(): void; /** * Get current connection state * * @returns Current WebSocket connection state */ getConnectionState(): WebSocketConnectionState; /** * Force reconnection to WebSocket server * * @returns Promise that resolves when reconnection is complete */ reconnect(): Promise<void>; /** * Send a message to the WebSocket server * * @param message - Message to send * @throws Error if not connected */ sendMessage(message: WebSocketMessage): void; /** * Subscribe to real-time option updates * * @param callback - Function to call when options are updated * @returns Unsubscribe function */ subscribeToUpdates(callback: (options: ChoiceOption[]) => void): () => void; /** * Cleanup WebSocket resources */ protected cleanupResources(): void; /** * Validate WebSocket configuration */ private validateConfig; /** * Normalize configuration with defaults */ private normalizeConfig; /** * Ensure WebSocket connection is established */ private ensureConnection; /** * Establish WebSocket connection */ private connect; /** * Build connection URL with authentication */ private buildConnectionUrl; /** * Authenticate the WebSocket connection */ private authenticateConnection; /** * Request initial options from server */ private requestInitialOptions; /** * Handle incoming WebSocket messages */ private handleMessage; /** * Handle search response messages */ private handleSearchResponse; /** * Handle options update messages (real-time updates) */ private handleOptionsUpdate; /** * Handle options add messages */ private handleOptionsAdd; /** * Handle options remove messages */ private handleOptionsRemove; /** * Handle options patch messages */ private handleOptionsPatch; /** * Handle error messages from server */ private handleErrorMessage; /** * Handle heartbeat messages */ private handleHeartbeat; /** * Handle WebSocket connection close */ private handleConnectionClose; /** * Handle WebSocket connection errors */ private handleConnectionError; /** * Schedule reconnection with exponential backoff */ private scheduleReconnection; /** * Start heartbeat monitoring */ private startHeartbeat; /** * Debounce search requests */ private debounceSearch; /** * Send search request to server */ private sendSearchRequest; /** * Transform response data using configured mapper */ private transformResponseData; /** * Apply simple response mapper */ private applySimpleMapper; /** * Apply nested response mapper */ private applyNestedMapper; /** * Get cached data safely */ private getWebSocketCachedData; /** * Set cached data safely */ private setWebSocketCachedData; /** * Generate unique message ID */ private generateMessageId; } /** * Factory function to create WebSocketDataSource instances * * @param config - WebSocket data source configuration * @param options - Additional configuration options * @returns New WebSocketDataSource instance */ export declare function createWebSocketDataSource(config: WebSocketDataSourceConfig, options?: WebSocketDataSourceOptions): WebSocketDataSource; /** * Common WebSocket authentication helpers */ export declare const WS_AUTH_HELPERS: { /** * Bearer token authentication */ bearer: (token: string) => { type: "bearer"; credentials: string; }; /** * Query parameter authentication */ query: (token: string, paramName?: string) => { type: "query"; credentials: string; paramName: string; }; /** * Header-based authentication */ header: (token: string, headerName?: string) => { type: "header"; credentials: string; paramName: string; }; }; /** * Common WebSocket message helpers */ export declare const WS_MESSAGE_HELPERS: { /** * Create a search request message */ searchRequest: (searchParams?: Record<string, unknown>, messageId?: string) => WebSocketMessage; /** * Create a heartbeat ping message */ heartbeatPing: (messageId?: string) => WebSocketMessage; /** * Create an options update message */ optionsUpdate: (options: ChoiceOption[], messageId?: string) => WebSocketMessage; };