import { REALTIME_EVENT_NAMES, validateRealtimeEvent, type KeepaliveEvent, type NotificationSnapshotEvent, type NotificationUpdateEvent, type RealtimeErrorEvent } from "./events.js"; export type RealtimeSubscriberStatus = "connecting" | "open" | "reconnecting" | "closed"; export type RealtimeSubscriberDiagnostic = { phase: "parse" | "validation" | "callback" | "eventsource" | "reconnect"; message: string; eventName?: string; cursor?: string; requestId?: string; retryAttempt?: number; delayMs?: number; }; export type RealtimeMessageEvent = { data: string; type?: string; }; export type RealtimeEventSourceLike = { onopen: (() => void) | null; onmessage: ((event: RealtimeMessageEvent) => void) | null; onerror: ((event: unknown) => void) | null; addEventListener?: (type: string, listener: (event: RealtimeMessageEvent) => void) => void; close: () => void; }; export type RealtimeEventSourceConstructor = new (url: string | URL) => RealtimeEventSourceLike; export type RealtimeReconnectScheduler = { setTimeout: (callback: () => void, delayMs: number) => unknown; clearTimeout: (handle: unknown) => void; }; export type RealtimeReconnectOptions = { enabled?: boolean; baseDelayMs?: number; maxDelayMs?: number; maxRetries?: number; scheduler?: RealtimeReconnectScheduler; }; export type RealtimeSubscriberOptions = { url: string | URL; EventSource?: RealtimeEventSourceConstructor; reconnect?: RealtimeReconnectOptions; onStatus?: (status: RealtimeSubscriberStatus) => void; onDiagnostic?: (diagnostic: RealtimeSubscriberDiagnostic) => void; onSnapshot?: (event: NotificationSnapshotEvent) => void; onUpdate?: (event: NotificationUpdateEvent) => void; onKeepalive?: (event: KeepaliveEvent) => void; onError?: (event: RealtimeErrorEvent) => void; }; export type RealtimeSubscriber = { readonly source: RealtimeEventSourceLike; readonly currentSource: RealtimeEventSourceLike; close: () => void; }; type ParsedEventShape = { event?: unknown; cursor?: unknown; requestId?: unknown; }; const MAX_DIAGNOSTIC_MESSAGE_LENGTH = 160; const DEFAULT_RECONNECT_BASE_DELAY_MS = 1_000; const DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000; const DEFAULT_RECONNECT_MAX_RETRIES = 5; export function subscribeToRealtime(options: RealtimeSubscriberOptions): RealtimeSubscriber { const EventSourceConstructor = options.EventSource ?? getGlobalEventSource(); const reconnect = normalizeReconnectOptions(options.reconnect); let closed = false; let retryAttempts = 0; let reconnectTimer: unknown; let source = connect(); function connect(): RealtimeEventSourceLike { clearReconnectTimer(); const nextSource = new EventSourceConstructor(options.url); emitStatus(options, "connecting"); nextSource.onopen = () => { if (!closed) { retryAttempts = 0; emitStatus(options, "open"); } }; nextSource.onmessage = (message) => { if (!closed) { handleMessage(options, message); } }; registerNamedRealtimeEventListeners(nextSource, options, () => closed); nextSource.onerror = () => { if (!closed) { handleEventSourceError(nextSource); } }; return nextSource; } function handleEventSourceError(failedSource: RealtimeEventSourceLike): void { emitDiagnostic(options, { phase: "eventsource", message: "EventSource reported an error." }); failedSource.close(); if (!reconnect.enabled) { emitStatus(options, "closed"); return; } if (retryAttempts >= reconnect.maxRetries) { emitDiagnostic(options, { phase: "reconnect", message: "Realtime reconnect retry limit reached.", retryAttempt: retryAttempts, }); emitStatus(options, "closed"); return; } retryAttempts += 1; const delayMs = reconnectDelay(retryAttempts, reconnect.baseDelayMs, reconnect.maxDelayMs); emitDiagnostic(options, { phase: "reconnect", message: "Realtime reconnect scheduled.", retryAttempt: retryAttempts, delayMs, }); emitStatus(options, "reconnecting"); reconnectTimer = reconnect.scheduler.setTimeout(() => { reconnectTimer = undefined; if (!closed) { source = connect(); } }, delayMs); } function clearReconnectTimer(): void { if (reconnectTimer !== undefined) { reconnect.scheduler.clearTimeout(reconnectTimer); reconnectTimer = undefined; } } return { get source() { return source; }, get currentSource() { return source; }, close: () => { if (closed) { return; } closed = true; clearReconnectTimer(); source.close(); emitStatus(options, "closed"); }, }; } function registerNamedRealtimeEventListeners( source: RealtimeEventSourceLike, options: RealtimeSubscriberOptions, isClosed: () => boolean ): void { if (typeof source.addEventListener !== "function") { return; } for (const eventName of Object.values(REALTIME_EVENT_NAMES)) { source.addEventListener(eventName, (message) => { if (!isClosed()) { handleMessage(options, message); } }); } } type NormalizedRealtimeReconnectOptions = Required; function normalizeReconnectOptions(options: RealtimeReconnectOptions | undefined): NormalizedRealtimeReconnectOptions { const baseDelayMs = normalizePositiveInteger(options?.baseDelayMs, DEFAULT_RECONNECT_BASE_DELAY_MS); return { enabled: options?.enabled ?? true, baseDelayMs, maxDelayMs: Math.max(baseDelayMs, normalizePositiveInteger(options?.maxDelayMs, DEFAULT_RECONNECT_MAX_DELAY_MS)), maxRetries: normalizeNonNegativeInteger(options?.maxRetries, DEFAULT_RECONNECT_MAX_RETRIES), scheduler: options?.scheduler ?? globalReconnectScheduler, }; } function reconnectDelay(retryAttempt: number, baseDelayMs: number, maxDelayMs: number): number { return Math.min(maxDelayMs, baseDelayMs * 2 ** (retryAttempt - 1)); } function normalizePositiveInteger(value: number | undefined, fallback: number): number { return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback; } function normalizeNonNegativeInteger(value: number | undefined, fallback: number): number { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback; } const globalReconnectScheduler: RealtimeReconnectScheduler = { setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs), clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType), }; function handleMessage(options: RealtimeSubscriberOptions, message: RealtimeMessageEvent): void { let parsed: unknown; try { parsed = JSON.parse(message.data); } catch { emitDiagnostic(options, { phase: "parse", message: "Malformed realtime event JSON: [redacted]" }); return; } try { const event = validateRealtimeEvent(parsed); switch (event.event) { case REALTIME_EVENT_NAMES.notificationSnapshot: invokeCallback(options, "onSnapshot", event); return; case REALTIME_EVENT_NAMES.notificationUpdate: invokeCallback(options, "onUpdate", event); return; case REALTIME_EVENT_NAMES.keepalive: invokeCallback(options, "onKeepalive", event); return; case REALTIME_EVENT_NAMES.error: invokeCallback(options, "onError", event); return; } } catch (error) { emitDiagnostic(options, { ...extractDiagnosticContext(parsed), phase: "validation", message: redactedErrorMessage(error), }); } } function invokeCallback(options: RealtimeSubscriberOptions, key: keyof RealtimeSubscriberOptions, event: Event): void { const callback = options[key]; if (typeof callback !== "function") { return; } try { (callback as (event: Event) => void)(event); } catch (error) { emitDiagnostic(options, { ...extractDiagnosticContext(event), phase: "callback", message: redactedErrorMessage(error), }); } } function emitStatus(options: RealtimeSubscriberOptions, status: RealtimeSubscriberStatus): void { options.onStatus?.(status); } function emitDiagnostic(options: RealtimeSubscriberOptions, diagnostic: RealtimeSubscriberDiagnostic): void { options.onDiagnostic?.(diagnostic); } function extractDiagnosticContext(input: unknown): Pick { if (!isRecord(input)) { return {}; } const event = input as ParsedEventShape; return { eventName: typeof event.event === "string" ? event.event : undefined, cursor: typeof event.cursor === "string" ? event.cursor : undefined, requestId: typeof event.requestId === "string" ? event.requestId : undefined, }; } function redactedErrorMessage(error: unknown): string { if (!(error instanceof Error)) { return "Realtime subscriber rejected an invalid event."; } return error.message.replace(/: .+$/u, ": [redacted]").slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH); } function getGlobalEventSource(): RealtimeEventSourceConstructor { const constructor = globalThis.EventSource as RealtimeEventSourceConstructor | undefined; if (constructor === undefined) { throw new Error("EventSource is not available; provide an EventSource option."); } return constructor; } function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); }