ServerSentEventParseStream

import { ServerSentEventParseStream } from "jsr:@ende/http";

class

class ServerSentEventParseStream extends TransformStream<Uint8Array, ServerSentEventParsedMessage>

Transforms a byte stream of server-sent events into parsed message objects.

This enables consuming server-sent events using the Fetch API instead of EventSource, which is useful when you need custom headers, request bodies, or HTTP methods other than GET.

Example: Basic usage with fetch

import { ServerSentEventParseStream } from "@ende/http/server-sent-event-parse-stream";

const response = await fetch("https://example.com/sse", {
  headers: { "Authorization": "Bearer token" },
});

const stream = response.body!
  .pipeThrough(new ServerSentEventParseStream());

for await (const event of stream) {
  console.log(event.event, event.data);
}

Example: Roundtrip with ServerSentEventStream

import { ServerSentEventParseStream } from "@ende/http/server-sent-event-parse-stream";
import { ServerSentEventStream } from "@ende/http/server-sent-event-stream";
import { assertEquals } from "@ende/assert";

const original = [
  { data: "hello" },
  { event: "update", data: "world" },
  { id: "1", data: "with id" },
];

const encoded = ReadableStream.from(original)
  .pipeThrough(new ServerSentEventStream());

const decoded = encoded.pipeThrough(new ServerSentEventParseStream());
const result = await Array.fromAsync(decoded);

assertEquals(result, original);

Example: Ignoring comments

import { ServerSentEventParseStream } from "@ende/http/server-sent-event-parse-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([
  new TextEncoder().encode(":keepalive\ndata: hello\n\n"),
]).pipeThrough(new ServerSentEventParseStream({ ignoreComments: true }));

const result = await Array.fromAsync(stream);

assertEquals(result, [{ data: "hello" }]);

See also

Constructors

constructor

new ServerSentEventParseStream(options: ServerSentEventParseStreamOptions = [UNSUPPORTED])

Constructs a new instance.

options: ServerSentEventParseStreamOptions = [UNSUPPORTED]

Options for the stream.

Source