r/javascript • • Jun 09 '24

I made River.ts, a Declarative library for defining, emitting & consuming SSE Events in client & server.

https://github.com/Bewinxed/river.ts
0 Upvotes

14 comments sorted by

4

u/[deleted] Jun 09 '24

Why would i need to use this wrapper?

1

u/Bewinxed Jun 09 '24

Custom headers/Methods other than GET & more declarative syntax.

You create an events object then you can use it on both server and client to emit and consume events with proper types.

1

u/guest271314 Jun 09 '24

Interesting. Do you create an EventSource instance on the client after the client makes a POST request? Since EventSource is always a GET request what is your approach here? Are you just using a TransformStream from WHATWG Streams to emulate EventSource server to client without using EventSource?

2

u/Bewinxed Jun 09 '24

Normal fetch then Emulate EventSource via using a body reader and splitting newlines etc assuming the incoming request complies with eventstream format ( which it should). Then placing it into the appropriate place in the return value.

1

u/guest271314 Jun 09 '24

So you're not using EventSource event handlers when making a POST request with fetch()?

The incoming request cannot comply with text/event-stream as that is always a GET request.

I would just use WHATWG Streams for actual streaming requests and use EventSource for text/event-stream. If it works for you in your environment, keep it working.

Technically responding to a EventSource GET request can be done using a ServiceWorker, see https://plnkr.co/edit/qX5tepJ38BuDOSZj?preview

self.addEventListener('fetch', async (e) => {
  try {
    if (e.request.url.includes('index.html')) {
      e.respondWith(
        fetch(e.request.url, {
          cache: 'no-store',
        })
      );
    }

    // Keep ServiceWorker active during stream
    if (e.request.url.split('/').pop() === 'stream') {
      console.log(e.request);
      let { readable, writable } = new TransformStream();
      let writer = writable.getWriter();

      e.respondWith(
        new Response(readable.pipeThrough(new TextEncoderStream()), {
          cache: 'no-store',
          keepalive: true,
          status: 200,
          headers: {
            Connection: 'keep-alive',
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-store',
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Allow-Origin': '*',
          },
        })
      );
      while (true) {
        crypto.getRandomValues(arr);
        await writer.write(
          `event: stream\n` +
            // `retry: 15000\n` +
            `id: ${lastEventId}\n` +
            `data: ${JSON.stringify([...arr])}\n\n`
        );
        ++lastEventId;
        await Promise.race([
          new Promise((resolve) => setTimeout(resolve, 1000)),
          // Interrupt client Request
          abortable,
        ]);
        if (globalThis.gc) {
          gc();
        }
      }
      writer.abort();
    }
  } catch (error) {
    console.log(error || 'EventSource closed in ServiceWorker');
    // Reset interrupt
    interrupt = void 0;
    abortable = new Promise((_) => (interrupt = _));
  }
});

and https://github.com/guest271314/persistent-serviceworker/blob/main/event-source-fetch-event/sw.js#L11-L28

self.addEventListener('fetch', async (event) => {
  if (event.request.url.includes('persistentServiceWorker')) {
    const now = new Date();
    const message =
      `event: persistentServiceWorker\n` +
      `retry: 15000\n` +
      `id: ${id++}\n` +
      `data: {"start":"${start}","now": "${now}", "minutes":"${
        (now - start) / 60000
      }"}\n\n`;
    const blob = new Blob([message], { type: 'text/event-stream' });
    event.respondWith(
      new Response(blob, {
        headers: { 'Content-Type': 'text/event-stream' },
      })
    );
  }
});

1

u/Bewinxed Jun 10 '24

Wow i just woke up and saw this, i appreciate it! I’ll check this and amend it 😮

1

u/Bewinxed Jun 10 '24

Actually yeah would be cool to handle it using a service worker, but the way I respond to the event stream still complies and is recognized by chrome dev tools as an event stream 🤔maybe I should try using ssr.js but I'll review this.

3

u/dbpcut Jun 09 '24

What does it mean to be a Based library?

0

u/Bewinxed Jun 09 '24

2

u/dbpcut Jun 09 '24

Definitely familiar with it, just didn't understand it in this context (like if it was the name of a development group or something.)

Thanks! Definitely interesting, will take a peak. SSE isn't something many people reach for though it's super useful in a few contexts!

1

u/Bewinxed Jun 09 '24

Ah my bad, I’m just proud of it so that’s why i use it for my libs 😄

I like SSE because my needs are usually one way and are easier to set up vs sockets ( which were a pain in regular sveltekit which i work with usually)

3

u/Bewinxed Jun 09 '24

Page on NPM:

https://www.npmjs.com/package/river.ts?activeTab=readme

I made this for my own usage, let me know if you find it helpful :)

The server emitter is tested in Node-based environments, and is based on EventEmitter, I tested it in Sveltekit & Bun.

2

u/ThoorAdam Jun 09 '24

snake_case 🥲

0

u/Xunnamius Jun 09 '24

Interesting! Will give it a look. And nice artwork