Repository Public
1// Server-Sent Events client on fetch streaming (same-origin, session cookie). Compared with EventSource it can see2// HTTP status codes (401 → signed out), sends Last-Event-ID itself on every reconnect, and is unit-testable.34export interface SseMessage {5 id?: string;6 event: string;7 data: string;8}910/** Incremental parser of the text/event-stream format. */11export class SseParser {12 private buffer = "";13 private data: string[] = [];14 private event = "";15 private id: string | undefined;16 retry: number | undefined;1718 push(chunk: string): SseMessage[] {19 this.buffer += chunk;20 const out: SseMessage[] = [];21 for (;;) {22 const m = /\r\n|\n|\r/.exec(this.buffer);23 if (!m) break;24 // a lone trailing \r may be the first half of \r\n: wait for more input25 if (m[0] === "\r" && m.index === this.buffer.length - 1) break;26 const line = this.buffer.slice(0, m.index);27 this.buffer = this.buffer.slice(m.index + m[0].length);28 if (line === "") {29 if (this.data.length > 0 || this.event !== "") {30 out.push({ event: this.event || "message", data: this.data.join("\n"), ...(this.id !== undefined ? { id: this.id } : {}) });31 }32 this.data = [];33 this.event = "";34 continue;35 }36 if (line.startsWith(":")) continue; // comment / heartbeat37 const colon = line.indexOf(":");38 const field = colon === -1 ? line : line.slice(0, colon);39 let value = colon === -1 ? "" : line.slice(colon + 1);40 if (value.startsWith(" ")) value = value.slice(1);41 if (field === "data") this.data.push(value);42 else if (field === "event") this.event = value;43 else if (field === "id") {44 if (!value.includes("\0")) this.id = value;45 } else if (field === "retry" && /^\d+$/.test(value)) this.retry = Number(value);46 }47 return out;48 }49}5051export type SseState = "connecting" | "live" | "reconnecting" | "offline" | "closed";52export interface SseStatus {53 state: SseState;54 /** When the current state began (ms). For reconnecting/offline: when the connection was lost. */55 since: number;56 attempt: number;57 lastEventAt?: number;58}5960export interface SseClientOptions {61 url: string;62 onMessage: (m: SseMessage) => void;63 onStatus?: (s: SseStatus) => void;64 /** Called on 401/403: the session is gone, the client stops. */65 onUnauthorized?: () => void;66 fetch?: typeof fetch;67 now?: () => number;68 random?: () => number;69 baseDelayMs?: number;70 maxDelayMs?: number;71 /** Failed attempts after which the state becomes `offline` instead of `reconnecting`. */72 offlineAfterAttempts?: number;73 /** No byte (event or heartbeat) for this long ⇒ the connection is considered dead. Server pings every 15 s. */74 idleTimeoutMs?: number;75 setTimeout?: (fn: () => void, ms: number) => unknown;76 clearTimeout?: (h: unknown) => void;77}7879export class SseClient {80 private lastEventId: string | undefined;81 private status: SseStatus;82 private abort: AbortController | null = null;83 private timer: unknown = null;84 private idle: unknown = null;85 private stopped = true;86 private attempt = 0;87 private lostAt: number | null = null;88 private readonly o: Required<Omit<SseClientOptions, "onStatus" | "onUnauthorized">> & Pick<SseClientOptions, "onStatus" | "onUnauthorized">;8990 constructor(options: SseClientOptions) {91 this.o = {92 fetch: (...a) => globalThis.fetch(...a),93 now: () => Date.now(),94 random: Math.random,95 baseDelayMs: 1000,96 maxDelayMs: 30000,97 offlineAfterAttempts: 3,98 idleTimeoutMs: 45000,99 setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),100 clearTimeout: (h) => globalThis.clearTimeout(h as ReturnType<typeof globalThis.setTimeout>),101 ...options,102 };103 this.status = { state: "closed", since: this.o.now(), attempt: 0 };104 }105106 getStatus(): SseStatus {107 return this.status;108 }109 getLastEventId(): string | undefined {110 return this.lastEventId;111 }112113 start(): void {114 if (!this.stopped) return;115 this.stopped = false;116 this.attempt = 0;117 this.lostAt = null;118 this.set("connecting");119 void this.connect();120 }121122 stop(): void {123 this.stopped = true;124 this.abort?.abort();125 this.abort = null;126 if (this.timer !== null) this.o.clearTimeout(this.timer);127 if (this.idle !== null) this.o.clearTimeout(this.idle);128 this.timer = this.idle = null;129 this.set("closed");130 }131132 /** Reconnect now (for example when the browser reports it is back online). */133 wake(): void {134 if (this.stopped || this.status.state === "live" || this.status.state === "connecting") return;135 if (this.timer !== null) this.o.clearTimeout(this.timer);136 this.timer = null;137 void this.connect();138 }139140 private set(state: SseState): void {141 const since = state === "reconnecting" || state === "offline" ? (this.lostAt ?? this.o.now()) : this.o.now();142 if (this.status.state === state && this.status.since === since && this.status.attempt === this.attempt) return;143 this.status = { state, since, attempt: this.attempt, ...(this.status.lastEventAt !== undefined ? { lastEventAt: this.status.lastEventAt } : {}) };144 this.o.onStatus?.(this.status);145 }146147 private armIdle(): void {148 if (this.idle !== null) this.o.clearTimeout(this.idle);149 this.idle = this.o.setTimeout(() => this.abort?.abort(), this.o.idleTimeoutMs);150 }151152 private async connect(): Promise<void> {153 if (this.stopped) return;154 const abort = new AbortController();155 this.abort = abort;156 let opened = false;157 try {158 const headers: Record<string, string> = { Accept: "text/event-stream" };159 if (this.lastEventId !== undefined) headers["Last-Event-ID"] = this.lastEventId;160 const res = await this.o.fetch(this.o.url, { headers, credentials: "same-origin", cache: "no-store", signal: abort.signal });161 if (res.status === 401 || res.status === 403) {162 this.stopped = true;163 this.set("closed");164 this.o.onUnauthorized?.();165 return;166 }167 if (!res.ok || !res.body) throw new Error(`sse http ${res.status}`);168 opened = true;169 this.attempt = 0;170 this.lostAt = null;171 this.set("live");172 this.armIdle();173 const reader = res.body.getReader();174 const decoder = new TextDecoder();175 const parser = new SseParser();176 for (;;) {177 const { done, value } = await reader.read();178 if (done) break;179 this.armIdle();180 for (const m of parser.push(decoder.decode(value, { stream: true }))) {181 if (m.id !== undefined) this.lastEventId = m.id;182 this.status = { ...this.status, lastEventAt: this.o.now() };183 this.o.onMessage(m);184 }185 }186 } catch {187 /* network error, abort or idle timeout: handled below */188 }189 if (this.idle !== null) this.o.clearTimeout(this.idle);190 this.idle = null;191 if (this.stopped) return;192 if (this.lostAt === null) this.lostAt = this.o.now();193 // A stream that was open and ended (server-side 30 min bound, deploy) reconnects at once; failures back off.194 const delay = opened ? 0 : this.nextDelay();195 if (!opened) this.attempt++;196 this.set(this.attempt >= this.o.offlineAfterAttempts ? "offline" : "reconnecting");197 this.timer = this.o.setTimeout(() => {198 this.timer = null;199 void this.connect();200 }, delay);201 }202203 private nextDelay(): number {204 const exp = Math.min(this.o.maxDelayMs, this.o.baseDelayMs * 2 ** this.attempt);205 return Math.round(exp * (0.8 + 0.4 * this.o.random()));206 }207}208