// Server-sent events over fetch (EventSource cannot send an Authorization header). export interface SseEvent { event: string; data: string; id?: string; } /** Parse complete events out of a text buffer; returns the unparsed remainder. */ export function parseSse(buffer: string): { events: SseEvent[]; rest: string } { const normalized = buffer.replace(/\r\n?/g, "\n"); const blocks = normalized.split("\n\n"); const rest = blocks.pop() ?? ""; const events: SseEvent[] = []; for (const block of blocks) { let event = "message"; let id: string | undefined; const data: string[] = []; for (const line of block.split("\n")) { if (!line || line.startsWith(":")) continue; const i = line.indexOf(":"); const field = i === -1 ? line : line.slice(0, i); const value = i === -1 ? "" : line.slice(i + 1).replace(/^ /, ""); if (field === "event") event = value; else if (field === "data") data.push(value); else if (field === "id") id = value; } if (data.length) events.push({ event, data: data.join("\n"), id }); } return { events, rest }; } export interface StreamOptions { headers?: Record; signal?: AbortSignal; onEvent: (e: SseEvent) => void; } /** Read one SSE response to the end. Resolves when the server closes the stream. */ export async function streamSse(url: string, opts: StreamOptions): Promise { const res = await fetch(url, { headers: { Accept: "text/event-stream", ...opts.headers }, signal: opts.signal, cache: "no-store", }); if (!res.ok || !res.body) return res.status; const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ""; for (;;) { const { value, done } = await reader.read(); if (done) break; buffer += value; const { events, rest } = parseSse(buffer); buffer = rest; for (const e of events) opts.onEvent(e); } const { events } = parseSse(buffer + "\n\n"); for (const e of events) opts.onEvent(e); return res.status; }