blob: c2ce30f179c1061c963f2b659802013297619a25 (
plain) (
blame)
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
|
import type { EventStreamOptions, EventStream as IEventStream } from "bun";
export function getEventStream() {
return class EventStream extends ReadableStream implements IEventStream {
#ctrl: ReadableStreamDirectController | undefined;
constructor(opts?: EventStreamOptions) {
super({
type: "direct",
pull: controller => {
this.#ctrl = controller;
opts?.start?.(this);
},
cancel: () => {
opts?.cancel?.(this);
this.#ctrl = undefined;
},
});
}
send(event?: unknown, data?: unknown): void {
var ctrl = this.#ctrl!;
if (!ctrl) {
throw new Error("EventStream has ended");
}
if (!data) {
data = event;
event = undefined;
} else if (event === "message") {
// According to spec, 'The default event type is "message"'
// This means we can omit this event type.
event = undefined;
}
if (data === undefined) {
throw new TypeError("EventStream.send() requires a data argument");
}
if (typeof data === "string") {
ctrl.write("data: " + data.replace(/\n/g, "\ndata: ") + "\n\n");
} else {
if (event) ctrl.write("event: " + event + "\n");
ctrl.write("data: " + JSON.stringify(data) + "\n\n");
}
ctrl.flush();
}
};
}
|