Files
core/src/encoders.ts
T
chrnx 7b3fe57590
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 14s
feat(sse): emit id:, so an EventSource reconnect has something to resume from
`sseEncoder` wrote one field. With no `id:` on the wire the browser had nothing to put in
`Last-Event-ID`, so every automatic reconnect rebuilt the route's iterable from its start
and lost the gap in silence — a healthy-looking stream that had simply skipped events.

Half of this already worked and it was worth checking before designing anything: the
request envelope has always carried every header, so a handler could already read
`@header('last-event-id')`. It just always arrived empty, because we never gave the
browser an id to send.

`sse(data, { id, event, retry })` tags a stream item; `sseEncoder` writes the fields ahead
of `data:`. An app that never calls it sees byte-identical output. `event:` and `retry:`
come along because the envelope carries them for free and neither was reachable before.

**green-tea stores nothing.** No buffer, no retention window, no replay. The framework
carries the marker in both directions and the handler decides what the gap means, because
only the source knows: a paged log re-reads from an offset, a live sensor has no past
worth delivering. Framework-managed replay would need a stream identity that survives a
disconnect — which does not exist, since every request builds a fresh iterable — plus a
retention policy no default can get right and an in-process buffer that breaks the moment
there are two instances. This commit is also the prerequisite for any of that: whatever
replay might land later keys on these ids.

An id with a newline is rejected, not stripped. An id is exactly the value most likely to
be derived from a request — a cursor, a page token — and the SSE format is line-based, so
one newline lets a caller append arbitrary fields to somebody else's stream. Stripping
would resume from the wrong place invisibly, which is the failure this whole feature
exists to close, so it throws where the stream can report it.

`ndjsonEncoder` unwraps the payload and drops the fields: a `negotiate` route yields the
same items to both encoders, and NDJSON has no frame to carry them and no resumption
protocol to use them.

Verified non-vacuous: reverting just the two `encode` functions fails the six framing and
round-trip assertions and leaves the validation ones passing, which is the right split.

Closes #46

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:47:14 -05:00

126 lines
5.8 KiB
TypeScript

/**
* Serializes stream items into wire frames for a streaming transport (SSE, NDJSON).
* `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive.
*/
export interface StreamEncoder {
headers: Record<string, string>;
encode(item: unknown): string | Buffer;
encodeError(err: unknown): string | Buffer | null;
ping?(): string;
}
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
// being recognised across them would silently degrade back to an id-less `data:` frame.
const SSE_EVENT = Symbol.for('green-tea.sse-event');
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
export interface SseFields {
/**
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
* `@header('last-event-id')` and resume from there.
*/
id?: string;
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
event?: string;
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
retry?: number;
}
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
export interface SseEvent<T = unknown> extends SseFields {
readonly [SSE_EVENT]: true;
data: T;
}
/** Type guard: true when a stream item was built by {@link sse}. */
export function isSseEvent(item: unknown): item is SseEvent {
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
}
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
function assertFieldSafe(field: string, value: string): void {
if (!/[\r\n\0]/.test(value)) return;
throw new Error(
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
'one would end the field and let the rest of the value be read as further SSE fields. ' +
`Received ${JSON.stringify(value)}.`,
);
}
/**
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
* instead of a bare `data:` frame.
*
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
* marker in both directions and stores nothing — a source that can resume, resumes; one that
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
*
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
*
* @example
* ```ts
* @Sse('/feed')
* feed(@header('last-event-id') from: string) {
* return (async function* () {
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
* })();
* }
* ```
*/
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
// reconnection delay at the default rather than at the value the app asked for.
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
}
return { [SSE_EVENT]: true, data, ...fields };
}
/**
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
*/
function sseFrame(item: unknown): string {
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
let frame = '';
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
if (item.event !== undefined) frame += `event: ${item.event}\n`;
if (item.id !== undefined) frame += `id: ${item.id}\n`;
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
}
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
export const sseEncoder: StreamEncoder = {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
encode: sseFrame,
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
ping: () => ': ping\n\n',
};
/** Newline-delimited JSON encoder: one JSON object per line. */
export const ndjsonEncoder: StreamEncoder = {
headers: { 'content-type': 'application/x-ndjson' },
// Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
};