All files / src/lib sse.ts

97.77% Statements 88/90
92.64% Branches 63/68
100% Functions 6/6
98.75% Lines 79/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227                                                                13x   13x 13x   13x 13x                                                   27x     27x 27x                       3x 1x   2x           24x 7x     17x 1x     16x       16x 16x 16x 31x 29x     11x 1x 1x   11x     18x     18x 18x 18x 18x 18x 18x 15x       2x 1x   1x 1x         16x 16x               7x 7x 1x   6x 1x   5x 3x 3x 3x             2x 1x   1x         33x 33x 33x 16x         18x       19x 19x 19x       19x 39x 37x 37x 36x   36x 36x 36x   13x 13x   19x 19x   1x 1x   2x 2x 2x       1x       19x 18x              
// Server-Sent Events client primitive.
//
// Why not native EventSource?
//   1. EventSource only supports GET. Compose bodies (briefs) must go in a
//      request body โ€” never a query string โ€” because Cloudflare Worker access
//      logs capture query strings, violating the platform invariant of never
//      logging message bodies or raw recipient identifiers.
//   2. EventSource hides HTTP status codes. A 401 on the stream is
//      indistinguishable from a network drop. Using fetch() + ReadableStream
//      lets us inspect status BEFORE consuming the stream and differentiate
//      auth failure, rate limit, client error, and server error.
//
// Track C plan ยง6 โ€” this is the primitive for future streaming consumers.
 
export type SSEEvent = {
	event: string;
	data: string;
	id?: string;
	retry?: number;
};
 
export type SSEErrorKind =
	| "auth_expired"
	| "rate_limit"
	| "forbidden"
	| "client_error"
	| "server_error"
	| "network"
	| "aborted";
 
export class SSEError extends Error {
	constructor(
		public kind: SSEErrorKind,
		message: string,
		public status?: number,
		public retryAfterSeconds?: number,
	) {
		super(message);
		this.name = "SSEError";
	}
}
 
export type StreamFetchOptions = {
	method?: "GET" | "POST";
	body?: unknown; // serialized as JSON if not undefined
	headers?: Record<string, string>;
	signal?: AbortSignal;
};
 
/**
 * Open a streaming fetch and return an async iterable of parsed SSE events.
 *
 * Throws SSEError synchronously (inside the returned AsyncIterable) on any
 * non-2xx HTTP status, network error, or abort. Consumers should iterate
 * inside a try/catch.
 *
 * Parses standard SSE format: blocks separated by blank lines, each block
 * containing `event: <name>` and/or `data: <payload>` lines. `data:` can span
 * multiple lines (concatenated with newline per the SSE spec).
 */
export async function* streamSSE(
	url: string,
	options: StreamFetchOptions = {},
): AsyncIterable<SSEEvent> {
	const { method = "POST", body, headers = {}, signal } = options;
 
	let response: Response;
	try {
		response = await fetch(url, {
			method,
			headers: {
				"Content-Type": "application/json",
				Accept: "text/event-stream",
				...headers,
			},
			body: body === undefined ? undefined : JSON.stringify(body),
			credentials: "include",
			signal,
		});
	} catch (err) {
		if (err instanceof DOMException && err.name === "AbortError") {
			throw new SSEError("aborted", "Stream aborted before start");
		}
		throw new SSEError(
			"network",
			err instanceof Error ? err.message : "Network error",
		);
	}
 
	if (!response.ok) {
		throw mapHttpErrorToSSEError(response);
	}
 
	if (!response.body) {
		throw new SSEError("server_error", "Response has no body", response.status);
	}
 
	const reader = response.body
		.pipeThrough(new TextDecoderStream())
		.getReader();
 
	let buffer = "";
	try {
		while (true) {
			const { done, value } = await reader.read();
			if (done) {
				// Flush any trailing event if buffer isn't empty. Spec says events
				// are terminated by a blank line, but tolerate missing trailer.
				if (buffer.trim().length > 0) {
					const evt = parseSSEBlock(buffer);
					Eif (evt) yield evt;
				}
				return;
			}
 
			buffer += value;
 
			// Process complete events (delimited by blank line: \n\n or \r\n\r\n).
			let sepIdx = findEventSeparator(buffer);
			while (sepIdx !== -1) {
				const block = buffer.slice(0, sepIdx);
				buffer = buffer.slice(sepIdx + separatorLength(buffer, sepIdx));
				const evt = parseSSEBlock(block);
				if (evt) yield evt;
				sepIdx = findEventSeparator(buffer);
			}
		}
	} catch (err) {
		if (err instanceof DOMException && err.name === "AbortError") {
			throw new SSEError("aborted", "Stream aborted");
		}
		Iif (err instanceof SSEError) throw err;
		throw new SSEError(
			"network",
			err instanceof Error ? err.message : "Stream read error",
		);
	} finally {
		try {
			reader.releaseLock();
		} catch {
			// ignore
		}
	}
}
 
function mapHttpErrorToSSEError(response: Response): SSEError {
	const { status } = response;
	if (status === 401) {
		return new SSEError("auth_expired", "Session expired", status);
	}
	if (status === 403) {
		return new SSEError("forbidden", "Not authorized", status);
	}
	if (status === 429) {
		const retryAfter = response.headers.get("Retry-After");
		const seconds = retryAfter ? parseInt(retryAfter, 10) : undefined;
		return new SSEError(
			"rate_limit",
			"Rate limit exceeded",
			status,
			Number.isFinite(seconds) ? seconds : undefined,
		);
	}
	if (status >= 400 && status < 500) {
		return new SSEError("client_error", `Client error ${status}`, status);
	}
	return new SSEError("server_error", `Server error ${status}`, status);
}
 
function findEventSeparator(buf: string): number {
	// Find the earliest of "\n\n" or "\r\n\r\n".
	const lf = buf.indexOf("\n\n");
	const crlf = buf.indexOf("\r\n\r\n");
	if (lf === -1) return crlf;
	Eif (crlf === -1) return lf;
	return Math.min(lf, crlf);
}
 
function separatorLength(buf: string, sepIdx: number): number {
	return buf.startsWith("\r\n\r\n", sepIdx) ? 4 : 2;
}
 
function parseSSEBlock(block: string): SSEEvent | null {
	const lines = block.split(/\r?\n/);
	let event = "message";
	const dataParts: string[] = [];
	let id: string | undefined;
	let retry: number | undefined;
 
	for (const line of lines) {
		if (!line || line.startsWith(":")) continue; // comment or empty
		const colonIdx = line.indexOf(":");
		if (colonIdx === -1) continue;
		const field = line.slice(0, colonIdx);
		// Strip at most one leading space from value per the SSE spec.
		let value = line.slice(colonIdx + 1);
		Eif (value.startsWith(" ")) value = value.slice(1);
		switch (field) {
			case "event":
				event = value;
				break;
			case "data":
				dataParts.push(value);
				break;
			case "id":
				id = value;
				break;
			case "retry": {
				const n = parseInt(value, 10);
				if (Number.isFinite(n)) retry = n;
				break;
			}
			default:
				// Unknown fields are ignored per spec.
				break;
		}
	}
 
	if (dataParts.length === 0) return null;
	return {
		event,
		data: dataParts.join("\n"),
		id,
		retry,
	};
}