peerix
Build browser (or Node.js) peer-to-peer apps with Peerix (WebRTC rooms, data channels, media streams, pluggable signaling drivers). Use when writing or debugging code that imports "peerix" — creating a Room, choosing or writing a signaling driver, sending messages or files between peers, sharing camera/screen streams, or writing an Addon.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/meefik--peerix)HTML
<a href="/listings/meefik--peerix"><img src="/api/listings/meefik--peerix/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Install the library:
npm install peerix
Create a room, listen for messages, and join:
import { Room, BroadcastChannelDriver } from "peerix";
const driver = new BroadcastChannelDriver();
const room = new Room({ id: "my-room", driver });
room.on("channel:message", async (e) => {
const message = await e.data;
console.log(`Message from ${e.peer.id}:`, message);
});
await room.join({ name: "Alice" });
room.on("channel:open", (e) => {
e.peer.send("Hello!", { label: e.label });
});
await room.open({ label: "chat" });The room `id` must be the same for all peers that want to connect with each other. `BroadcastChannelDriver` works across tabs in the same browser; see [Signaling Drivers](#signaling-drivers) for cross-device options.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 305 lines
- ---
- name: peerix
- description: Build browser (or Node.js) peer-to-peer apps with Peerix (WebRTC rooms, data channels, media streams, pluggable signaling drivers). Use when writing or debugging code that imports "peerix" — creating a Room, choosing or writing a signaling driver, sending messages or files between peers, sharing camera/screen streams, or writing an Addon.
- license: Apache-2.0
- ---
- # Peerix
- Peerix is a zero-dependency TypeScript library that turns WebRTC into rooms. Peers that join the same room `id` over the same signaling driver discover each other and connect directly. Each pair of peers shares one `RTCPeerConnection` that carries every data channel and media stream. Peerix runs in the browser. Node.js has no WebRTC, so a Node.js peer needs a WebRTC package passed through the `webrtc` room option.
- ```sh
- npm install peerix
- ```
- Everything is exported from the package root: `import { Room, MqttDriver, PeerixError, Addon } from "peerix"`.
- ## Minimal room
- ```js
- import { Room, BroadcastChannelDriver } from "peerix";
- const room = new Room({ id: "my-room", driver: new BroadcastChannelDriver() });
- // Register handlers before join() so no early event is missed.
- room.on("channel:open", (e) => e.peer.send("Hello!", { label: e.label }));
- room.on("channel:message", async (e) => console.log(e.peer.id, await e.data));
- const me = await room.join({ name: "Alice" }); // { id, metadata }, also room.me
- await room.open({ label: "chat" }); // opens "chat" with every current and future peer
- // later
- await room.leave();
- ```
- `join()` while joined or joining resolves with the same peer. Room-wide `open`/`share` calls are remembered and applied to peers that connect later.
- ## Choosing a driver
- The driver is only used for discovery and the initial handshake. After that, peers renegotiate over their own control channel. Every driver except Memory and BroadcastChannel takes a client you create and connect yourself, so install that client library in the app.
- | Driver | Constructor | Client library / backend |
- | --- | --- | --- |
- | `MemoryDriver` | `new MemoryDriver()` | none; one page only (default when `driver` is omitted) |
- | `BroadcastChannelDriver` | `new BroadcastChannelDriver(channelName = "peerix")` | none; tabs of the same origin |
- | `NatsDriver` | `new NatsDriver({ nc, prefix? })` | `@nats-io/nats-core` `wsconnect(...)`; use `noEcho: true` |
- | `MqttDriver` | `new MqttDriver({ client, prefix? })` | `mqtt` `connect("ws://…/mqtt")`; broker needs WebSockets |
- | `CentrifugeDriver` | `new CentrifugeDriver({ centrifuge, prefix? })` | `centrifuge`; call `centrifuge.connect()` |
- | `SupabaseDriver` | `new SupabaseDriver({ supabase, prefix? })` | `@supabase/supabase-js` `createClient(url, key)` (Realtime broadcast) |
- | `NostrDriver` | `new NostrDriver({ relays, prefix?, WebSocket? })` | none; `relays` (`wss://…` URLs) is required, there is no default list. Public relays may throttle ephemeral events |
- | `SocketIoDriver` | `new SocketIoDriver({ socket, prefix?, ackTimeout? })` | `socket.io-client`, plus your own Socket.IO server (below) |
- | `SseDriver` | `new SseDriver({ url?, EventSource?, subscriber?, publisher? })` | Mercure hub or compatible endpoint; `url` defaults to `/.well-known/mercure`; in Node.js pass `EventSource` (e.g. the `eventsource` package) and an absolute `url` |
- `MemoryDriver` and `BroadcastChannelDriver` never reach another device. Use them for tests and demos only.
- A Socket.IO server must relay four events, all with `prefix` prepended verbatim. Include the separator in the prefix, for example `prefix: "peerix:"`:
- ```js
- io.on("connection", (socket) => {
- socket.on("peerix:subscribe", (ns, ack) => { socket.join(ns); ack?.(); });
- socket.on("peerix:unsubscribe", (ns, ack) => { socket.leave(ns); ack?.(); });
- socket.on("peerix:publish", (ns, data, ack) => {
- socket.broadcast.to(ns).emit("peerix:message", ns, data);
- ack?.();
- });
- });
- ```
- ### Driver setup
- Create the client, wait for it to be ready where noted, then pass it in. `prefix` namespaces every topic/channel/subject, so two apps can share one backend. Peers must use the same `prefix` to see each other.
- ```js
- // Memory / BroadcastChannel: nothing to install
- new MemoryDriver();
- new BroadcastChannelDriver("my-app");
- // NATS: needs a server with WebSocket enabled; noEcho stops a peer receiving its own messages
- import { wsconnect } from "@nats-io/nats-core";
- const nc = await wsconnect({ servers: ["wss://demo.nats.io:8443"], noEcho: true });
- new NatsDriver({ nc });
- // MQTT: the broker must listen on WebSockets (e.g. Mosquitto `protocol websockets`)
- import { connect } from "mqtt";
- new MqttDriver({ client: connect("wss://broker.emqx.io:8084/mqtt") });
- // Centrifuge: call connect() yourself
- import { Centrifuge } from "centrifuge";
- const centrifuge = new Centrifuge("ws://localhost:8000/connection/websocket");
- centrifuge.connect();
- new CentrifugeDriver({ centrifuge });
- // Supabase: uses Realtime broadcast channels
- import { createClient } from "@supabase/supabase-js";
- new SupabaseDriver({ supabase: createClient(SUPABASE_URL, SUPABASE_ANON_KEY) });
- // Nostr: no client library; `relays` is required. Prefer relays you run or trust
- new NostrDriver({ relays: ["wss://relay.primal.net", "wss://offchain.pub"] }); // public relays, fine for testing
- // Outside the browser, or to use a custom socket, pass `WebSocket`.
- // Socket.IO: needs the relay server shown above; the prefix must match it
- import { io } from "socket.io-client";
- new SocketIoDriver({ socket: io("http://localhost:8080"), prefix: "peerix:" });
- // SSE: Mercure hub (or the Express stand-in in the TypeDoc); `subscriber` goes to EventSource, `publisher` to fetch
- new SseDriver({
- url: "http://localhost:8080/.well-known/mercure",
- publisher: { headers: { Authorization: `Bearer ${PUBLISHER_JWT}` } },
- });
- ```
- Notes:
- - Each subscribed room holds two namespaces. `SseDriver` opens one HTTP connection per namespace, so serve it over HTTP/2 when a page joins more than two rooms (HTTP/1.1 allows 6 connections per host).
- - `NostrDriver` signs events with a throwaway key and does not verify relay messages. Pair it with Peerix encryption when peers must be authenticated. It reconnects with backoff, pauses rate-limited relays and drops blocked ones.
- - A subscribe fails after 10 s without confirmation on `MqttDriver`, `CentrifugeDriver` and `NostrDriver`, and after 10 s without an open connection on `SseDriver`. `SocketIoDriver` rejects acks after `ackTimeout` (default 10000 ms).
- - A namespace that fails to subscribe or that the server ends is retried with backoff while the driver stays active, and rooms announce themselves again once it is restored.
- - Constructors throw `TypeError` when the client lacks the expected methods, so pass the real client rather than a wrapper.
- - For local testing, the TypeDoc of each driver has a one-line `podman run` for a matching server. `docker run` works the same way.
- ### Custom driver
- Extend `Driver` and implement `subscribe`, `unsubscribe` and `publish`. Keep the `super` calls, because they emit the driver's events. Keep `this.active` in sync with the connection: rooms publish only while the driver is active, and re-announce themselves when it becomes active again. If a single namespace fails, keep the driver active, retry that namespace, and call `this.emit("active")` once it is back so rooms re-announce. `data` is a `number[]` of bytes, so it survives JSON transports. Deliver the same array to the handler on the other side. Several handlers can share a namespace (two rooms with the same ID on one driver), so keep the transport subscription until the last one leaves, and release the client's listeners in `destroy()`.
- ```js
- import { Driver } from "peerix";
- class MyDriver extends Driver {
- #client;
- #handlers = new Map(); // ns -> Set of handlers
- #onConnect = () => (this.active = true);
- #onDisconnect = () => (this.active = false);
- constructor({ client }) {
- super();
- this.#client = client;
- client.on("connect", this.#onConnect);
- client.on("disconnect", this.#onDisconnect);
- this.active = client.connected;
- }
- async subscribe(ns, handler) {
- super.subscribe(ns, handler);
- let handlers = this.#handlers.get(ns);
- if (!handlers) {
- this.#handlers.set(ns, (handlers = new Set()));
- await this.#client.subscribe(ns, (data) =>
- this.#handlers.get(ns)?.forEach((h) => h(data)),
- );
- }
- handlers.add(handler);
- }
- async unsubscribe(ns, handler) {
- super.unsubscribe(ns, handler);
- const handlers = this.#handlers.get(ns);
- if (!handlers?.delete(handler) || handlers.size) return;
- this.#handlers.delete(ns);
- await this.#client.unsubscribe(ns);
- }
- async publish(ns, data) {
- super.publish(ns, data);
- await this.#client.publish(ns, data);
- }
- destroy() {
- super.destroy();
- this.#client.off("connect", this.#onConnect);
- this.#client.off("disconnect", this.#onDisconnect);
- this.#handlers.clear();
- }
- }
- ```
- ## Room options
- ```js
- new Room({
- id: "my-room", // must match on every peer; default "default"
- driver, // default: a shared MemoryDriver
- iceServers: [{ urls: "stun:stun.l.google.com:19302" }], // default []: local network only
- iceTransportPolicy: "all", // "relay" forces TURN
- connectionTimeout: 15000, // ms; 0 disables
- iceCandidateDebounce: 50, // ms to batch candidates
- namespaceHashing: true,
- signalingCompression: true,
- signalingEncryption: true, // all peers in a room must agree
- verify: ({ id, metadata }) => true, // accept or reject a remote peer; may be async, may run more than once
- webrtc: { RTCPeerConnection, MediaStream }, // default: the globals; for Node.js
- });
- ```
- In Node.js, pass `RTCPeerConnection` and `MediaStream` from `@roamhq/wrtc`. Without `MediaStream`, the peer is data-only: `share()` rejects with `MEDIASTREAM_ERROR` and incoming tracks are ignored. The `node-datachannel` polyfill does not work: it never fires `negotiationneeded`.
- In TypeScript, pass the metadata type: `new Room<{ name: string }>(…)`. That types `join()`, `room.me`, `verify` and `peer.metadata`. Remote metadata is untrusted network input, so validate it in `verify`.
- Room properties are `id`, `active`, `me`, `peers` (a `ReadonlyMap<string, Peer>`) and `addons`.
- ## Data channels
- - `room.open(label | ChannelOptions)` and `room.close(label)` act on every peer. `peer.open`/`peer.close` act on one peer. `ChannelOptions` contains `label`, `ordered`, `maxPacketLifeTime`, `maxRetransmits` and `protocol`.
- - `room.send(data, { label, to?, info?, signal? })` broadcasts to every peer whose channel is open and skips peers still connecting. With `to` (an id or an array of ids), it fails before sending anything if any target has no open channel. If a peer fails mid-transfer, the others still get the message, and the send rejects once every transfer ends. `peer.send(data, options)` sends to one peer.
- - `data` can be a string, a JSON-serialisable value, a `Blob`/`File`, an `ArrayBuffer`/typed array, or a `ReadableStream` of bytes. Large payloads are chunked with flow control, and a transfer fails only once the channel buffer stops draining for 10 s, so slow links are fine.
- - `send()` returns a stream of progress updates (`{ id, label, current, total?, done }`) that you can also `await`. Pass `signal` to abort.
- - `info` describes the message, for example a file name. It arrives before the data, must be valid JSON, and must stay under about 16 KB.
- - A channel with a `protocol` is raw, for your own wire format and realtime data such as pointer positions (open it with `ordered: false, maxRetransmits: 0`). `send()` accepts only strings and binary data (no `info`, no streams), passes them straight to the channel with no chunking or acks, and on an unreliable channel silently drops a message while the buffer is backed up. Receivers get `e.raw === true` and `e.data` as the payload itself (`string` or `ArrayBuffer`), not a stream: `room.on("channel:message", (e) => { if (e.raw) draw(new Float32Array(e.data)); })`. Without a protocol, `send()` works only on ordered, reliable channels.
- ```js
- // sender, with progress
- const transfer = room.send(file, { label: "files", info: { name: file.name } });
- for await (const p of transfer) console.log(p.current, p.total);
- // receiver
- room.on("channel:message", async (e) => {
- // e.type is "text" | "json" | "blob" | "bytes"
- if (e.type === "blob") {
- const chunks = [];
- for await (const chunk of e.data) chunks.push(chunk); // stream it...
- save(new File(chunks, e.info?.name));
- } else {
- console.log(await e.data); // ...or await the decoded value. Read e.data only once.
- }
- });
- ```
- Realtime data such as shared cursors uses a raw channel:
- ```js
- room.open({ label: "pointer", protocol: "pointer-v1", ordered: false, maxRetransmits: 0 });
- addEventListener("pointermove", (e) => {
- room.send(new Float32Array([e.clientX / innerWidth, e.clientY / innerHeight]), { label: "pointer" });
- });
- room.on("channel:message", (e) => {
- if (e.label !== "pointer" || !e.raw) return;
- const [x, y] = new Float32Array(e.data);
- moveCursor(e.peer.id, x, y);
- });
- ```
- ## Media streams
- ```js
- const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
- await room.share({
- label: "camera",
- stream,
- videoParameters: { maxBitrate: 500_000, maxFramerate: 30, scaleResolutionDownBy: 1 },
- audioParameters: { maxBitrate: 32_000 },
- });
- room.on("stream:add", (e) => {
- if (!e.peer) return; // local streams fire the same events with no peer
- videoFor(e.peer.id, e.label).srcObject = e.stream;
- });
- room.on("stream:remove", (e) => e.peer && removeVideo(e.peer.id, e.label));
- await room.share({ label: "camera", stream: otherStream }); // same label replaces the tracks
- await room.unshare({ label: "camera" });
- ```
- - By default Peerix stops the tracks it replaces or unshares, and unshares a stream whose tracks have all ended. Pass `managed: true` if the app owns the track lifecycle.
- - `peer.streams` maps labels to the remote streams. `peer.share`/`peer.unshare` target one peer only.
- ## Events
- `room.on(name, handler, { signal? })` and `room.once(...)` return an unsubscribe function, and `room.off(name, handler?)` removes handlers. A group prefix such as `"connection"` matches every event in that group. Handlers run in a microtask after the event, and a throwing handler is reported as an `error` event with code `HANDLER_ERROR`.
- | Event | Payload (besides `name`) |
- | --- | --- |
- | `connection:new` / `:connecting` / `:connected` / `:disconnected` / `:failed` / `:closed` | `peer`, `state` |
- | `channel:new` / `:open` / `:close` | `peer`, `channel`, `label` |
- | `channel:message` | `peer`, `channel`, `label`, `type`, `info?`, `data` (a `ReadableStream<Uint8Array>` you can also await for the decoded value) |
- | `channel:error` | `peer`, `channel`, `label`, `error` |
- | `stream:add` / `stream:remove` | `peer?`, `stream`, `label` |
- | `track:add` / `track:remove` | `peer?`, `stream`, `track`, `label` |
- | `error` | `error` (a `PeerixError`) |
- `disconnected` can recover. `failed` and `closed` are final for that `Peer` object, and a rejoin creates a new one. Peers also expose `on`/`off`/`once` for their own events.
- ## Errors
- Failures are `PeerixError` instances whose `code` is one of `SIGNALING_ERROR`, `NEGOTIATION_ERROR`, `ICECANDIDATE_ERROR`, `MEDIASTREAM_ERROR`, `DATACHANNEL_ERROR`, `HANDLER_ERROR` or `UNKNOWN_ERROR`. Background failures arrive as `room.on("error", ({ error }) => …)`. Calls such as `send` reject or error their stream directly.
- ## Addons
- ```js
- import { Addon } from "peerix";
- class Presence extends Addon {
- async attach(room) { this.off = room.on("connection", (e) => this.emit("change", e)); }
- async detach(room) { this.off?.(); }
- }
- await room.attach(new Presence()); // attaching twice or detaching an unattached addon does nothing
- ```
- - In TypeScript, type the addon's own events with `Addon<{ change: [ConnectionEvent] }>`.
- - Never call `room.attach(this)` or `room.detach(this)` from inside the same addon's `attach` or `detach`. Those calls queue behind the one in progress and deadlock.
- ## Troubleshooting
- - **Peers on different networks never connect:** add STUN servers, and TURN servers for restrictive NATs.
- - **Two peers don't see each other:** check that they use the same room `id`, the same backend and the same `signalingEncryption` setting, and that both called `join()`. BroadcastChannel works within one origin only.
- - **A broadcast misses a peer:** that peer's channel wasn't open yet. Send on `channel:open`, or use `to` to get an error instead of a silent skip.
- - **`SIGNALING_ERROR`:** the driver's client can't reach its backend. The room re-announces itself once the driver becomes active again.
- - **Camera or microphone access fails:** serve the page over HTTPS or from localhost.
- Full API reference: https://peerix.dev
README.md · README · 494 lines
- # Peerix
- Peerix is a TypeScript library for peer-to-peer room-based media and data sharing over WebRTC. It abstracts WebRTC complexity into a simple API, handling peer discovery and connection management through pluggable signaling drivers without vendor lock-in.
- **Try it out**: [Peerix Talk](https://talk.peerix.dev) | [Source](https://github.com/meefik/peerix-talk)
- Read the full documentation and access the source code:
- - 📖 [Documentation](https://peerix.dev)
- - 🧑💻 [Source Code](https://github.com/meefik/peerix)
- - 👾 [Issues](https://github.com/meefik/peerix/issues)
- - 💬 [Discussions](https://github.com/meefik/peerix/discussions)
- ## Features
- - **Pluggable signaling drivers** — MQTT, NATS, SSE, SocketIO, Centrifuge, Supabase, Nostr, BroadcastChannel, Memory — or write your own
- - **Room & state management** out of the box for complex peer-to-peer applications
- - **Single peer connection** — multiplexed media streams and data channels over one RTCPeerConnection
- - **Encryption & compression** of signaling messages between peers (enabled by default)
- - **Zero dependencies**, fully typed, cross-browser compatible
- - **95% branch coverage** enforced in CI
- ## For AI Agents
- Install the Peerix skill to get tailored help when coding with this library:
- ```sh
- npx skills add meefik/peerix
- ```
- ## Quick Start
- Install the library:
- ```sh
- npm install peerix
- ```
- Create a room, listen for messages, and join:
- ```js
- import { Room, BroadcastChannelDriver } from "peerix";
- const driver = new BroadcastChannelDriver();
- const room = new Room({ id: "my-room", driver });
- room.on("channel:message", async (e) => {
- const message = await e.data;
- console.log(`Message from ${e.peer.id}:`, message);
- });
- await room.join({ name: "Alice" });
- room.on("channel:open", (e) => {
- e.peer.send("Hello!", { label: e.label });
- });
- await room.open({ label: "chat" });
- ```
- The room `id` must be the same for all peers that want to connect with each other. `BroadcastChannelDriver` works across tabs in the same browser; see [Signaling Drivers](#signaling-drivers) for cross-device options.
- ## Signaling Drivers
- Drivers handle peer discovery and initial connection setup. After the handshake, each peer connection negotiates its own data channel for signaling, so the external backend is only needed during discovery. Messages use a compact binary format with compression and encryption.
- ### Built-in Drivers
- - **`MemoryDriver`** — single-page testing (no backend required)
- - **`BroadcastChannelDriver`** — multi-tab communication (same browser origin)
- - **`NatsDriver`** — distributed / performance ([NATS](https://nats.io/))
- - **`MqttDriver`** — lightweight broker ([MQTT broker](https://mqtt.org/))
- - **`CentrifugeDriver`** — real-time messaging ([Centrifuge](https://centrifugal.dev/))
- - **`SseDriver`** — Server-Sent Events + POST ([Mercure](https://mercure.rocks/))
- - **`SupabaseDriver`** — database + real-time ([Supabase](https://supabase.com/))
- - **`NostrDriver`** — decentralized relays, bring your own relay list ([Nostr](https://nostr.com/))
- - **`SocketIoDriver`** — WebSocket-based signaling ([Socket.IO](https://socket.io/) server)
- If no driver is specified, the default is `MemoryDriver`, which only works within a single page. Drivers require their respective client libraries to be installed by you — Peerix itself has zero runtime dependencies.
- ### Custom Driver
- Extend `Driver` and implement `subscribe`, `unsubscribe`, and `publish`. This example wraps a generic pub/sub client:
- ```js
- import { Driver } from "peerix";
- class MyDriver extends Driver {
- #client;
- #handlers = new Map(); // namespace -> Set of handlers
- #onConnect = () => (this.active = true);
- #onDisconnect = () => (this.active = false);
- constructor({ client }) {
- super();
- this.#client = client;
- client.on("connect", this.#onConnect);
- client.on("disconnect", this.#onDisconnect);
- this.active = client.connected;
- }
- async subscribe(namespace, handler) {
- super.subscribe(namespace, handler);
- let handlers = this.#handlers.get(namespace);
- if (!handlers) {
- handlers = new Set();
- this.#handlers.set(namespace, handlers);
- // One client subscription per namespace, shared by its handlers.
- await this.#client.subscribe(namespace, (data) => {
- this.#handlers.get(namespace)?.forEach((h) => h(data));
- });
- }
- handlers.add(handler);
- }
- async unsubscribe(namespace, handler) {
- super.unsubscribe(namespace, handler);
- const handlers = this.#handlers.get(namespace);
- if (!handlers?.delete(handler) || handlers.size) return;
- // Another room on this driver may still use the namespace.
- this.#handlers.delete(namespace);
- await this.#client.unsubscribe(namespace);
- }
- async publish(namespace, data) {
- super.publish(namespace, data);
- await this.#client.publish(namespace, data);
- }
- destroy() {
- super.destroy();
- this.#client.off("connect", this.#onConnect);
- this.#client.off("disconnect", this.#onDisconnect);
- this.#handlers.clear();
- }
- }
- ```
- - Set `this.active` to reflect the connection. Messages are only published while the driver is active, and switching back to active makes joined rooms announce themselves again. A namespace that fails on its own shouldn't turn the driver inactive: retry it, and call `this.emit("active")` once it is subscribed again, so that rooms announce themselves to the peers they missed.
- - `data` is the encoded message as an array of byte values (`number[]`), so it survives JSON-based transports. Deliver the same array to the handler on the receiving side.
- - The `super` calls emit the driver's `subscribe`, `unsubscribe`, and `publish` events, as the built-in drivers do.
- - Several handlers may subscribe to the same namespace, for example two rooms with the same ID on one driver, so keep the transport subscription until the last one unsubscribes.
- - Release the client's listeners in `destroy()`.
- ### Example: NATS Driver
- ```js
- import { NatsDriver } from "peerix";
- import { wsconnect } from "@nats-io/nats-core";
- const nc = await wsconnect({
- servers: ["wss://demo.nats.io:8443"],
- noEcho: true,
- });
- const driver = new NatsDriver({ nc });
- ```
- ## Room Configuration
- Create a `Room` and configure connection behavior:
- ```js
- import { Room } from "peerix";
- const room = new Room({
- id: "my-room",
- driver,
- iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
- });
- await room.join();
- ```
- `join()` resolves with the local peer (`{ id, metadata }`), also available as `room.me`. Calling it again while joined or joining resolves with the same peer.
- In TypeScript, pass the metadata type to type `join()`, `room.me`, `verify`, and the metadata of every peer:
- ```ts
- const room = new Room<{ name: string }>({ id: "my-room", driver });
- await room.join({ name: "Alice" });
- room.on("connection:connected", (e) => console.log(e.peer.metadata?.name));
- ```
- Remote metadata comes from the network, so validate it in `verify` before relying on its type.
- ### Options
- - **`id`** — room identifier (default: `"default"`)
- - **`driver`** — signaling driver instance (default: `MemoryDriver`)
- - **`iceServers`** — STUN/TURN servers for NAT traversal (default: `[]`)
- - **`iceTransportPolicy`** — set to `"relay"` to enforce TURN-only connectivity (default: `"all"`)
- - **`connectionTimeout`** — milliseconds before disconnecting failed peers, `0` disables (default: `15000`)
- - **`iceCandidateDebounce`** — milliseconds to batch ICE candidates (default: `50`)
- - **`namespaceHashing`** — hash room namespaces in signaling for privacy (default: `true`)
- - **`signalingCompression`** — compress signaling messages (default: `true`)
- - **`signalingEncryption`** — encrypt signaling between peers with AES-GCM (default: `true`). This hides messages from the signaling backend, but peer IDs are not authenticated, so it doesn't stop a backend that actively impersonates peers
- - **`verify`** — callback to accept or reject incoming peers
- - **`webrtc`** — `RTCPeerConnection` and `MediaStream` classes to use instead of the globals (see [Node.js](#nodejs))
- Peerix handles collision resolution internally when two peers initiate connection simultaneously, using perfect negotiation (polite/impolite peers).
- ### Accessing Peers via `room.peers`
- After joining, connected peers are available through `room.peers`, a read-only `Map<string, Peer>` indexed by peer ID. Each `Peer` exposes:
- - **`id`** — unique identifier (the Map key)
- - **`metadata`** — optional metadata shared at join time
- - **`state`** — connection state (`new`, `connecting`, `connected`, `disconnected`, `failed`, `closed`)
- - **`connection`** — the underlying `RTCPeerConnection`
- - **`send()`** — direct messaging to that peer (bypasses broadcast)
- - **`share()` / `unshare()`** — per-peer stream control
- - **`on()` / `off()`** — subscribe to peer-specific events
- ```js
- // iterate over all connected peers
- for (const [id, peer] of room.peers) {
- if (peer.state === "connected") {
- console.log(`Peer ${id} is online`);
- }
- }
- // look up a specific peer by ID and send directly
- const target = room.peers.get(somePeerId);
- if (target && target.metadata?.name) {
- await target.send(`Hello, ${target.metadata.name}!`, { label: "chat" });
- }
- ```
- ## Data Channels
- Data channels provide reliable messaging between peers. Open a channel with `room.open()`, send messages with `room.send()` (broadcast) or `peer.send()` (direct), and close with `room.close()`:
- ```js
- await room.open({ label: "chat" });
- room.on("channel:message", async (e) => {
- const message = await e.data;
- console.log(`Msg from ${e.peer.id}:`, message);
- });
- ```
- Messages are automatically decoded based on the sender's type: strings, JSON objects, Blobs, or raw bytes. `e.type` tells which one arrived (`"text"`, `"json"`, `"blob"`, or `"bytes"`), so you can handle each kind before reading `e.data`:
- ```js
- room.on("channel:message", async (e) => {
- if (e.type === "blob") showFile(await e.data, e.info);
- else console.log(await e.data);
- });
- ```
- Use `to` to target specific peers instead of broadcasting:
- ```js
- await room.send("Hello!", { label: "chat", to: peer.id });
- ```
- A broadcast goes to every peer whose channel is open and skips peers that are still connecting. A send with `to` fails before anything is sent if any target has no open channel. A peer that fails mid-transfer doesn't stop the others, and the send rejects with its failure once every transfer ends. A transfer to a peer fails once the channel buffer stops draining for 10 seconds, however slow the link. Send failures are `PeerixError` instances with the `DATACHANNEL_ERROR` code.
- ### File Transfer with Progress Tracking
- `send()` returns a stream you can iterate over to track upload progress. On the receiving side, binary data arrives as chunks. Use `info` to describe the message, for example with a file name: it arrives with the first chunk, so the receiver can read it before the data. It is sent as JSON and must be smaller than one chunk (about 16 KB). Peer `metadata`, in contrast, describes a peer for its whole connection.
- ```js
- // sender
- const transfer = room.send(file, {
- label: "chat",
- info: { name: file.name, size: file.size },
- signal: AbortSignal.timeout(60_000),
- });
- for await (const p of transfer) {
- console.log(`${Math.round((p.current / p.total) * 100)}%`);
- }
- ```
- ```js
- // receiver — reassemble file from chunks
- room.on("channel:message", async (e) => {
- const chunks = [];
- for await (const chunk of e.data) chunks.push(chunk);
- const file = new File(chunks, e.info?.name);
- console.log(file);
- });
- ```
- ### Realtime Data (Pointer Positions)
- A channel opened with a `protocol` is raw. Messages skip chunking and acknowledgments, so pairing it with `ordered: false` and `maxRetransmits: 0` suits updates where only the latest value matters, such as shared cursors. `send()` takes only strings and binary data, and on an unreliable channel it drops a message while the buffer is backed up instead of delaying a fresher one. Receivers get `e.raw === true` and `e.data` as the payload itself (`string` or `ArrayBuffer`), not a stream:
- ```js
- await room.open({
- label: "pointer",
- protocol: "pointer-v1",
- ordered: false,
- maxRetransmits: 0,
- });
- // sender — normalized coordinates, 8 bytes per message
- addEventListener("pointermove", (e) => {
- room.send(new Float32Array([e.clientX / innerWidth, e.clientY / innerHeight]), {
- label: "pointer",
- });
- });
- // receiver
- room.on("channel:message", (e) => {
- if (e.label !== "pointer" || !e.raw) return;
- const [x, y] = new Float32Array(e.data);
- moveCursor(e.peer.id, x * innerWidth, y * innerHeight);
- });
- ```
- ## Media Streams
- Share camera, microphone, screen capture, or any `MediaStream` with peers using `room.share()`. Each stream is identified by a label:
- ```js
- const stream = await navigator.mediaDevices.getUserMedia({
- video: true,
- audio: true,
- });
- await room.share({ label: "camera", stream });
- ```
- Listen for stream changes. The room also fires these events for its own streams, with an undefined `peer`, so skip those when handling remote streams:
- ```js
- room.on("stream:add", (e) => {
- if (!e.peer) return; // a local stream
- document.getElementById("remote-video").srcObject = e.stream;
- });
- room.on("stream:remove", (e) => {
- if (!e.peer) return;
- console.log(`${e.peer.id} stopped sharing`);
- });
- ```
- Call `share()` again with the same label to replace a stream. Old tracks are removed and new ones added automatically across all connected peers. Call `unshare()` to stop sharing entirely:
- ```js
- await room.unshare({ label: "camera" });
- ```
- ### Encoding Parameters
- Control codec settings per stream:
- ```js
- await room.share({
- label: "camera",
- stream,
- audioParameters: { maxBitrate: 16_000 },
- videoParameters: { maxBitrate: 128_000, maxFramerate: 15 },
- });
- ```
- ## Addons
- Addons are modular extensions that attach to a Room for additional functionality. Create custom addons by extending `Addon`:
- ```js
- import { Addon } from "peerix";
- class MyAddon extends Addon {
- async attach(room) {
- /* setup */
- }
- async detach(room) {
- /* cleanup */
- }
- }
- const addon = new MyAddon();
- await room.attach(addon);
- // await room.detach(addon); // later, if needed
- ```
- Attaching an addon twice, or detaching one that isn't attached, does nothing. In TypeScript, pass an event map to type the addon's own events, as in `class Presence extends Addon<{ online: [id: string] }> {}`.
- ## Lifecycle Events
- Peerix emits typed events for all state changes. Subscribe using `room.on()` with a group prefix (e.g., `"connection"` matches any connection event) or a specific name:
- #### Connection Events (`connection:*`)
- - **`:new`** — new peer detected
- - **`:connecting`** — negotiation in progress
- - **`:connected`** — peer connection established
- - **`:disconnected`** — peer disconnected (may reconnect)
- - **`:failed`** — connection attempt failed
- - **`:closed`** — connection permanently closed
- #### Channel Events (`channel:*`)
- - **`:new`** — data channel created
- - **`:open`** — channel ready for messaging
- - **`:close`** — channel closed
- - **`:message`** — message received
- - **`:error`** — channel error occurred
- #### Stream Events (`stream:*`)
- - **`:add`** — peer shared a media stream
- - **`:remove`** — peer stopped sharing a stream
- #### Track Events (`track:*`)
- - **`:add`** — track added to a shared stream
- - **`:remove`** — track removed from a stream
- The `"error"` event catches general signaling and connection failures. Subscribe with `room.on("error", ...)`.
- `on()` and `once()` return a function that removes the handler. You can also pass a `signal` so that one `AbortController` removes several handlers at once:
- ```js
- const off = room.on("channel:message", onMessage);
- off();
- const controller = new AbortController();
- room.on("stream:add", onStreamAdd, { signal: controller.signal });
- room.on("stream:remove", onStreamRemove, { signal: controller.signal });
- controller.abort();
- ```
- Handlers run asynchronously, in a microtask after the event is emitted. If a handler throws, the error is reported as an `error` event with the `HANDLER_ERROR` code.
- ## ICE Servers
- STUN servers help peers discover their public address, while TURN servers relay traffic when direct connection is not possible. Use TURN for better connectivity in restrictive networks:
- ```js
- const room = new Room({
- id: "my-room",
- driver,
- iceServers: [
- { urls: "stun:stun.l.google.com:19302" },
- {
- urls: "turn:turn.example.com:3478",
- username: "user",
- credential: "pass",
- },
- ],
- });
- ```
- Set `iceTransportPolicy` to `"relay"` to force traffic through TURN servers only, enforcing privacy in sensitive environments. No ICE servers limits connections to the local network.
- ## Node.js
- Node.js has no built-in WebRTC, so pass the classes from [`@roamhq/wrtc`](https://www.npmjs.com/package/@roamhq/wrtc) through the `webrtc` option to run a peer there:
- ```js
- // npm install @roamhq/wrtc
- import { RTCPeerConnection, MediaStream } from "@roamhq/wrtc";
- import { Room } from "peerix";
- const room = new Room({ id: "my-room", driver, webrtc: { RTCPeerConnection, MediaStream } });
- ```
- Without `MediaStream`, the peer handles data only: `share()` rejects and incoming tracks are ignored. Pick a driver whose client runs in Node.js. The `node-datachannel` polyfill does not work, because it never fires `negotiationneeded`.
- ## Troubleshooting
- **Peers cannot connect across networks.** — Add STUN/TURN servers via `iceServers`.
- **I get a `SIGNALING_ERROR`.** — The driver failed to send or receive messages. Check that your signaling client can reach its backend; the room announces itself again when the driver reconnects. Listen on `room.on("error", ...)` for details.
- **Camera/microphone access fails.** — Ensure the page is served over HTTPS (or localhost). Check that no other tab holds an exclusive lock on the device.
- **A peer doesn't receive a broadcast.** — `room.send()` skips peers whose channel isn't open yet. Wait for the `channel:open` event for that peer. A targeted send (`peer.send(...)` or `room.send(..., { to })`) fails with `DATACHANNEL_ERROR` instead of skipping.
- **Peers disconnect during negotiation.** — Increase `connectionTimeout` (default `15000` ms), or set it to `0` to disable.
- **Two peers in the same room don't see each other.** — Verify both use the same driver connected to the same backend, call `room.join()` on both sides, and that the room `id` matches exactly. BroadcastChannel only works within the same origin.
- **Signaling messages fail after disabling encryption.** — Encryption is enabled by default. If you disable it (`signalingEncryption: false`), all peers in the room must use the same setting.
- ## License
- Copyright (C) 2026 Anton Skshidlevsky (aka meefik)
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
src/drivers/sse.ts · Bundled script · 487 lines · 1 finding marked
- // Signaling driver over Server-Sent Events, publishing via HTTP POST.
- import { Driver } from "#/drivers/driver.js";
- import { EventEmitter } from "#/utils/emitter.js";
- import { Inflight } from "#/utils/inflight.js";
- import { Retries } from "#/utils/retries.js";
- /** How long to wait for a new SSE connection to open, in milliseconds. */
- const CONNECT_TIMEOUT = 10 * 1000;
- // Fixed by the EventSource spec; polyfills don't always expose them statically.
- const OPEN = 1;
- const CLOSED = 2;
- /**
- * Server-Sent Events (SSE) signaling driver.
- *
- * SSE is a unidirectional communication protocol that allows servers to push real-time
- * updates to clients over a single HTTP connection. This driver uses SSE to receive
- * updates from the server. To send messages to the server, it uses standard HTTP POST
- * requests. This protocol can be used as an alternative to WebSocket-based transport.
- * If a connection doesn't open within 10 seconds, subscribing fails. A
- * connection that the browser stops retrying, such as after an HTTP error
- * while the server restarts, is reopened with a backoff of up to 30 seconds.
- *
- * Each subscribed namespace holds its own connection, and a joined room
- * subscribes two. Over HTTP/1.1, browsers allow only 6 connections per host,
- * shared with the publish requests, so serve the endpoint over HTTP/2 (as
- * Mercure does with TLS) when a page joins more than two rooms.
- *
- * ```mermaid
- * sequenceDiagram
- * participant A as Peer A
- * participant S as SSE Server
- * participant B as Peer B
- * A->>S: GET /.well-known/mercure?topic=... (open SSE stream)
- * B->>S: GET /.well-known/mercure?topic=... (open SSE stream)
- * A->>S: POST /.well-known/mercure?topic=... (signal payload)
- * S-->>B: SSE event: data: payload
- * B->>S: POST /.well-known/mercure?topic=... (signal payload)
- * S-->>A: SSE event: data: payload
- * ```
- *
- * > This driver requires a [Mercure](https://mercure.rocks/) server or compatible
- * > server-side implementation to work.
- *
- * In Node.js there is no global `EventSource` or `location`: pass an
- * implementation such as the `eventsource` package as `options.EventSource`,
- * and an absolute `url`.
- *
- * @example
- *
- * Client-side code (browser with SSE support):
- * ```js
- * const publisherJwtKey = "mercure-publisher-jwt-key";
- * const driver = new SseDriver({
- * url: "http://localhost:8080/.well-known/mercure",
- * publisher: {
- * headers: {
- * Authorization: `Bearer ${publisherJwtKey}`,
- * },
- * },
- * });
- * ```
- *
- * You can use this JWT publisher key with the Mercure server's default configuration for testing purposes:
- * ```
- * eyJhbGciOiJIUzI1NiJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdLCJzdWJzY3JpYmUiOlsiKiJdfX0.bVXdlWXwfw9ySx7-iV5OpUSHo34RkjUdVzDLBcc6l_g
- Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
- Line 68 on GitHub
- * ```
- *
- * Running a local Mercure server for testing:
- * ```sh
- * podman run --rm -p 8080:80 \
- * -e SERVER_NAME=':80' \
- * -e MERCURE_PUBLISHER_JWT_KEY='!ChangeThisMercureHubJWTSecretKey!' \
- * -e MERCURE_SUBSCRIBER_JWT_KEY='!ChangeThisMercureHubJWTSecretKey!' \
- * docker.io/dunglas/mercure:latest caddy run --config /etc/caddy/dev.Caddyfile
- * ```
- *
- * Instead of using Mercure, you can use a Node.js server:
- * ```js
- * const express = require("express");
- * const cors = require("cors");
- *
- * const app = express();
- * app.use(express.urlencoded({ extended: true }));
- * app.use(cors({ origin: true, credentials: true }));
- *
- * const namespaces = new Map();
- *
- * // route for outgoing messages (subscribe/stream)
- * app.get("/.well-known/mercure", (req, res) => {
- * const { topic } = req.query;
- * if (!topic) return res.status(400).end();
- * // support multiple topics in a single request
- * const topics = Array.isArray(topic) ? topic : [topic];
- * for (const t of topics) {
- * const clients = namespaces.get(t) || new Set();
- * namespaces.set(t, clients);
- * clients.add(res);
- * }
- * // set headers to establish the SSE stream
- * res.setHeader("Content-Type", "text/event-stream");
- * res.setHeader("Cache-Control", "no-cache");
- * res.setHeader("Connection", "keep-alive");
- * res.flushHeaders();
- * // clean up if the browser closes the page or disconnects
- * req.on("close", () => {
- * for (const t of topics) {
- * const clients = namespaces.get(t);
- * if (clients) {
- * clients.delete(res);
- * if (!clients.size) namespaces.delete(t);
- * }
- * }
- * res.end();
- * });
- * });
- *
- * // route for incoming messages (publish)
- * app.post("/.well-known/mercure", (req, res) => {
- * const { topic, data = "" } = req.body || {};
- * if (topic) {
- * const topics = Array.isArray(topic) ? topic : [topic];
- * for (const t of topics) {
- * const clients = namespaces.get(t);
- * if (clients) {
- * for (const client of clients) {
- * client.write(`data: ${data}\n\n`);
- * }
- * }
- * }
- * }
- * res.status(200).end();
- * });
- *
- * app.listen(8080);
- * ```
- *
- * @category Drivers
- */
- export class SseDriver extends Driver {
- #emitter = new EventEmitter<Record<string, [number[]]>>();
- #eventSources = new Map<string, SseEventSource>();
- #connecting = new Inflight();
- #retries = new Retries();
- #pendingOpens = new Map<SseEventSource, (error: unknown) => void>();
- #openWaiters = new Map<string, Set<(error?: Error) => void>>();
- #destroyed = false;
- #url: string;
- #EventSource: SseEventSourceConstructor;
- #subscriberOptions: EventSourceInit;
- #publisherOptions: RequestInit;
- /**
- * Creates a new instance of the driver.
- *
- * @param options Optional configuration for the driver.
- * @param options.url URL to connect to via SSE. Defaults to "/.well-known/mercure".
- * @param options.EventSource Optional EventSource constructor, such as the
- * `eventsource` package in Node.js. Defaults to the global one.
- * @param options.subscriber Subscriber options for the EventSource instance.
- * @param options.publisher Publisher options for the HTTP requests (fetch).
- * @throws {TypeError} If no EventSource implementation is available.
- */
- constructor(options?: {
- url?: string;
- EventSource?: SseEventSourceConstructor;
- subscriber?: EventSourceInit;
- publisher?: RequestInit;
- }) {
- super();
- const {
- url = "/.well-known/mercure",
- EventSource = globalThis.EventSource,
- subscriber = {},
- publisher = {},
- } = options ?? {};
- if (typeof EventSource !== "function") {
- throw new TypeError("SseDriver requires an EventSource implementation");
- }
- this.#url = url;
- this.#EventSource = EventSource;
- this.#subscriberOptions = subscriber;
- this.#publisherOptions = publisher;
- }
- override async subscribe(
- namespace: string,
- handler: (data: number[]) => void,
- ): Promise<void> {
- if (this.#destroyed) return;
- super.subscribe(namespace, handler);
- // Added before connecting, so an unsubscribe while it is pending keeps
- // the connection for the other subscribers still waiting on it.
- const off = this.#emitter.on(namespace, handler);
- try {
- // Concurrent subscribers share one connection instead of leaking a second.
- await this.#connecting.run(namespace, () => this.#open(namespace));
- } catch (error) {
- off();
- throw error;
- }
- }
- override async unsubscribe(
- namespace: string,
- handler: (data: number[]) => void,
- ): Promise<void> {
- if (this.#destroyed) return;
- super.unsubscribe(namespace, handler);
- this.#emitter.off(namespace, handler);
- if (!this.#emitter.has(namespace)) {
- // A later subscribe must not share the connect of the closed connection.
- this.#connecting.cancel(namespace);
- this.#closeEventSource(namespace);
- }
- }
- override async publish(namespace: string, data: number[]): Promise<void> {
- if (this.#destroyed) return;
- super.publish(namespace, data);
- await this.#send(namespace, data);
- }
- override destroy(): void {
- super.destroy();
- this.#destroyed = true;
- this.#emitter.clear();
- const topics = new Set([
- ...this.#eventSources.keys(),
- ...this.#openWaiters.keys(),
- ]);
- for (const topic of topics) {
- this.#closeEventSource(topic);
- }
- this.#retries.reset();
- }
- /**
- * Builds a request URL for the given topic while preserving any existing
- * query parameters on the configured base URL.
- *
- * @param topic The topic string.
- * @returns The fully qualified request URL.
- * @throws {TypeError} If the URL is relative and there is no `location` (Node.js).
- */
- #makeUrl(topic: string): string {
- // Outside a browser there is no base, so only an absolute URL resolves.
- const url = new URL(this.#url, globalThis.location?.href);
- url.searchParams.append("topic", topic);
- return url.toString();
- }
- /**
- * Checks if any EventSource connection is open. Each topic has its own
- * connection, so one that fails doesn't stop the others from signaling.
- *
- * @returns True if at least one EventSource connection is open.
- */
- #isOpen(): boolean {
- return Array.from(this.#eventSources.values()).some(
- (es) => es.readyState === OPEN,
- );
- }
- /**
- * Opens a connection for the topic, or waits for the one it has to open
- * when it is reconnecting.
- *
- * @param topic The topic string to connect to.
- * @throws Error if the connection doesn't open within 10 seconds or is closed.
- */
- async #open(topic: string): Promise<void> {
- const eventSource = this.#eventSources.get(topic);
- const reconnecting = this.#retries.has(topic);
- if (!eventSource && !reconnecting) return this.#createEventSource(topic);
- if (!reconnecting && eventSource!.readyState === OPEN) return;
- await new Promise<void>((resolve, reject) => {
- const waiters = this.#openWaiters.get(topic) ?? new Set();
- this.#openWaiters.set(topic, waiters);
- const settle = (error?: Error) => {
- clearTimeout(timer);
- waiters.delete(settle);
- if (!waiters.size) this.#openWaiters.delete(topic);
- if (error) reject(error);
- else resolve();
- };
- const timer = setTimeout(() => {
- settle(new Error("SSE connection timed out"));
- }, CONNECT_TIMEOUT);
- waiters.add(settle);
- });
- }
- /**
- * Settles the subscribes waiting for the topic's connection to open.
- *
- * @param topic The topic string.
- * @param error The error to fail them with, if the connection was closed.
- */
- #settleOpenWaiters(topic: string, error?: Error): void {
- for (const settle of [...(this.#openWaiters.get(topic) ?? [])]) {
- settle(error);
- }
- }
- /**
- * Creates a new EventSource connection for the given topic.
- *
- * @param topic The topic string to connect to.
- * @throws Error if the connection fails or doesn't open within 10 seconds.
- */
- async #createEventSource(topic: string): Promise<void> {
- let opened = false;
- await new Promise<void>((resolve, reject) => {
- const eventSource = new this.#EventSource(
- this.#makeUrl(topic),
- this.#subscriberOptions,
- );
- // Drops a connection that never opened, so it doesn't keep the driver inactive.
- const discard = (error: unknown) => {
- clearTimeout(timer);
- this.#pendingOpens.delete(eventSource);
- eventSource.close();
- if (this.#eventSources.get(topic) === eventSource) {
- this.#eventSources.delete(topic);
- }
- // `destroy` discards pending opens, and the driver must stay inactive.
- if (!this.#destroyed) this.active = this.#isOpen();
- reject(error);
- };
- const timer = setTimeout(() => {
- discard(new Error("SSE connection timed out"));
- }, CONNECT_TIMEOUT);
- eventSource.onmessage = (e) => {
- try {
- const data = Array.from(atob(e.data), (char) => char.charCodeAt(0));
- this.#emitter.emit(topic, data);
- } catch (error) {
- this.emit("error", error);
- }
- };
- eventSource.onerror = (event) => {
- // An error event carries no details, and callers expect an `Error`.
- const error = new Error(`SSE connection error: ${topic}`, {
- cause: event,
- });
- // A connection that never opened fails the subscribe, which reports it.
- if (!opened) {
- if (eventSource.readyState === CLOSED) discard(error);
- else if (!this.#isOpen()) this.active = false;
- return;
- }
- this.emit("error", error);
- // EventSource retries a dropped connection by itself, but gives up for
- // good on an HTTP error status, such as a 502 while the server restarts.
- if (
- eventSource.readyState === CLOSED &&
- this.#eventSources.get(topic) === eventSource
- ) {
- this.#reconnect(topic);
- }
- if (!this.#isOpen()) this.active = false;
- };
- eventSource.onopen = () => {
- const reopened = opened || this.#retries.has(topic);
- if (!opened) {
- clearTimeout(timer);
- this.#pendingOpens.delete(eventSource);
- resolve();
- }
- opened = true;
- if (this.#eventSources.get(topic) === eventSource) {
- this.#retries.reset(topic);
- this.#settleOpenWaiters(topic);
- // Rooms announce again on `active`, reaching the peers they missed.
- if (reopened && this.active) this.emit("active");
- }
- this.active = this.#isOpen();
- };
- this.#eventSources.set(topic, eventSource);
- this.#pendingOpens.set(eventSource, discard);
- });
- }
- /**
- * Opens a new EventSource connection for the given topic after a delay,
- * retrying with exponential backoff until it opens or the topic is closed.
- *
- * @param topic The topic string to reconnect.
- */
- #reconnect(topic: string): void {
- this.#retries.schedule(topic, () => {
- this.#createEventSource(topic).catch(() => {
- // Closing the topic resets its retries, which ends them.
- if (this.#retries.has(topic)) this.#reconnect(topic);
- });
- });
- }
- /**
- * Closes the EventSource connection for the given topic and stops reopening it.
- *
- * @param topic The topic string to close the connection for.
- */
- #closeEventSource(topic: string): void {
- const eventSource = this.#eventSources.get(topic);
- const reconnecting = this.#retries.has(topic);
- this.#retries.reset(topic);
- if (eventSource) {
- // close() fires no event, so a connection that is still opening is
- // failed here instead of waiting out the connect timeout.
- this.#pendingOpens.get(eventSource)?.(new Error("SSE connection closed"));
- eventSource.close();
- this.#eventSources.delete(topic);
- }
- // A destroyed driver is already inactive and must not flip back.
- if (!this.#destroyed && (eventSource || reconnecting)) {
- this.active = this.#isOpen();
- }
- this.#settleOpenWaiters(topic, new Error("SSE connection closed"));
- }
- /**
- * Sends data to the server via an HTTP POST request.
- *
- * @param topic The topic string.
- * @param data Optional data to send.
- */
- async #send(topic: string, data: number[]): Promise<void> {
- // Spreading would drop headers given as a `Headers` instance or an array.
- const headers = new Headers(this.#publisherOptions.headers);
- if (!headers.has("Content-Type")) {
- headers.set("Content-Type", "application/x-www-form-urlencoded");
- }
- const res = await fetch(this.#makeUrl(topic), {
- ...this.#publisherOptions,
- method: "POST",
- headers,
- body: new URLSearchParams({
- topic,
- data: btoa(
- data.reduce((acc, byte) => acc + String.fromCharCode(byte), ""),
- ),
- }),
- });
- if (!res.ok) {
- throw new Error(`SSE backend error: ${res.statusText} (${res.status})`);
- }
- }
- }
- /**
- * Minimal EventSource instance used by the driver.
- *
- * @internal
- * @category Drivers
- */
- export interface SseEventSource {
- readyState: number;
- onopen: ((event: any) => void) | null;
- onmessage: ((event: any) => void) | null;
- onerror: ((event: any) => void) | null;
- close(): void;
- }
- /**
- * Constructor of a minimal EventSource.
- *
- * @internal
- * @category Drivers
- */
- export type SseEventSourceConstructor = new (
- url: string,
- init?: EventSourceInit,
- ) => SseEventSource;
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.