aboutsummaryrefslogtreecommitdiff
path: root/src/js/builtins/EventStream.ts
blob: c9d574836e9215fdef1aaf3e4b0c39faa45179ef (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
47
48
49
50
51
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;
        },
      });
      $putByIdDirectPrivate(this, "contentType", "text/event-stream");
    }

    send(event?: unknown, data?: unknown): void {
      var ctrl = this.#ctrl!;
      if (!ctrl) {
        throw new Error("EventStream is closed");
      }
      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();
    }

    close() {
      this.#ctrl?.close();
    }
  };
}