/** * Realtime Manager - WebSocket subscription support * @generated by @constructive-io/graphql-codegen * DO NOT EDIT - changes will be overwritten */ // Minimal type shims so this module compiles without graphql-ws // installed. Consumers supply a WsClient via RealtimeConfig; // the SDK itself never imports or requires graphql-ws. interface WsGraphQLError { readonly message: string; readonly [key: string]: unknown; } interface WsExecutionResult> { data?: TData | null; errors?: readonly WsGraphQLError[]; extensions?: Record; } interface WsSink { next(value: T): void; error(error: unknown): void; complete(): void; } /** * Minimal interface matching the graphql-ws Client. * Consumers pass a concrete instance via RealtimeConfig.client. */ export interface WsClient { subscribe>( payload: { query: string; variables?: Record }, sink: WsSink> ): () => void; dispose(): void; } // ============================================================================ // Types // ============================================================================ /** The DML operation that triggered the subscription event */ export type SubscriptionOperation = 'INSERT' | 'UPDATE' | 'DELETE'; /** Connection state of the WebSocket */ export type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting'; /** Listener for connection state changes */ export type ConnectionStateListener = (state: ConnectionState) => void; /** Function returned by subscribe() to cancel the subscription */ export type Unsubscribe = () => void; /** * A realtime subscription event delivered to the client. * * @typeParam T - The row type of the subscribed table */ export interface SubscriptionEvent { /** The DML operation that triggered this event */ operation: SubscriptionOperation; /** The current row data (null for DELETE if row is no longer visible) */ data: T | null; /** Previous field values (populated on UPDATE when available) */ previousValues?: Partial; /** Server-side timestamp of when the change occurred */ timestamp: string; } /** * Options for creating a subscription. * * @typeParam T - The row type of the subscribed table * @typeParam TFilter - The filter type for the table */ export interface SubscribeOptions> { /** Server-side filter to limit which events are delivered */ filter?: TFilter; /** Called when a subscription event is received */ onEvent: (event: SubscriptionEvent) => void; /** Called when the subscription encounters an error */ onError?: (error: Error) => void; /** Called when the subscription completes (server-initiated close) */ onComplete?: () => void; } /** * Metadata about a subscription field, used internally to map * table names to GraphQL subscription field names and types. */ export interface SubscriptionFieldMeta { /** The GraphQL subscription field name (e.g., 'onContactChanged') */ fieldName: string; /** The table name in the source schema (e.g., 'contact') */ tableName: string; /** The data field name inside the subscription payload (e.g., 'contact') */ dataFieldName: string; } /** * Configuration for the realtime (WebSocket) connection. * Pass this as the `realtime` option in OrmClientConfig. * * @example * ```ts * import { createClient } from 'graphql-ws'; * * const client = createOrmClient({ * endpoint: 'https://api.example.com/graphql', * realtime: { * client: createClient({ url: 'wss://api.example.com/graphql' }), * }, * }); * ``` */ export interface RealtimeConfig { /** * A graphql-ws Client instance (or any object satisfying WsClient). * The consumer creates this themselves, giving full control over * connection options, auth, and transport. * * @example * ```ts * import { createClient } from 'graphql-ws'; * const wsClient = createClient({ url: 'wss://...' }); * ``` */ client: WsClient; } // ============================================================================ // RealtimeManager // ============================================================================ /** * Manages a graphql-ws WebSocket client and multiplexes * subscriptions over it. Created by OrmClient when `realtime` * config is provided. */ export class RealtimeManager { private wsClient: WsClient; private connectionState: ConnectionState = 'disconnected'; private stateListeners: Set = new Set(); private activeSubscriptions = 0; constructor(config: RealtimeConfig) { this.wsClient = config.client; } /** * Subscribe to a GraphQL subscription operation. * Models call this with typed metadata and documents. */ subscribe( meta: SubscriptionFieldMeta, document: string, variables: Record, options: { onEvent: (event: SubscriptionEvent) => void; onError?: (error: Error) => void; onComplete?: () => void; } ): Unsubscribe { this.activeSubscriptions++; let disposed = false; const cleanup = this.wsClient.subscribe>( { query: document, variables }, { next: (result) => { if (disposed) return; if (result.errors) { options.onError?.(new Error(result.errors.map((e) => e.message).join('; '))); return; } const payload = result.data?.[meta.fieldName] as | { event?: string; [key: string]: unknown } | undefined; if (!payload) return; const event: SubscriptionEvent = { operation: (payload.event as SubscriptionOperation) ?? 'UPDATE', data: (payload[meta.dataFieldName] as T) ?? null, previousValues: payload.previousValues as Partial | undefined, timestamp: (payload.timestamp as string) ?? new Date().toISOString(), }; options.onEvent(event); }, error: (err) => { if (disposed) return; options.onError?.(err instanceof Error ? err : new Error(String(err))); }, complete: () => { if (disposed) return; options.onComplete?.(); }, } ); return () => { if (disposed) return; disposed = true; this.activeSubscriptions--; cleanup(); }; } /** Register a listener for connection state changes */ onConnectionStateChange(listener: ConnectionStateListener): Unsubscribe { this.stateListeners.add(listener); return () => { this.stateListeners.delete(listener); }; } /** Get current connection state */ getConnectionState(): ConnectionState { return this.connectionState; } /** Number of active subscriptions */ getActiveSubscriptionCount(): number { return this.activeSubscriptions; } /** Dispose the manager and close the WebSocket connection */ dispose(): void { this.wsClient.dispose(); this.stateListeners.clear(); this.activeSubscriptions = 0; this.setConnectionState('disconnected'); } private setConnectionState(state: ConnectionState): void { if (this.connectionState === state) return; this.connectionState = state; for (const listener of this.stateListeners) { listener(state); } } }