@dimchansky/meshpost 0.1.0 → 0.2.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/README.md CHANGED
@@ -76,7 +76,7 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
76
76
  3. Use `createChannel` when your app has multiple message types (so modules do not collide):
77
77
 
78
78
  ```ts
79
- import { createChannel } from './dist/index.js'
79
+ import { createChannel } from '@dimchansky/meshpost'
80
80
 
81
81
  const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
82
82
  const chat = createChannel(room, 'chat', { delivery: 'reliable' })
@@ -95,17 +95,19 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
95
95
 
96
96
  Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
97
97
 
98
- | Adapter | Best for | Server needed? |
99
- | --------------------------- | ------------------------------------------------------------------------------ | ------------------ |
100
- | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
101
- | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
102
- | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
103
- | Custom `Signaling` | Production apps with your own server (such as WebSocket or Server-Sent Events) | Your server |
98
+ | Adapter | Best for | Server needed? |
99
+ | ---------------------------- | ----------------------------------------------------------------------------- | ------------------ |
100
+ | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
101
+ | `wsSignaling(url, options?)` | Production apps with your own WebSocket signaling server (`wss://`) | Your WS server |
102
+ | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
103
+ | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
104
+ | `combineSignaling(...list)` | Composing multiple adapters (e.g. instant local tabs + remote MQTT/WebSocket) | Depends on list |
105
+ | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
104
106
 
105
107
  ### Local tabs (`tabSignaling`)
106
108
 
107
109
  ```ts
108
- import { joinRoom, tabSignaling } from './dist/index.js'
110
+ import { joinRoom, tabSignaling } from '@dimchansky/meshpost'
109
111
 
110
112
  const room = joinRoom('arena', {
111
113
  appId: 'my-game',
@@ -116,7 +118,7 @@ const room = joinRoom('arena', {
116
118
  ### Offline copy-paste (`manualSignaling`)
117
119
 
118
120
  ```ts
119
- import { joinRoom, manualSignaling } from './dist/index.js'
121
+ import { joinRoom, manualSignaling } from '@dimchansky/meshpost'
120
122
 
121
123
  const manual = manualSignaling((toPeerId, replyText) => {
122
124
  // Show replyText to the user to send to `toPeerId`.
@@ -133,7 +135,7 @@ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies he
133
135
  manual.forget(oldPeerId) // Optional: stop retrying an old contact.
134
136
  ```
135
137
 
136
- > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, this also encrypts setup messages. Browsers allow encryption only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()` on `file://` or plain `http://<lan-ip>` throws an error. (`tabSignaling()` and `manualSignaling()` support `password` everywhere.)
138
+ > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, this also encrypts setup messages. Browsers allow encryption only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()` on `file://` or plain `http://<lan-ip>` throws an error. (`tabSignaling()`, `wsSignaling()`, and `manualSignaling()` support `password` everywhere.)
137
139
 
138
140
  ## Public API reference
139
141
 
@@ -157,19 +159,48 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
157
159
 
158
160
  ### `Room`
159
161
 
160
- | Member | Description |
161
- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
162
- | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
163
- | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
164
- | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
165
- | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
166
- | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
167
- | `room.onPacket((from, bytes, delivery) => ...)` | Runs when a packet arrives. Returns an unsubscribe function. |
168
- | `room.onDrain((peerId, delivery) => ...)` | Runs when a full send buffer has space again (after `send()` returned `'busy'`). Returns unsubscribe. |
169
- | `room.onPeerJoin((peerId) => ...)` | Runs when a peer finishes connecting and is ready to exchange packets. Returns unsubscribe. |
170
- | `room.onPeerLeave((peerId) => ...)` | Runs when a connected peer disconnects. Returns unsubscribe. |
171
- | `room.onSignalingChange((state, reason?) => ...)` | Runs on future `signalingState` changes. Returns unsubscribe. |
172
- | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
162
+ | Member | Description |
163
+ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
164
+ | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
165
+ | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
166
+ | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
167
+ | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
168
+ | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
169
+ | `room.onPacket(fn, options?: ListenOptions)` | Runs when a packet arrives (`(from, bytes, delivery) => ...`). Returns an unsubscribe function. |
170
+ | `room.onDrain(fn, options?: ListenOptions)` | Runs when a full send buffer has space again (`(peerId, delivery) => ...`, after `send()` returned `'busy'`). Returns unsubscribe. |
171
+ | `room.onPeerJoin(fn, options?: ListenOptions)` | Runs when a peer finishes connecting and is ready to exchange packets (`(peerId) => ...`). Returns unsubscribe. |
172
+ | `room.onPeerLeave(fn, options?: ListenOptions)` | Runs when a connected peer disconnects (`(peerId) => ...`). Returns unsubscribe. |
173
+ | `room.onSignalingChange(fn, options?: ListenOptions)` | Runs on future `signalingState` changes (`(state, reason?) => ...`). Returns unsubscribe. |
174
+ | `room.onError(fn, options?: ListenOptions)` | Runs on structured room or signaling errors (`(error: RoomError) => ...`, codes `'room-full' \| 'ice-failed' \| 'media-error' \| 'decrypt-failed' \| 'signaling-error'`). Returns unsubscribe. |
175
+ | `room.addStream(stream, to?)` | Attaches a local `MediaStream` (audio/video) to all connected and future peers, or selectively to one peer (`to`). |
176
+ | `room.removeStream(stream, to?)` | Detaches a previously added local `MediaStream` from all peers, or from one peer (`to`). |
177
+ | `room.onPeerStream(fn, options?: ListenOptions)` | Runs when a remote peer adds a `MediaStream` (`(peerId, stream) => ...`). Fires strictly after `onPeerJoin`. Returns unsubscribe. |
178
+ | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream) => ...`). Returns unsubscribe. |
179
+ | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
180
+
181
+ All `on*` methods (on `Room`, `Channel`, and `BlobChannel`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
182
+
183
+ `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
184
+
185
+ #### P2P Voice / MediaStreams
186
+
187
+ ```ts
188
+ const mic = await navigator.mediaDevices.getUserMedia({ audio: true })
189
+ room.addStream(mic) // Broadcast to all current & future peers (or pass peerId as 2nd arg)
190
+
191
+ room.onPeerStream((peerId, stream) => {
192
+ const audio = new Audio()
193
+ audio.srcObject = stream
194
+ audio.play()
195
+ })
196
+ room.onPeerStreamEnd((peerId, stream) => console.log('Stream ended:', peerId, stream.id))
197
+
198
+ // Later: detach from room and stop local microphone tracks yourself.
199
+ room.removeStream(mic)
200
+ for (const track of mic.getTracks()) track.stop()
201
+ ```
202
+
203
+ > **Note:** `removeStream()` does not stop local `MediaStreamTrack`s (call `track.stop()` when done), and streams with 0 tracks or tracks added to a `MediaStream` _after_ `addStream()` are not renegotiated automatically.
173
204
 
174
205
  ### `SendResult`
175
206
 
@@ -201,15 +232,39 @@ Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing
201
232
 
202
233
  - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
203
234
  - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
204
- - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ...) }` (`ChannelSendOptions` is `{ to?: string }`).
235
+ - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
236
+
237
+ ### `createBlobChannel(room, name, options?: BlobChannelOptions)`
238
+
239
+ Creates an opt-in chunked reliable transfer helper for payloads larger than Meshpost's `16,384`-byte packet limit (such as files, images, or large state snapshots). Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
240
+
241
+ - `options` (`BlobChannelOptions`): `{ maxReceiveBytes?, chunkSize?, receiveTimeoutMs?, maxConcurrentPerPeer? }`. Defaults: `4 MiB` max receive, `15 KiB` chunk size, `30 s` receive inactivity timeout, `4` concurrent incoming transfers per peer.
242
+ - Returns a `BlobChannel` with `{ name, send(bytes, options?: BlobSendOptions), onBlob((from, bytes) => ..., options?: ListenOptions), onProgress((from, progress: BlobProgress) => ..., options?: ListenOptions), close() }` where `BlobProgress` is `{ transferId, receivedBytes, totalBytes }`.
243
+ - `send(bytes, { to?, onProgress?: (peerId, sentBytes, totalBytes) => void, signal? })` paces each recipient independently using `room.onDrain` and resolves to `ReadonlyMap<string, BlobSendStatus>` (`'sent' | 'aborted' | 'unavailable' | 'too-large'`).
244
+
245
+ ```ts
246
+ import { createBlobChannel } from '@dimchansky/meshpost'
247
+
248
+ const files = createBlobChannel(room, 'file', { maxReceiveBytes: 8 * 1024 * 1024 })
249
+ files.onProgress((from, { receivedBytes, totalBytes }) =>
250
+ console.log(from, receivedBytes, totalBytes)
251
+ )
252
+ files.onBlob((from, bytes) => console.log('Received', bytes.byteLength, 'bytes from', from))
253
+
254
+ const results = await files.send(fileBytes, {
255
+ onProgress: (peerId, sent, total) => console.log(peerId, sent, total)
256
+ })
257
+ ```
205
258
 
206
259
  ### Signaling exports
207
260
 
208
261
  - `mqttSignaling({ urls?, appId?, password?, handshakeTimeoutMs? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`).
262
+ - `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`). See [docs/behavior.md](docs/behavior.md) and [examples/serve.mjs](examples/serve.mjs) for the minimal JSON server protocol.
263
+ - `combineSignaling(...adapters)` — Combines multiple `Signaling` adapters, merging peer rosters and keeping discovery online as long as any child adapter is online (e.g. `combineSignaling(tabSignaling(), wsSignaling('wss://relay.example/ws'))`).
209
264
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
210
265
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
211
266
  - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
212
- - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `Signal`, `ManualSignaling`, `MqttSignalingOptions`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
267
+ - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `MqttSignalingOptions`, `WsSignalingOptions`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
213
268
 
214
269
  ## Connecting through strict firewalls (TURN)
215
270
 
@@ -251,12 +306,19 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
251
306
 
252
307
  - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` or hosted on a public `https://` origin (such as GitHub Pages).
253
308
  - For completely offline copy-paste exchange with zero network requests, open `dist/playground.html#mode=manual` (or click **Offline mode** on the join screen).
254
- - When hosted on `localhost` or a LAN host without the demo's local `/events` relay server, it automatically falls back to `tabSignaling()` (same-browser tabs only).
309
+ - When hosted on `localhost` or a LAN host without the demo's local `/ws` relay server, it automatically falls back to `tabSignaling()` (same-browser tabs only).
255
310
 
256
311
  ### Read the example code
257
312
 
258
- - [examples/playground/app.js](examples/playground/app.js) — Shows `joinRoom` (with auto-generated password and invite links), `createChannel('pointer')` (unreliable cursor and click ripples, ignoring out-of-order updates), `createChannel('draw')` (reliable collaborative canvas strokes, late-join snapshots, and clear actions), `createChannel('chat')` (group messages), `createChannel('direct')` (private messages to one peer), `createChannel('profile')` (display names without a server), `room.getStats()` (live ping and route tooltips), checking `SendResult`, and manual exchange.
259
- - [examples/playground/relay.js](examples/playground/relay.js) — Shows how to write a custom `Signaling` adapter using Server-Sent Events with a fallback to `tabSignaling()`.
313
+ All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
314
+
315
+ - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade wiring `joinRoom()`, signaling adapters (`combineSignaling`, `mqttSignaling`, `wsSignaling`, `tabSignaling`, `manualSignaling`), `createChannel()` (`pointer`, `draw`, `chat`, `direct`, `profile`), `createBlobChannel()` (`draw-snap`, `file`), `ListenOptions` (`{ signal }`), `room.onError()`, `room.getStats()`, and `room.addStream()` / `onPeerStream()`.
316
+ - [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `wsSignaling()` with a silent fallback to `tabSignaling()` on plain static localhost servers.
317
+ - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs for pointer updates, canvas strokes, and file metadata envelopes.
318
+ - [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
319
+ - [examples/playground/voice.js](examples/playground/voice.js) — Local microphone capture, mute toggle, remote `<audio>` playback, and `AnalyserNode` speaking indicator.
320
+ - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs, `sessionStorage` auto-rejoin, and TURN credential broker fetch.
321
+ - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
260
322
  - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
261
323
  - [examples/turn-worker/](examples/turn-worker/README.md) — Ready-to-deploy Cloudflare Worker template that issues short-lived TURN credentials (supporting Metered Open Relay, Cloudflare Realtime TURN, and self-hosted `coturn`) behind an `Origin` allowlist and shared access key.
262
324
 
@@ -268,7 +330,7 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
268
330
  | `examples/playground/` | Interactive demo source |
269
331
  | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
270
332
  | `examples/build.mjs` | Bundles the playground into one portable HTML file |
271
- | `examples/serve.mjs` | Local dev server with a Server-Sent Events signaling relay |
333
+ | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
272
334
  | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
273
335
  | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
274
336
 
package/dist/blob.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { ListenOptions, Room } from './room.js';
2
+ export interface BlobChannelOptions {
3
+ /** Maximum total bytes accepted for a single incoming blob. @default 4194304 (4 MiB) */
4
+ maxReceiveBytes?: number;
5
+ /** Maximum payload bytes per chunk (must fit within the 16 KiB channel budget). @default 15360 */
6
+ chunkSize?: number;
7
+ /** Inactivity timeout in milliseconds for an incomplete incoming transfer. @default 30000 */
8
+ receiveTimeoutMs?: number;
9
+ /** Maximum simultaneous incoming transfers tracked per peer. @default 4 */
10
+ maxConcurrentPerPeer?: number;
11
+ }
12
+ export interface BlobSendOptions {
13
+ /** Optional target peer ID. Omit to send to all currently connected peers. */
14
+ to?: string;
15
+ /** Optional progress callback invoked per recipient as chunks are accepted. */
16
+ onProgress?: (peerId: string, sentBytes: number, totalBytes: number) => void;
17
+ /** Optional AbortSignal to cancel in-flight sending. */
18
+ signal?: AbortSignal;
19
+ }
20
+ /** Final per-recipient outcome returned by `blobChannel.send()`. */
21
+ export type BlobSendStatus = 'sent' | 'aborted' | 'unavailable' | 'too-large';
22
+ /** Progress snapshot emitted by `blobChannel.onProgress()`. */
23
+ export interface BlobProgress {
24
+ readonly transferId: number;
25
+ readonly receivedBytes: number;
26
+ readonly totalBytes: number;
27
+ }
28
+ /** Chunked reliable binary transfer helper built on top of a Room and Channel. */
29
+ export interface BlobChannel {
30
+ /** Logical channel name. */
31
+ readonly name: string;
32
+ /** Send a Uint8Array of arbitrary size (including 0 bytes). Resolves with per-peer final status. */
33
+ send(bytes: Uint8Array, options?: BlobSendOptions): Promise<ReadonlyMap<string, BlobSendStatus>>;
34
+ /** Subscribe to completed incoming blobs. Returns an unsubscribe function. */
35
+ onBlob(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
36
+ /** Subscribe to incoming transfer progress updates. Returns an unsubscribe function. */
37
+ onProgress(fn: (from: string, progress: BlobProgress) => void, options?: ListenOptions): () => void;
38
+ /** Detach internal room listeners and cancel all active incoming/outgoing transfers. */
39
+ close(): void;
40
+ }
41
+ /**
42
+ * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
43
+ * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
44
+ */
45
+ export declare function createBlobChannel(room: Room, name: string, options?: BlobChannelOptions): BlobChannel;
package/dist/blob.js ADDED
@@ -0,0 +1,364 @@
1
+ import { createChannel } from './channel.js';
2
+ const opStart = 0x01;
3
+ const opData = 0x02;
4
+ const opAbort = 0x03;
5
+ const startHeaderBytes = 9;
6
+ const dataHeaderBytes = 5;
7
+ const abortFrameBytes = 5;
8
+ const maxPacketBytes = 16 * 1024;
9
+ const maxUint32 = 0xffff_ffff;
10
+ const defaultMaxReceiveBytes = 4 * 1024 * 1024;
11
+ const defaultChunkSize = 15 * 1024;
12
+ const defaultReceiveTimeoutMs = 30_000;
13
+ const defaultMaxConcurrentPerPeer = 4;
14
+ const encoder = new TextEncoder();
15
+ function listeners() {
16
+ const entries = new Set();
17
+ let closed = false;
18
+ return {
19
+ add(fn, options) {
20
+ const signal = options?.signal;
21
+ if (closed || signal?.aborted)
22
+ return () => { };
23
+ const entry = {
24
+ fn,
25
+ once: Boolean(options?.once),
26
+ off() {
27
+ if (!entries.delete(entry))
28
+ return;
29
+ signal?.removeEventListener('abort', entry.off);
30
+ }
31
+ };
32
+ entries.add(entry);
33
+ signal?.addEventListener('abort', entry.off, { once: true });
34
+ return entry.off;
35
+ },
36
+ fire(...args) {
37
+ for (const entry of [...entries]) {
38
+ if (!entries.has(entry))
39
+ continue;
40
+ if (entry.once)
41
+ entry.off();
42
+ try {
43
+ entry.fn(...args);
44
+ }
45
+ catch (error) {
46
+ globalThis.reportError?.(error);
47
+ }
48
+ }
49
+ },
50
+ clear() {
51
+ closed = true;
52
+ for (const entry of [...entries])
53
+ entry.off();
54
+ }
55
+ };
56
+ }
57
+ /**
58
+ * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
59
+ * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
60
+ */
61
+ export function createBlobChannel(room, name, options = {}) {
62
+ const channel = createChannel(room, name, { delivery: 'reliable' });
63
+ const nameBytesLen = encoder.encode(name).length;
64
+ const maxAllowedChunk = maxPacketBytes - (1 + nameBytesLen) - startHeaderBytes;
65
+ const maxReceiveBytes = options.maxReceiveBytes ?? defaultMaxReceiveBytes;
66
+ if (!Number.isSafeInteger(maxReceiveBytes) || maxReceiveBytes < 0 || maxReceiveBytes > maxUint32)
67
+ throw new RangeError('Invalid maxReceiveBytes');
68
+ const chunkSize = options.chunkSize ?? Math.min(defaultChunkSize, maxAllowedChunk);
69
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0 || chunkSize > maxAllowedChunk)
70
+ throw new RangeError(`chunkSize must be 1..${maxAllowedChunk}`);
71
+ const receiveTimeoutMs = options.receiveTimeoutMs ?? defaultReceiveTimeoutMs;
72
+ if (!Number.isSafeInteger(receiveTimeoutMs) ||
73
+ receiveTimeoutMs <= 0 ||
74
+ receiveTimeoutMs > 2_147_483_647)
75
+ throw new RangeError('Invalid receiveTimeoutMs');
76
+ const maxConcurrentPerPeer = options.maxConcurrentPerPeer ?? defaultMaxConcurrentPerPeer;
77
+ if (!Number.isSafeInteger(maxConcurrentPerPeer) ||
78
+ maxConcurrentPerPeer <= 0 ||
79
+ maxConcurrentPerPeer > 64)
80
+ throw new RangeError('Invalid maxConcurrentPerPeer');
81
+ const blobs = listeners();
82
+ const progresses = listeners();
83
+ const incoming = new Map();
84
+ const closeWaiters = new Set();
85
+ const internalAbort = new AbortController();
86
+ let nextTransferId = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x7fff_ffff) + 1;
87
+ const isRoomClosed = () => room.signalingState === 'closed';
88
+ let closed = isRoomClosed();
89
+ const dropTransfer = (peerId, transferId) => {
90
+ const byPeer = incoming.get(peerId);
91
+ const entry = byPeer?.get(transferId);
92
+ if (!entry)
93
+ return;
94
+ clearTimeout(entry.timer);
95
+ byPeer.delete(transferId);
96
+ if (byPeer.size === 0)
97
+ incoming.delete(peerId);
98
+ };
99
+ const dropPeerTransfers = (peerId) => {
100
+ const byPeer = incoming.get(peerId);
101
+ if (!byPeer)
102
+ return;
103
+ for (const entry of byPeer.values())
104
+ clearTimeout(entry.timer);
105
+ incoming.delete(peerId);
106
+ };
107
+ const shutdown = () => {
108
+ if (closed)
109
+ return;
110
+ closed = true;
111
+ internalAbort.abort();
112
+ for (const byPeer of incoming.values()) {
113
+ for (const entry of byPeer.values())
114
+ clearTimeout(entry.timer);
115
+ }
116
+ incoming.clear();
117
+ for (const wake of [...closeWaiters])
118
+ wake();
119
+ closeWaiters.clear();
120
+ blobs.clear();
121
+ progresses.clear();
122
+ };
123
+ const sendAbort = (peerId, transferId) => {
124
+ if (isRoomClosed())
125
+ return;
126
+ const frame = new Uint8Array(abortFrameBytes);
127
+ const view = new DataView(frame.buffer);
128
+ frame[0] = opAbort;
129
+ view.setUint32(1, transferId);
130
+ try {
131
+ channel.send(frame, { to: peerId });
132
+ }
133
+ catch {
134
+ // Ignore errors if room closed concurrently.
135
+ }
136
+ };
137
+ const waitForDrain = (peerId, signal) => new Promise((resolve) => {
138
+ if (closed || signal?.aborted) {
139
+ resolve('abort');
140
+ return;
141
+ }
142
+ if (isRoomClosed()) {
143
+ resolve('unavailable');
144
+ return;
145
+ }
146
+ const ctrl = new AbortController();
147
+ let settled = false;
148
+ const done = (outcome) => {
149
+ if (settled)
150
+ return;
151
+ settled = true;
152
+ ctrl.abort();
153
+ closeWaiters.delete(onClose);
154
+ signal?.removeEventListener('abort', onAbort);
155
+ resolve(outcome);
156
+ };
157
+ const onClose = () => done('abort');
158
+ const onAbort = () => done('abort');
159
+ closeWaiters.add(onClose);
160
+ signal?.addEventListener('abort', onAbort, { once: true });
161
+ room.onDrain((id, delivery) => {
162
+ if (id === peerId && delivery === 'reliable')
163
+ done('drain');
164
+ }, { signal: ctrl.signal });
165
+ room.onPeerLeave((id) => {
166
+ if (id === peerId)
167
+ done('unavailable');
168
+ }, { signal: ctrl.signal });
169
+ });
170
+ const sendToPeer = async (peerId, bytes, options) => {
171
+ const { onProgress, signal } = options;
172
+ if (closed || signal?.aborted)
173
+ return 'aborted';
174
+ if (isRoomClosed())
175
+ return 'unavailable';
176
+ if (bytes.byteLength > maxUint32)
177
+ return 'too-large';
178
+ const transferId = ++nextTransferId >>> 0;
179
+ const totalBytes = bytes.byteLength;
180
+ let offset = 0;
181
+ let started = false;
182
+ while (true) {
183
+ if (closed || signal?.aborted) {
184
+ if (started)
185
+ sendAbort(peerId, transferId);
186
+ return 'aborted';
187
+ }
188
+ if (isRoomClosed())
189
+ return 'unavailable';
190
+ const isStart = !started;
191
+ const sliceEnd = Math.min(totalBytes, offset + chunkSize);
192
+ const slice = bytes.subarray(offset, sliceEnd);
193
+ const headerLen = isStart ? startHeaderBytes : dataHeaderBytes;
194
+ const frame = new Uint8Array(headerLen + slice.byteLength);
195
+ const view = new DataView(frame.buffer);
196
+ frame[0] = isStart ? opStart : opData;
197
+ view.setUint32(1, transferId);
198
+ if (isStart)
199
+ view.setUint32(5, totalBytes);
200
+ frame.set(slice, headerLen);
201
+ let result;
202
+ try {
203
+ result = channel.send(frame, { to: peerId });
204
+ }
205
+ catch {
206
+ return 'unavailable';
207
+ }
208
+ const status = result.get(peerId);
209
+ if (status === 'accepted') {
210
+ started = true;
211
+ offset = sliceEnd;
212
+ try {
213
+ onProgress?.(peerId, offset, totalBytes);
214
+ }
215
+ catch (error) {
216
+ globalThis.reportError?.(error);
217
+ }
218
+ if (offset >= totalBytes)
219
+ return 'sent';
220
+ }
221
+ else if (status === 'busy') {
222
+ const outcome = await waitForDrain(peerId, signal);
223
+ if (outcome === 'abort') {
224
+ if (started)
225
+ sendAbort(peerId, transferId);
226
+ return 'aborted';
227
+ }
228
+ if (outcome === 'unavailable')
229
+ return 'unavailable';
230
+ }
231
+ else if (status === 'too-large') {
232
+ if (started)
233
+ sendAbort(peerId, transferId);
234
+ return 'too-large';
235
+ }
236
+ else {
237
+ return 'unavailable';
238
+ }
239
+ }
240
+ };
241
+ if (!closed) {
242
+ const internalListen = { signal: internalAbort.signal };
243
+ room.onPeerLeave((peerId) => dropPeerTransfers(peerId), internalListen);
244
+ room.onSignalingChange((state) => {
245
+ if (state === 'closed')
246
+ shutdown();
247
+ }, internalListen);
248
+ channel.onPacket((from, bytes) => {
249
+ if (closed || bytes.byteLength < abortFrameBytes)
250
+ return;
251
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
252
+ const op = bytes[0];
253
+ const transferId = view.getUint32(1);
254
+ if (op === opAbort) {
255
+ dropTransfer(from, transferId);
256
+ return;
257
+ }
258
+ if (op === opStart) {
259
+ if (bytes.byteLength < startHeaderBytes)
260
+ return;
261
+ const totalBytes = view.getUint32(5);
262
+ const payload = bytes.subarray(startHeaderBytes);
263
+ if (totalBytes > maxReceiveBytes || payload.byteLength > totalBytes)
264
+ return;
265
+ const existingByPeer = incoming.get(from);
266
+ if (existingByPeer?.has(transferId))
267
+ return;
268
+ if (payload.byteLength === totalBytes) {
269
+ if (totalBytes > 0) {
270
+ progresses.fire(from, { transferId, receivedBytes: totalBytes, totalBytes });
271
+ }
272
+ blobs.fire(from, payload.slice());
273
+ return;
274
+ }
275
+ if (existingByPeer && existingByPeer.size >= maxConcurrentPerPeer)
276
+ return;
277
+ const initialCap = Math.min(totalBytes, Math.max(payload.byteLength, 16 * 1024));
278
+ const buffer = new Uint8Array(initialCap);
279
+ if (payload.byteLength > 0)
280
+ buffer.set(payload, 0);
281
+ const timer = setTimeout(() => dropTransfer(from, transferId), receiveTimeoutMs);
282
+ const entry = {
283
+ totalBytes,
284
+ maxFrames: Math.ceil(totalBytes / 256) + 64,
285
+ receivedBytes: payload.byteLength,
286
+ frames: 1,
287
+ buffer,
288
+ timer
289
+ };
290
+ let byPeer = existingByPeer;
291
+ if (!byPeer) {
292
+ byPeer = new Map();
293
+ incoming.set(from, byPeer);
294
+ }
295
+ byPeer.set(transferId, entry);
296
+ if (entry.receivedBytes > 0) {
297
+ progresses.fire(from, { transferId, receivedBytes: entry.receivedBytes, totalBytes });
298
+ }
299
+ return;
300
+ }
301
+ if (op === opData) {
302
+ if (bytes.byteLength <= dataHeaderBytes)
303
+ return;
304
+ const byPeer = incoming.get(from);
305
+ const entry = byPeer?.get(transferId);
306
+ if (!entry)
307
+ return;
308
+ const payload = bytes.subarray(dataHeaderBytes);
309
+ entry.frames++;
310
+ if (entry.frames > entry.maxFrames ||
311
+ entry.receivedBytes + payload.byteLength > entry.totalBytes) {
312
+ dropTransfer(from, transferId);
313
+ return;
314
+ }
315
+ const needed = entry.receivedBytes + payload.byteLength;
316
+ if (needed > entry.buffer.byteLength) {
317
+ let nextCap = entry.buffer.byteLength;
318
+ while (nextCap < needed)
319
+ nextCap = Math.min(entry.totalBytes, nextCap * 2);
320
+ const grown = new Uint8Array(nextCap);
321
+ grown.set(entry.buffer.subarray(0, entry.receivedBytes), 0);
322
+ entry.buffer = grown;
323
+ }
324
+ entry.buffer.set(payload, entry.receivedBytes);
325
+ entry.receivedBytes = needed;
326
+ clearTimeout(entry.timer);
327
+ progresses.fire(from, {
328
+ transferId,
329
+ receivedBytes: entry.receivedBytes,
330
+ totalBytes: entry.totalBytes
331
+ });
332
+ if (closed || byPeer?.get(transferId) !== entry)
333
+ return;
334
+ if (entry.receivedBytes === entry.totalBytes) {
335
+ dropTransfer(from, transferId);
336
+ blobs.fire(from, entry.buffer);
337
+ }
338
+ else {
339
+ entry.timer = setTimeout(() => dropTransfer(from, transferId), receiveTimeoutMs);
340
+ }
341
+ }
342
+ }, internalListen);
343
+ }
344
+ return {
345
+ name,
346
+ async send(bytes, sendOptions = {}) {
347
+ if (closed || isRoomClosed())
348
+ throw new Error('BlobChannel is closed');
349
+ if (!(bytes instanceof Uint8Array))
350
+ throw new TypeError('Expected a Uint8Array');
351
+ const targets = sendOptions.to === undefined ? [...room.peers] : [sendOptions.to];
352
+ const results = new Map();
353
+ if (targets.length === 0)
354
+ return results;
355
+ await Promise.all(targets.map(async (peerId) => {
356
+ results.set(peerId, await sendToPeer(peerId, bytes, sendOptions));
357
+ }));
358
+ return results;
359
+ },
360
+ onBlob: blobs.add,
361
+ onProgress: progresses.add,
362
+ close: shutdown
363
+ };
364
+ }
package/dist/channel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Delivery, Room, SendResult } from './room.js';
1
+ import type { Delivery, ListenOptions, Room, SendResult } from './room.js';
2
2
  export interface ChannelOptions {
3
3
  /** Delivery mode for this logical channel. @default 'unreliable' */
4
4
  delivery?: Delivery;
@@ -16,7 +16,7 @@ export interface Channel {
16
16
  /** Send a binary packet on this named channel synchronously. Returns a per-recipient result map. */
17
17
  send(bytes: Uint8Array, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
18
18
  /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
19
- onPacket(fn: (from: string, bytes: Uint8Array) => void): () => void;
19
+ onPacket(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
20
20
  }
21
21
  /**
22
22
  * Create a named logical channel multiplexed over a Room's existing data channels.
package/dist/channel.js CHANGED
@@ -28,16 +28,24 @@ export function createChannel(room, name, options = {}) {
28
28
  framed.set(bytes, prefix.length);
29
29
  return room.send(framed, sendOptions.to === undefined ? { delivery } : { to: sendOptions.to, delivery });
30
30
  },
31
- onPacket(fn) {
32
- return room.onPacket((from, bytes, mode) => {
31
+ onPacket(fn, options) {
32
+ if (options?.signal?.aborted)
33
+ return () => { };
34
+ const once = Boolean(options?.once);
35
+ const roomOptions = options?.signal ? { signal: options.signal } : undefined;
36
+ let off = () => { };
37
+ off = room.onPacket((from, bytes, mode) => {
33
38
  if (mode !== delivery || bytes.byteLength < prefix.length)
34
39
  return;
35
40
  for (let i = 0; i < prefix.length; i++) {
36
41
  if (bytes[i] !== prefix[i])
37
42
  return;
38
43
  }
44
+ if (once)
45
+ off();
39
46
  fn(from, bytes.subarray(prefix.length));
40
- });
47
+ }, roomOptions);
48
+ return off;
41
49
  }
42
50
  };
43
51
  }