@statewalker/webrun-http-events 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mikhail Kotelnikov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @statewalker/webrun-http-events
2
+
3
+ Generic publish/subscribe over [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html):
4
+ a standard `FetchHandler` on the server side and a matching `EventSource` client on the page side.
5
+
6
+ No runtime dependencies, no DOM APIs on the server half (it runs in a Worker, a ServiceWorker or
7
+ Node), and no vocabulary of its own — topics and event names are yours.
8
+
9
+ ```sh
10
+ npm install @statewalker/webrun-http-events
11
+ ```
12
+
13
+ ## Server
14
+
15
+ ```ts
16
+ import { newPubSub } from "@statewalker/webrun-http-events";
17
+
18
+ const events = newPubSub({ topics: ["build"], bufferSize: 64 });
19
+
20
+ // Mount the handler on any fetch-style router; the topic is the last path segment.
21
+ // GET /_events/build -> text/event-stream
22
+ export const fetch = (request: Request) => events.handler(request);
23
+
24
+ events.publish("build", { changed: ["/index.html"] }, "rebuilt");
25
+ ```
26
+
27
+ `newPubSub(options)`:
28
+
29
+ | option | meaning |
30
+ | --- | --- |
31
+ | `topics` | Allow-list of topic names. Without it, any request path allocates a topic — set it on a public endpoint. |
32
+ | `bufferSize` | Events retained per topic for `Last-Event-ID` replay (default 64). |
33
+ | `heartbeatMs` | Interval for `: ping` comment frames. 0 (default) means no heartbeat. |
34
+ | `onSubscriberError` | Called when a subscriber throws; delivery to the others continues either way. |
35
+
36
+ The handler answers `405` to anything but `GET` and `404` to an unknown or empty topic.
37
+
38
+ ## Client
39
+
40
+ ```ts
41
+ import { newPubSubClient } from "@statewalker/webrun-http-events";
42
+
43
+ const client = newPubSubClient("/_events", {
44
+ events: ["message", "rebuilt"], // see "event names" below
45
+ onGap: (topic) => location.reload(), // history could not be replayed: re-sync
46
+ onError: (topic, e) => console.warn("subscription failed", topic, e),
47
+ });
48
+
49
+ const off = client.subscribe("build", (data, { id, event }) => {
50
+ console.log(id, event, data);
51
+ });
52
+ ```
53
+
54
+ ### Event names
55
+
56
+ A frame published with a name (`publish(topic, data, "rebuilt")`) is dispatched by `EventSource`
57
+ **only** under that name — it does not also fire `message`. So every name a page wants must be
58
+ listed, either per client (`events`) or per subscription (`client.subscribe(topic, cb, { events })`).
59
+ The default is `["message"]`, which is what an unnamed `publish(topic, data)` produces.
60
+
61
+ `gap`, `error` and `open` are **reserved**: they are the client's own control channels, reported
62
+ through `onGap`, `onError` and `onOpen`. Listing one as a data event throws a `TypeError` — a gap
63
+ delivered as data is exactly the failure the gap contract exists to prevent.
64
+
65
+ ### Gaps
66
+
67
+ Every event carries an id. A reconnecting `EventSource` sends `Last-Event-ID`, and the server
68
+ replays what it still retains. When it cannot reconstruct the client's history — the events were
69
+ evicted, the id predates a server restart, or the header was unreadable — it sends a `gap` event
70
+ instead of a partial replay that would look whole. `onGap` means *you are not current*: reload or
71
+ re-sync rather than patching forward.
72
+
73
+ ### Permanent failure
74
+
75
+ `EventSource` reconnects on its own after a dropped connection, but a non-2xx response or a wrong
76
+ content-type closes it for good. That is reported through `onError` (check `readyState === 2`); a
77
+ subscription that died is never resurrected by itself.
78
+
79
+ ## Notes
80
+
81
+ - Reentrant publishing — calling `publish` from inside a subscriber — is not supported: the inner
82
+ event is delivered to completion first, so subscribers observe ids out of order.
83
+ - A payload JSON cannot represent (`undefined`, a function, a symbol, a BigInt, a circular object)
84
+ is framed as `null`; the event still reaches the client with its id and name.
85
+
86
+ ## License
87
+
88
+ MIT
@@ -0,0 +1,141 @@
1
+ //#region src/broker.d.ts
2
+ type BrokerEvent = {
3
+ id: number;
4
+ event?: string;
5
+ data: unknown;
6
+ };
7
+ type Subscriber = (e: BrokerEvent) => void;
8
+ type Unsubscribe = () => void;
9
+ interface Broker {
10
+ /**
11
+ * Deliver `data` to every subscriber of `topic` and retain it for replay.
12
+ *
13
+ * Delivery is synchronous and each subscriber is isolated: one that throws is
14
+ * reported to `onSubscriberError` and cannot starve the others or the caller.
15
+ *
16
+ * Publishing from inside a subscriber (a reentrant publish) is NOT supported:
17
+ * the inner event is delivered to completion before the outer one finishes, so
18
+ * subscribers observe ids out of order and a client's Last-Event-ID can move
19
+ * backwards. Publish from a fresh task instead.
20
+ */
21
+ publish(topic: string, data: unknown, event?: string): BrokerEvent;
22
+ /** Register `fn` for future events on `topic`. Use {@link Broker.replay} for history. */
23
+ subscribe(topic: string, fn: Subscriber): Unsubscribe;
24
+ /**
25
+ * Events retained after `afterId`, plus whether that is the whole story.
26
+ * `complete: false` means the caller's history cannot be reconstructed — either
27
+ * the events it wants were evicted, or its `afterId` is above anything this
28
+ * broker has issued (a client left over from a previous process).
29
+ */
30
+ replay(topic: string, afterId: number): {
31
+ events: BrokerEvent[];
32
+ complete: boolean;
33
+ };
34
+ subscriberCount(topic: string): number;
35
+ /** How many topics currently hold state. Topics with no subscribers and no retained events are dropped. */
36
+ topicCount(): number;
37
+ }
38
+ interface BrokerOptions {
39
+ /** How many recent events to retain per topic for Last-Event-ID replay. */
40
+ bufferSize?: number;
41
+ /**
42
+ * Called when a subscriber throws. Delivery continues either way; without this
43
+ * the failure would be invisible.
44
+ */
45
+ onSubscriberError?: (error: unknown, e: BrokerEvent) => void;
46
+ }
47
+ export declare function newBroker({ bufferSize, onSubscriberError }?: BrokerOptions): Broker;
48
+ //#endregion
49
+ //#region src/client.d.ts
50
+ interface PubSubClientOptions {
51
+ /** Injected for tests, and for runtimes with a non-global EventSource. */
52
+ EventSourceImpl?: typeof EventSource;
53
+ /**
54
+ * Default event names for every subscription on this client; `["message"]`
55
+ * unless given. A frame published with `event: X` is dispatched by the browser
56
+ * ONLY as type X — it does not also fire `message` — so a name that is not
57
+ * listed here is received by nobody.
58
+ *
59
+ * `gap`, `error` and `open` are RESERVED: they are this client's control
60
+ * channels, reported through `onGap`, `onError` and `onOpen`. Listing one here
61
+ * throws a `TypeError` rather than handing a control frame to a data callback.
62
+ */
63
+ events?: readonly string[];
64
+ /**
65
+ * Called when the server reports it could not replay the client's full
66
+ * history. The caller should re-sync from scratch rather than assume the
67
+ * events it did receive are complete.
68
+ *
69
+ * A gap is not the only way a subscription stops being trustworthy: a stream
70
+ * that fails permanently is reported through {@link PubSubClientOptions.onError}.
71
+ */
72
+ onGap?: (topic: string) => void;
73
+ /**
74
+ * Called when the stream errors. `EventSource` retries a dropped connection on
75
+ * its own, but a non-2xx response or a wrong content-type closes it FOR GOOD —
76
+ * the subscription is then dead and this is the only notice of it. Check
77
+ * `readyState === 2` (CLOSED) to tell the two apart, and resubscribe.
78
+ */
79
+ onError?: (topic: string, e: Event) => void;
80
+ /** Called when the stream opens, including after `EventSource`'s own reconnect. */
81
+ onOpen?: (topic: string) => void;
82
+ }
83
+ interface SubscribeOptions {
84
+ /**
85
+ * Event names for this subscription, overriding the client's default set.
86
+ * `gap`, `error` and `open` are reserved; see {@link PubSubClientOptions.events}.
87
+ */
88
+ events?: readonly string[];
89
+ }
90
+ interface PubSubClient {
91
+ subscribe(topic: string, cb: (data: unknown, e: {
92
+ id: number;
93
+ event?: string;
94
+ }) => void, options?: SubscribeOptions): Unsubscribe;
95
+ close(): void;
96
+ }
97
+ export declare function newPubSubClient(baseUrl: string, { EventSourceImpl, events, onGap, onError, onOpen }?: PubSubClientOptions): PubSubClient;
98
+ //#endregion
99
+ //#region src/handler.d.ts
100
+ type FetchHandler = (request: Request) => Promise<Response>;
101
+ interface PubSubOptions extends BrokerOptions {
102
+ /**
103
+ * When given, only these topic names are served; anything else answers 404.
104
+ * Without it any request path allocates a topic, so an open endpoint should
105
+ * set this.
106
+ */
107
+ topics?: readonly string[];
108
+ /**
109
+ * Interval in ms for `: ping` comment frames, which the SSE parser ignores but
110
+ * which keep a half-open connection visible to proxies. 0 (the default) means
111
+ * no heartbeat: a connection that dies silently is then only noticed when the
112
+ * client's own reconnect timer fires.
113
+ */
114
+ heartbeatMs?: number;
115
+ }
116
+ interface PubSub {
117
+ handler: FetchHandler;
118
+ publish(topic: string, data: unknown, event?: string): void;
119
+ subscriberCount(topic: string): number;
120
+ /** How many topics currently hold state; a topic with no subscribers and no retained events is dropped. */
121
+ topicCount(): number;
122
+ }
123
+ export declare function newPubSub(options?: PubSubOptions): PubSub;
124
+ //#endregion
125
+ //#region src/sse.d.ts
126
+ /**
127
+ * Format one WHATWG Server-Sent Event frame, terminated by the blank line that
128
+ * ends an event.
129
+ *
130
+ * `data` is always JSON-serialized, strings included (a string payload arrives
131
+ * back through `JSON.parse` as the same string, never half-decoded). JSON escapes
132
+ * newlines, so the body is a single line in practice; every line is prefixed
133
+ * anyway, because an unframed newline would end the event and truncate it.
134
+ *
135
+ * CR and LF are stripped from the event name: it is caller-supplied, and a
136
+ * newline there would inject whole frames onto the wire.
137
+ */
138
+ export declare function formatSseEvent(e: BrokerEvent): string;
139
+ //#endregion
140
+ export type { Broker, BrokerEvent, BrokerOptions, FetchHandler, PubSub, PubSubClient, PubSubClientOptions, PubSubOptions, SubscribeOptions, Subscriber, Unsubscribe };
141
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/broker.ts","../src/client.ts","../src/handler.ts","../src/sse.ts"],"mappings":";KAAY;EAAgB;EAAY;EAAgB;;KAC5C,cAAc,GAAG;KACjB;UAEK;;;;;;;;;;;;EAYf,QAAQ,eAAe,eAAe,iBAAiB;;EAEvD,UAAU,eAAe,IAAI,aAAa;;;;;;;EAO1C,OAAO,eAAe;IAAoB,QAAQ;IAAe;;EACjE,gBAAgB;;EAEhB;;UAGe;;EAEf;;;;;EAKA,qBAAqB,gBAAgB,GAAG;;wBAU1B,YAAY,YAAiB,sBAAqB,gBAAqB;;;UCvBtE;;EAEf,yBAAyB;;;;;;;;;;;EAWzB;;;;;;;;;EASA,SAAS;;;;;;;EAOT,WAAW,eAAe,GAAG;;EAE7B,UAAU;;UAGK;;;;;EAKf;;UAGe;EACf,UACE,eACA,KAAK,eAAe;IAAK;IAAY;cACrC,UAAU,mBACT;EACH;;wBAGc,gBACd,mBACE,iBAAiB,QAAQ,OAAO,SAAS,WAAU,sBACpD;;;KC5ES,gBAAgB,SAAS,YAAY,QAAQ;UAExC,sBAAsB;;;;;;EAMrC;;;;;;;EAOA;;UAGe;EACf,SAAS;EACT,QAAQ,eAAe,eAAe;EACtC,gBAAgB;;EAEhB;;wBA4Fc,UAAU,UAAS,gBAAqB;;;;;;;;;;;;;;;wBC1FxC,eAAe,GAAG"}
package/dist/index.mjs ADDED
@@ -0,0 +1,261 @@
1
+ //#region src/broker.ts
2
+ function newBroker({ bufferSize = 64, onSubscriberError } = {}) {
3
+ const topics = /* @__PURE__ */ new Map();
4
+ const state = (topic) => {
5
+ let s = topics.get(topic);
6
+ if (!s) {
7
+ s = {
8
+ nextId: 1,
9
+ buffer: [],
10
+ subscribers: /* @__PURE__ */ new Set()
11
+ };
12
+ topics.set(topic, s);
13
+ }
14
+ return s;
15
+ };
16
+ /** Drop a topic that holds nothing, so request-driven names cannot accumulate. */
17
+ const prune = (topic, s) => {
18
+ if (topics.get(topic) === s && s.subscribers.size === 0 && s.buffer.length === 0) topics.delete(topic);
19
+ };
20
+ const replay = (topic, afterId) => {
21
+ const s = topics.get(topic);
22
+ if (!s) return {
23
+ events: [],
24
+ complete: afterId <= 0
25
+ };
26
+ const events = s.buffer.filter((e) => e.id > afterId);
27
+ const latest = s.nextId - 1;
28
+ return {
29
+ events,
30
+ complete: afterId >= (s.buffer[0]?.id ?? s.nextId) - 1 && afterId <= latest
31
+ };
32
+ };
33
+ return {
34
+ publish(topic, data, event) {
35
+ const s = state(topic);
36
+ const e = {
37
+ id: s.nextId++,
38
+ data,
39
+ ...event === void 0 ? {} : { event }
40
+ };
41
+ s.buffer.push(e);
42
+ if (s.buffer.length > bufferSize) s.buffer.shift();
43
+ for (const fn of [...s.subscribers]) try {
44
+ fn(e);
45
+ } catch (error) {
46
+ try {
47
+ onSubscriberError?.(error, e);
48
+ } catch {}
49
+ }
50
+ return e;
51
+ },
52
+ subscribe(topic, fn) {
53
+ const s = state(topic);
54
+ s.subscribers.add(fn);
55
+ return () => {
56
+ s.subscribers.delete(fn);
57
+ prune(topic, s);
58
+ };
59
+ },
60
+ replay,
61
+ subscriberCount(topic) {
62
+ return topics.get(topic)?.subscribers.size ?? 0;
63
+ },
64
+ topicCount() {
65
+ return topics.size;
66
+ }
67
+ };
68
+ }
69
+ //#endregion
70
+ //#region src/client.ts
71
+ /** The SSE event type a subscription listens for when nothing else is asked for. */
72
+ const DEFAULT_EVENTS = ["message"];
73
+ /**
74
+ * Names this client owns. They are wired to `onGap`, `onError` and `onOpen`, never
75
+ * to a data callback: a `gap` delivered as data would have the caller patch forward
76
+ * from a false baseline believing its history complete, and `error`/`open` carry a
77
+ * bare `Event` with no `data` to parse.
78
+ */
79
+ const RESERVED_EVENTS = [
80
+ "gap",
81
+ "error",
82
+ "open"
83
+ ];
84
+ function checkEvents(events, where) {
85
+ for (const name of events) if (RESERVED_EVENTS.includes(name)) throw new TypeError(`${where}: "${name}" is a reserved event name — it is delivered to on${name[0]?.toUpperCase()}${name.slice(1)}, not to a subscriber`);
86
+ return events;
87
+ }
88
+ function newPubSubClient(baseUrl, { EventSourceImpl, events, onGap, onError, onOpen } = {}) {
89
+ const Impl = EventSourceImpl ?? globalThis.EventSource;
90
+ if (!Impl) throw new Error("no EventSource available; pass options.EventSourceImpl");
91
+ const open = /* @__PURE__ */ new Set();
92
+ const base = baseUrl.replace(/\/$/, "");
93
+ const defaultEvents = events === void 0 ? DEFAULT_EVENTS : checkEvents(events, "newPubSubClient");
94
+ return {
95
+ subscribe(topic, cb, options = {}) {
96
+ const names = options.events === void 0 ? defaultEvents : checkEvents(options.events, "subscribe");
97
+ const source = new Impl(`${base}/${topic}`);
98
+ open.add(source);
99
+ const listeners = [];
100
+ const on = (type, fn) => {
101
+ listeners.push([type, fn]);
102
+ source.addEventListener(type, fn);
103
+ };
104
+ for (const name of names) on(name, (e) => {
105
+ const m = e;
106
+ cb(JSON.parse(m.data), {
107
+ id: Number(m.lastEventId),
108
+ ...name === "message" ? {} : { event: name }
109
+ });
110
+ });
111
+ on("gap", () => onGap?.(topic));
112
+ on("error", (e) => onError?.(topic, e));
113
+ on("open", () => onOpen?.(topic));
114
+ return () => {
115
+ for (const [type, fn] of listeners) source.removeEventListener(type, fn);
116
+ listeners.length = 0;
117
+ source.close();
118
+ open.delete(source);
119
+ };
120
+ },
121
+ close() {
122
+ for (const s of open) s.close();
123
+ open.clear();
124
+ }
125
+ };
126
+ }
127
+ //#endregion
128
+ //#region src/sse.ts
129
+ /**
130
+ * JSON for the wire. Total by construction: `JSON.stringify` returns `undefined`
131
+ * rather than a string for `undefined`, a function or a symbol, and throws on a
132
+ * BigInt or a circular object. Any of those is framed as `null` — the event still
133
+ * reaches the client with its id and name, which is what an empty signal is for.
134
+ */
135
+ function serialize(data) {
136
+ try {
137
+ return JSON.stringify(data) ?? "null";
138
+ } catch {
139
+ return "null";
140
+ }
141
+ }
142
+ /**
143
+ * Format one WHATWG Server-Sent Event frame, terminated by the blank line that
144
+ * ends an event.
145
+ *
146
+ * `data` is always JSON-serialized, strings included (a string payload arrives
147
+ * back through `JSON.parse` as the same string, never half-decoded). JSON escapes
148
+ * newlines, so the body is a single line in practice; every line is prefixed
149
+ * anyway, because an unframed newline would end the event and truncate it.
150
+ *
151
+ * CR and LF are stripped from the event name: it is caller-supplied, and a
152
+ * newline there would inject whole frames onto the wire.
153
+ */
154
+ function formatSseEvent(e) {
155
+ const lines = serialize(e.data).split("\n").map((l) => `data: ${l}\n`).join("");
156
+ const name = e.event === void 0 ? "" : `event: ${e.event.replace(/[\r\n]/g, "")}\n`;
157
+ return `id: ${e.id}\n${name}${lines}\n`;
158
+ }
159
+ //#endregion
160
+ //#region src/handler.ts
161
+ /** The topic is the final non-empty path segment: /_events/build -> "build". */
162
+ function topicOf(request) {
163
+ return new URL(request.url).pathname.split("/").filter(Boolean).at(-1) ?? "";
164
+ }
165
+ /**
166
+ * The `ReadableStream` source behind one subscription.
167
+ *
168
+ * Exported so tests can drive it with a controller whose `enqueue` fails, which
169
+ * is the one path a real stream cannot be pushed down from outside.
170
+ */
171
+ function createSseSource(broker, topic, { replayFrom, forceGap = false, heartbeatMs = 0 } = {}) {
172
+ const encoder = new TextEncoder();
173
+ let unsubscribe;
174
+ let heartbeat;
175
+ let broken = false;
176
+ return {
177
+ start(controller) {
178
+ /** Tear the subscription down and end the stream, once. */
179
+ const stop = () => {
180
+ if (broken) return;
181
+ broken = true;
182
+ if (heartbeat !== void 0) clearInterval(heartbeat);
183
+ unsubscribe?.();
184
+ unsubscribe = void 0;
185
+ try {
186
+ controller.close();
187
+ } catch {}
188
+ };
189
+ const write = (frame) => {
190
+ if (broken) return;
191
+ try {
192
+ controller.enqueue(encoder.encode(frame()));
193
+ } catch {
194
+ stop();
195
+ }
196
+ };
197
+ unsubscribe = broker.subscribe(topic, (e) => write(() => formatSseEvent(e)));
198
+ if (forceGap || replayFrom !== void 0) {
199
+ const from = replayFrom ?? 0;
200
+ const { events, complete } = replayFrom === void 0 ? {
201
+ events: [],
202
+ complete: false
203
+ } : broker.replay(topic, replayFrom);
204
+ if (!complete) write(() => formatSseEvent({
205
+ id: from,
206
+ event: "gap",
207
+ data: { from }
208
+ }));
209
+ for (const e of events) write(() => formatSseEvent(e));
210
+ }
211
+ if (heartbeatMs > 0) heartbeat = setInterval(() => write(() => ": ping\n\n"), heartbeatMs);
212
+ },
213
+ cancel() {
214
+ if (heartbeat !== void 0) clearInterval(heartbeat);
215
+ broken = true;
216
+ unsubscribe?.();
217
+ unsubscribe = void 0;
218
+ }
219
+ };
220
+ }
221
+ function newPubSub(options = {}) {
222
+ const { topics, heartbeatMs, ...brokerOptions } = options;
223
+ const broker = newBroker(brokerOptions);
224
+ const allowed = topics === void 0 ? void 0 : new Set(topics);
225
+ const handler = async (request) => {
226
+ if (request.method !== "GET") return new Response("method not allowed", {
227
+ status: 405,
228
+ headers: { allow: "GET" }
229
+ });
230
+ const topic = topicOf(request);
231
+ if (topic === "" || allowed !== void 0 && !allowed.has(topic)) return new Response("no such topic", { status: 404 });
232
+ const header = request.headers.get("last-event-id");
233
+ const parsed = header === null ? NaN : Number(header);
234
+ const usable = header !== null && Number.isSafeInteger(parsed) && parsed >= 0;
235
+ const forceGap = header !== null && !usable;
236
+ const stream = new ReadableStream(createSseSource(broker, topic, {
237
+ ...usable ? { replayFrom: parsed } : {},
238
+ forceGap,
239
+ ...heartbeatMs === void 0 ? {} : { heartbeatMs }
240
+ }));
241
+ return new Response(stream, {
242
+ status: 200,
243
+ headers: {
244
+ "content-type": "text/event-stream",
245
+ "cache-control": "no-cache",
246
+ connection: "keep-alive",
247
+ "x-accel-buffering": "no"
248
+ }
249
+ });
250
+ };
251
+ return {
252
+ handler,
253
+ publish: (topic, data, event) => void broker.publish(topic, data, event),
254
+ subscriberCount: (topic) => broker.subscriberCount(topic),
255
+ topicCount: () => broker.topicCount()
256
+ };
257
+ }
258
+ //#endregion
259
+ export { formatSseEvent, newBroker, newPubSub, newPubSubClient };
260
+
261
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/broker.ts","../src/client.ts","../src/sse.ts","../src/handler.ts"],"sourcesContent":["export type BrokerEvent = { id: number; event?: string; data: unknown };\nexport type Subscriber = (e: BrokerEvent) => void;\nexport type Unsubscribe = () => void;\n\nexport interface Broker {\n /**\n * Deliver `data` to every subscriber of `topic` and retain it for replay.\n *\n * Delivery is synchronous and each subscriber is isolated: one that throws is\n * reported to `onSubscriberError` and cannot starve the others or the caller.\n *\n * Publishing from inside a subscriber (a reentrant publish) is NOT supported:\n * the inner event is delivered to completion before the outer one finishes, so\n * subscribers observe ids out of order and a client's Last-Event-ID can move\n * backwards. Publish from a fresh task instead.\n */\n publish(topic: string, data: unknown, event?: string): BrokerEvent;\n /** Register `fn` for future events on `topic`. Use {@link Broker.replay} for history. */\n subscribe(topic: string, fn: Subscriber): Unsubscribe;\n /**\n * Events retained after `afterId`, plus whether that is the whole story.\n * `complete: false` means the caller's history cannot be reconstructed — either\n * the events it wants were evicted, or its `afterId` is above anything this\n * broker has issued (a client left over from a previous process).\n */\n replay(topic: string, afterId: number): { events: BrokerEvent[]; complete: boolean };\n subscriberCount(topic: string): number;\n /** How many topics currently hold state. Topics with no subscribers and no retained events are dropped. */\n topicCount(): number;\n}\n\nexport interface BrokerOptions {\n /** How many recent events to retain per topic for Last-Event-ID replay. */\n bufferSize?: number;\n /**\n * Called when a subscriber throws. Delivery continues either way; without this\n * the failure would be invisible.\n */\n onSubscriberError?: (error: unknown, e: BrokerEvent) => void;\n}\n\ntype TopicState = {\n nextId: number;\n /** Bounded ring of recent events, oldest first. */\n buffer: BrokerEvent[];\n subscribers: Set<Subscriber>;\n};\n\nexport function newBroker({ bufferSize = 64, onSubscriberError }: BrokerOptions = {}): Broker {\n const topics = new Map<string, TopicState>();\n\n const state = (topic: string): TopicState => {\n let s = topics.get(topic);\n if (!s) {\n s = { nextId: 1, buffer: [], subscribers: new Set() };\n topics.set(topic, s);\n }\n return s;\n };\n\n /** Drop a topic that holds nothing, so request-driven names cannot accumulate. */\n const prune = (topic: string, s: TopicState): void => {\n if (topics.get(topic) === s && s.subscribers.size === 0 && s.buffer.length === 0) {\n topics.delete(topic);\n }\n };\n\n const replay: Broker[\"replay\"] = (topic, afterId) => {\n const s = topics.get(topic);\n // An absent topic has issued nothing: only a caller with no history is current.\n if (!s) return { events: [], complete: afterId <= 0 };\n const events = s.buffer.filter((e) => e.id > afterId);\n const latest = s.nextId - 1;\n // An empty ring retains nothing, so nothing before `nextId` can be reconstructed.\n const oldest = s.buffer[0]?.id ?? s.nextId;\n // Incomplete below, when the requested point predates the oldest retained event,\n // and above, when it names an id this broker never issued.\n return { events, complete: afterId >= oldest - 1 && afterId <= latest };\n };\n\n return {\n publish(topic, data, event) {\n const s = state(topic);\n const e: BrokerEvent = { id: s.nextId++, data, ...(event === undefined ? {} : { event }) };\n s.buffer.push(e);\n if (s.buffer.length > bufferSize) s.buffer.shift();\n // Copy before iterating: a subscriber may unsubscribe during delivery.\n for (const fn of [...s.subscribers]) {\n try {\n fn(e);\n } catch (error) {\n try {\n onSubscriberError?.(error, e);\n } catch {\n // A reporter that throws must not starve the remaining subscribers either.\n }\n }\n }\n return e;\n },\n\n subscribe(topic, fn) {\n const s = state(topic);\n s.subscribers.add(fn);\n return () => {\n s.subscribers.delete(fn);\n prune(topic, s);\n };\n },\n\n replay,\n\n subscriberCount(topic) {\n return topics.get(topic)?.subscribers.size ?? 0;\n },\n\n topicCount() {\n return topics.size;\n },\n };\n}\n","import type { Unsubscribe } from \"./broker.js\";\n\n/** The SSE event type a subscription listens for when nothing else is asked for. */\nconst DEFAULT_EVENTS = [\"message\"] as const;\n\n/**\n * Names this client owns. They are wired to `onGap`, `onError` and `onOpen`, never\n * to a data callback: a `gap` delivered as data would have the caller patch forward\n * from a false baseline believing its history complete, and `error`/`open` carry a\n * bare `Event` with no `data` to parse.\n */\nconst RESERVED_EVENTS: readonly string[] = [\"gap\", \"error\", \"open\"];\n\nfunction checkEvents(events: readonly string[], where: string): readonly string[] {\n for (const name of events) {\n if (RESERVED_EVENTS.includes(name)) {\n throw new TypeError(\n `${where}: \"${name}\" is a reserved event name — it is delivered to ` +\n `on${name[0]?.toUpperCase()}${name.slice(1)}, not to a subscriber`,\n );\n }\n }\n return events;\n}\n\nexport interface PubSubClientOptions {\n /** Injected for tests, and for runtimes with a non-global EventSource. */\n EventSourceImpl?: typeof EventSource;\n /**\n * Default event names for every subscription on this client; `[\"message\"]`\n * unless given. A frame published with `event: X` is dispatched by the browser\n * ONLY as type X — it does not also fire `message` — so a name that is not\n * listed here is received by nobody.\n *\n * `gap`, `error` and `open` are RESERVED: they are this client's control\n * channels, reported through `onGap`, `onError` and `onOpen`. Listing one here\n * throws a `TypeError` rather than handing a control frame to a data callback.\n */\n events?: readonly string[];\n /**\n * Called when the server reports it could not replay the client's full\n * history. The caller should re-sync from scratch rather than assume the\n * events it did receive are complete.\n *\n * A gap is not the only way a subscription stops being trustworthy: a stream\n * that fails permanently is reported through {@link PubSubClientOptions.onError}.\n */\n onGap?: (topic: string) => void;\n /**\n * Called when the stream errors. `EventSource` retries a dropped connection on\n * its own, but a non-2xx response or a wrong content-type closes it FOR GOOD —\n * the subscription is then dead and this is the only notice of it. Check\n * `readyState === 2` (CLOSED) to tell the two apart, and resubscribe.\n */\n onError?: (topic: string, e: Event) => void;\n /** Called when the stream opens, including after `EventSource`'s own reconnect. */\n onOpen?: (topic: string) => void;\n}\n\nexport interface SubscribeOptions {\n /**\n * Event names for this subscription, overriding the client's default set.\n * `gap`, `error` and `open` are reserved; see {@link PubSubClientOptions.events}.\n */\n events?: readonly string[];\n}\n\nexport interface PubSubClient {\n subscribe(\n topic: string,\n cb: (data: unknown, e: { id: number; event?: string }) => void,\n options?: SubscribeOptions,\n ): Unsubscribe;\n close(): void;\n}\n\nexport function newPubSubClient(\n baseUrl: string,\n { EventSourceImpl, events, onGap, onError, onOpen }: PubSubClientOptions = {},\n): PubSubClient {\n const Impl = EventSourceImpl ?? globalThis.EventSource;\n if (!Impl) throw new Error(\"no EventSource available; pass options.EventSourceImpl\");\n\n const open = new Set<EventSource>();\n const base = baseUrl.replace(/\\/$/, \"\");\n const defaultEvents =\n events === undefined ? DEFAULT_EVENTS : checkEvents(events, \"newPubSubClient\");\n\n return {\n subscribe(topic, cb, options = {}) {\n // Validated before anything is opened, so a rejected call leaks no EventSource.\n const names =\n options.events === undefined ? defaultEvents : checkEvents(options.events, \"subscribe\");\n\n const source = new Impl(`${base}/${topic}`);\n open.add(source);\n\n const listeners: Array<[string, (e: Event) => void]> = [];\n const on = (type: string, fn: (e: Event) => void) => {\n listeners.push([type, fn]);\n source.addEventListener(type, fn);\n };\n\n for (const name of names) {\n on(name, (e) => {\n const m = e as MessageEvent;\n cb(JSON.parse(m.data), {\n id: Number(m.lastEventId),\n // `message` is the unnamed default; anything else names itself.\n ...(name === \"message\" ? {} : { event: name }),\n });\n });\n }\n // The gap signal is the client half of the replay contract; it never\n // reaches the subscriber, which would mistake it for a payload.\n on(\"gap\", () => onGap?.(topic));\n on(\"error\", (e) => onError?.(topic, e));\n on(\"open\", () => onOpen?.(topic));\n\n return () => {\n for (const [type, fn] of listeners) source.removeEventListener(type, fn);\n listeners.length = 0;\n source.close();\n open.delete(source);\n };\n },\n\n close() {\n for (const s of open) s.close();\n open.clear();\n },\n };\n}\n","import type { BrokerEvent } from \"./broker.js\";\n\n/**\n * JSON for the wire. Total by construction: `JSON.stringify` returns `undefined`\n * rather than a string for `undefined`, a function or a symbol, and throws on a\n * BigInt or a circular object. Any of those is framed as `null` — the event still\n * reaches the client with its id and name, which is what an empty signal is for.\n */\nfunction serialize(data: unknown): string {\n try {\n return JSON.stringify(data) ?? \"null\";\n } catch {\n return \"null\";\n }\n}\n\n/**\n * Format one WHATWG Server-Sent Event frame, terminated by the blank line that\n * ends an event.\n *\n * `data` is always JSON-serialized, strings included (a string payload arrives\n * back through `JSON.parse` as the same string, never half-decoded). JSON escapes\n * newlines, so the body is a single line in practice; every line is prefixed\n * anyway, because an unframed newline would end the event and truncate it.\n *\n * CR and LF are stripped from the event name: it is caller-supplied, and a\n * newline there would inject whole frames onto the wire.\n */\nexport function formatSseEvent(e: BrokerEvent): string {\n const lines = serialize(e.data)\n .split(\"\\n\")\n .map((l) => `data: ${l}\\n`)\n .join(\"\");\n const name = e.event === undefined ? \"\" : `event: ${e.event.replace(/[\\r\\n]/g, \"\")}\\n`;\n return `id: ${e.id}\\n${name}${lines}\\n`;\n}\n","import { type Broker, type BrokerOptions, newBroker, type Unsubscribe } from \"./broker.js\";\nimport { formatSseEvent } from \"./sse.js\";\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\nexport interface PubSubOptions extends BrokerOptions {\n /**\n * When given, only these topic names are served; anything else answers 404.\n * Without it any request path allocates a topic, so an open endpoint should\n * set this.\n */\n topics?: readonly string[];\n /**\n * Interval in ms for `: ping` comment frames, which the SSE parser ignores but\n * which keep a half-open connection visible to proxies. 0 (the default) means\n * no heartbeat: a connection that dies silently is then only noticed when the\n * client's own reconnect timer fires.\n */\n heartbeatMs?: number;\n}\n\nexport interface PubSub {\n handler: FetchHandler;\n publish(topic: string, data: unknown, event?: string): void;\n subscriberCount(topic: string): number;\n /** How many topics currently hold state; a topic with no subscribers and no retained events is dropped. */\n topicCount(): number;\n}\n\n/** The topic is the final non-empty path segment: /_events/build -> \"build\". */\nfunction topicOf(request: Request): string {\n const segments = new URL(request.url).pathname.split(\"/\").filter(Boolean);\n return segments.at(-1) ?? \"\";\n}\n\nexport interface SseSourceOptions {\n /** Replay events after this id; undefined for a fresh subscription. */\n replayFrom?: number;\n /** Send a `gap` before anything else — the client's Last-Event-ID was unusable. */\n forceGap?: boolean;\n /** See {@link PubSubOptions.heartbeatMs}. */\n heartbeatMs?: number;\n}\n\n/**\n * The `ReadableStream` source behind one subscription.\n *\n * Exported so tests can drive it with a controller whose `enqueue` fails, which\n * is the one path a real stream cannot be pushed down from outside.\n */\nexport function createSseSource(\n broker: Broker,\n topic: string,\n { replayFrom, forceGap = false, heartbeatMs = 0 }: SseSourceOptions = {},\n): UnderlyingSource<Uint8Array> {\n const encoder = new TextEncoder();\n let unsubscribe: Unsubscribe | undefined;\n let heartbeat: ReturnType<typeof setInterval> | undefined;\n let broken = false;\n\n return {\n start(controller) {\n /** Tear the subscription down and end the stream, once. */\n const stop = () => {\n if (broken) return;\n broken = true;\n if (heartbeat !== undefined) clearInterval(heartbeat);\n unsubscribe?.();\n unsubscribe = undefined;\n try {\n controller.close();\n } catch {\n // Already closed or errored; nothing left to do.\n }\n };\n\n const write = (frame: () => string) => {\n if (broken) return;\n try {\n // Formatting happens inside the guard: it is given caller data, and a\n // throw here used to escape this catch entirely.\n controller.enqueue(encoder.encode(frame()));\n } catch {\n // The client went away, or the frame could not be produced.\n stop();\n }\n };\n\n // Subscribe first, so the teardown above can release it even if the very\n // first replay frame fails.\n unsubscribe = broker.subscribe(topic, (e) => write(() => formatSseEvent(e)));\n\n if (forceGap || replayFrom !== undefined) {\n const from = replayFrom ?? 0;\n const { events, complete } =\n replayFrom === undefined\n ? { events: [], complete: false }\n : broker.replay(topic, replayFrom);\n // Tell the client its history is incomplete rather than handing it a\n // partial replay that looks whole; it can reload instead of patching.\n if (!complete) write(() => formatSseEvent({ id: from, event: \"gap\", data: { from } }));\n for (const e of events) write(() => formatSseEvent(e));\n }\n\n if (heartbeatMs > 0) {\n heartbeat = setInterval(() => write(() => \": ping\\n\\n\"), heartbeatMs);\n }\n },\n\n cancel() {\n if (heartbeat !== undefined) clearInterval(heartbeat);\n broken = true;\n unsubscribe?.();\n unsubscribe = undefined;\n },\n };\n}\n\nexport function newPubSub(options: PubSubOptions = {}): PubSub {\n const { topics, heartbeatMs, ...brokerOptions } = options;\n const broker = newBroker(brokerOptions);\n const allowed = topics === undefined ? undefined : new Set(topics);\n\n const handler: FetchHandler = async (request) => {\n if (request.method !== \"GET\") {\n return new Response(\"method not allowed\", { status: 405, headers: { allow: \"GET\" } });\n }\n\n const topic = topicOf(request);\n if (topic === \"\" || (allowed !== undefined && !allowed.has(topic))) {\n return new Response(\"no such topic\", { status: 404 });\n }\n\n const header = request.headers.get(\"last-event-id\");\n const parsed = header === null ? Number.NaN : Number(header);\n const usable = header !== null && Number.isSafeInteger(parsed) && parsed >= 0;\n // An id we cannot read is not a fresh client: it had history and lost it, so\n // it gets a gap rather than silence.\n const forceGap = header !== null && !usable;\n\n const stream = new ReadableStream<Uint8Array>(\n createSseSource(broker, topic, {\n ...(usable ? { replayFrom: parsed } : {}),\n forceGap,\n ...(heartbeatMs === undefined ? {} : { heartbeatMs }),\n }),\n );\n\n return new Response(stream, {\n status: 200,\n headers: {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n \"x-accel-buffering\": \"no\", // defeat proxy buffering that would stall delivery\n },\n });\n };\n\n return {\n handler,\n publish: (topic, data, event) => void broker.publish(topic, data, event),\n subscriberCount: (topic) => broker.subscriberCount(topic),\n topicCount: () => broker.topicCount(),\n };\n}\n"],"mappings":";AAgDA,SAAgB,UAAU,EAAE,aAAa,IAAI,sBAAqC,CAAC,GAAW;CAC5F,MAAM,yBAAS,IAAI,IAAwB;CAE3C,MAAM,SAAS,UAA8B;EAC3C,IAAI,IAAI,OAAO,IAAI,KAAK;EACxB,IAAI,CAAC,GAAG;GACN,IAAI;IAAE,QAAQ;IAAG,QAAQ,CAAC;IAAG,6BAAa,IAAI,IAAI;GAAE;GACpD,OAAO,IAAI,OAAO,CAAC;EACrB;EACA,OAAO;CACT;;CAGA,MAAM,SAAS,OAAe,MAAwB;EACpD,IAAI,OAAO,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,S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OAAO,MAAM;EAC3D,MAAM,SAAS,WAAW,QAAQ,OAAO,cAAc,MAAM,KAAK,UAAU;EAG5E,MAAM,WAAW,WAAW,QAAQ,CAAC;EAErC,MAAM,SAAS,IAAI,eACjB,gBAAgB,QAAQ,OAAO;GAC7B,GAAI,SAAS,EAAE,YAAY,OAAO,IAAI,CAAC;GACvC;GACA,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACrD,CAAC,CACH;EAEA,OAAO,IAAI,SAAS,QAAQ;GAC1B,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,iBAAiB;IACjB,YAAY;IACZ,qBAAqB;GACvB;EACF,CAAC;CACH;CAEA,OAAO;EACL;EACA,UAAU,OAAO,MAAM,UAAU,KAAK,OAAO,QAAQ,OAAO,MAAM,KAAK;EACvE,kBAAkB,UAAU,OAAO,gBAAgB,KAAK;EACxD,kBAAkB,OAAO,WAAW;CACtC;AACF"}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@statewalker/webrun-http-events",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Generic publish/subscribe over Server-Sent Events: a standard FetchHandler and a matching client.",
7
+ "license": "MIT",
8
+ "exports": {
9
+ ".": {
10
+ "source": "./src/index.ts",
11
+ "types": "./dist/index.d.mts",
12
+ "import": "./dist/index.mjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src"
18
+ ],
19
+ "devDependencies": {
20
+ "esbuild": "^0.28.2",
21
+ "playwright": "^1.63.0",
22
+ "tsdown": "^0.23.0",
23
+ "typescript": "^7.0.2",
24
+ "vitest": "^5.0.3",
25
+ "@statewalker/webrun-http-browser": "^0.6.3"
26
+ },
27
+ "sideEffects": false,
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "build": "tsdown",
33
+ "test": "pnpm run build && vitest run --passWithNoTests",
34
+ "test:browser": "vitest run test-browser --config vitest.browser.config.ts",
35
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test-browser.json"
36
+ }
37
+ }