@dimchansky/meshpost 0.5.0 → 0.7.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.
Files changed (49) hide show
  1. package/README.md +66 -544
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +44 -45
  6. package/dist/channel.d.ts +4 -0
  7. package/dist/channel.js +19 -44
  8. package/dist/combine.d.ts +9 -2
  9. package/dist/combine.js +40 -57
  10. package/dist/crypto.js +10 -9
  11. package/dist/identity.d.ts +2 -0
  12. package/dist/identity.js +39 -71
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/listeners.js +18 -3
  16. package/dist/mqtt.js +211 -476
  17. package/dist/nostr.js +194 -836
  18. package/dist/peer-link.d.ts +1 -0
  19. package/dist/peer-link.js +983 -0
  20. package/dist/presence.d.ts +1 -0
  21. package/dist/presence.js +74 -0
  22. package/dist/public.d.ts +1 -1
  23. package/dist/public.js +25 -77
  24. package/dist/relay-core.d.ts +1 -0
  25. package/dist/relay-core.js +399 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +115 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +245 -1218
  31. package/dist/rpc.js +25 -28
  32. package/dist/signaling.d.ts +8 -0
  33. package/dist/signaling.js +55 -0
  34. package/dist/state.js +23 -33
  35. package/dist/tabs.js +6 -50
  36. package/dist/voice-mic.d.ts +1 -0
  37. package/dist/voice-mic.js +496 -0
  38. package/dist/voice-remote.d.ts +1 -0
  39. package/dist/voice-remote.js +568 -0
  40. package/dist/voice.d.ts +19 -1
  41. package/dist/voice.js +95 -1036
  42. package/dist/ws.js +56 -197
  43. package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
  44. package/docs/api.md +219 -0
  45. package/docs/behavior.md +14 -8
  46. package/docs/guide.md +404 -0
  47. package/docs/signaling-and-production.md +312 -0
  48. package/docs/voice-and-media.md +193 -0
  49. package/package.json +6 -3
@@ -0,0 +1 @@
1
+ export {};
package/dist/bip340.js ADDED
@@ -0,0 +1,346 @@
1
+ // =============================================================================
2
+ // Pure-TS Zero-Dependency SHA-256 & BIP-340 Schnorr (secp256k1)
3
+ // Lazily initialized so bundlers drop 100% of this module when unused.
4
+ // =============================================================================
5
+ const encoder = new TextEncoder();
6
+ const secpP = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;
7
+ const secpN = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
8
+ const secpGx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n;
9
+ const secpGy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;
10
+ const sqrtExp = (secpP + 1n) >> 2n;
11
+ /** @internal */
12
+ export const hex64Pattern = /^[0-9a-f]{64}$/;
13
+ /** @internal */
14
+ export const hex128Pattern = /^[0-9a-f]{128}$/;
15
+ let cachedSha256K;
16
+ let cachedTagHashes;
17
+ function getSha256K() {
18
+ cachedSha256K ??= new Uint32Array([
19
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
20
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
21
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
22
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
23
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
24
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
25
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
26
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
27
+ ]);
28
+ return cachedSha256K;
29
+ }
30
+ /** @internal */
31
+ export function sha256(data) {
32
+ const K = getSha256K();
33
+ let h0 = 0x6a09e667;
34
+ let h1 = 0xbb67ae85;
35
+ let h2 = 0x3c6ef372;
36
+ let h3 = 0xa54ff53a;
37
+ let h4 = 0x510e527f;
38
+ let h5 = 0x9b05688c;
39
+ let h6 = 0x1f83d9ab;
40
+ let h7 = 0x5be0cd19;
41
+ const len = data.byteLength;
42
+ const paddedLen = (len + 9 + 63) & ~63;
43
+ const padded = new Uint8Array(paddedLen);
44
+ padded.set(data);
45
+ padded[len] = 0x80;
46
+ const dv = new DataView(padded.buffer);
47
+ dv.setUint32(paddedLen - 8, Math.floor(len / 0x20000000) >>> 0, false);
48
+ dv.setUint32(paddedLen - 4, (len << 3) >>> 0, false);
49
+ const w = new Uint32Array(64);
50
+ for (let off = 0; off < paddedLen; off += 64) {
51
+ for (let i = 0; i < 16; i++)
52
+ w[i] = dv.getUint32(off + i * 4, false);
53
+ for (let i = 16; i < 64; i++) {
54
+ const w15 = w[i - 15];
55
+ const w2 = w[i - 2];
56
+ const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
57
+ const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
58
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
59
+ }
60
+ let a = h0;
61
+ let b = h1;
62
+ let c = h2;
63
+ let d = h3;
64
+ let e = h4;
65
+ let f = h5;
66
+ let g = h6;
67
+ let h = h7;
68
+ for (let i = 0; i < 64; i++) {
69
+ const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
70
+ const ch = (e & f) ^ (~e & g);
71
+ const temp1 = (h + S1 + ch + K[i] + w[i]) >>> 0;
72
+ const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
73
+ const maj = (a & b) ^ (a & c) ^ (b & c);
74
+ const temp2 = (S0 + maj) >>> 0;
75
+ h = g;
76
+ g = f;
77
+ f = e;
78
+ e = (d + temp1) >>> 0;
79
+ d = c;
80
+ c = b;
81
+ b = a;
82
+ a = (temp1 + temp2) >>> 0;
83
+ }
84
+ h0 = (h0 + a) >>> 0;
85
+ h1 = (h1 + b) >>> 0;
86
+ h2 = (h2 + c) >>> 0;
87
+ h3 = (h3 + d) >>> 0;
88
+ h4 = (h4 + e) >>> 0;
89
+ h5 = (h5 + f) >>> 0;
90
+ h6 = (h6 + g) >>> 0;
91
+ h7 = (h7 + h) >>> 0;
92
+ }
93
+ const out = new Uint8Array(32);
94
+ const outDv = new DataView(out.buffer);
95
+ outDv.setUint32(0, h0, false);
96
+ outDv.setUint32(4, h1, false);
97
+ outDv.setUint32(8, h2, false);
98
+ outDv.setUint32(12, h3, false);
99
+ outDv.setUint32(16, h4, false);
100
+ outDv.setUint32(20, h5, false);
101
+ outDv.setUint32(24, h6, false);
102
+ outDv.setUint32(28, h7, false);
103
+ return out;
104
+ }
105
+ function getTagHashes() {
106
+ if (!cachedTagHashes) {
107
+ cachedTagHashes = {
108
+ aux: sha256(encoder.encode('BIP0340/aux')),
109
+ nonce: sha256(encoder.encode('BIP0340/nonce')),
110
+ challenge: sha256(encoder.encode('BIP0340/challenge'))
111
+ };
112
+ }
113
+ return cachedTagHashes;
114
+ }
115
+ function taggedHash(tagHash, ...parts) {
116
+ let total = 64;
117
+ for (const p of parts)
118
+ total += p.byteLength;
119
+ const buf = new Uint8Array(total);
120
+ buf.set(tagHash, 0);
121
+ buf.set(tagHash, 32);
122
+ let off = 64;
123
+ for (const p of parts) {
124
+ buf.set(p, off);
125
+ off += p.byteLength;
126
+ }
127
+ return sha256(buf);
128
+ }
129
+ /** @internal */
130
+ export function bytesToHex(bytes) {
131
+ let out = '';
132
+ for (let i = 0; i < bytes.length; i++)
133
+ out += bytes[i].toString(16).padStart(2, '0');
134
+ return out;
135
+ }
136
+ /** @internal */
137
+ export function hexToBytes(hex) {
138
+ const out = new Uint8Array(hex.length >>> 1);
139
+ for (let i = 0; i < out.length; i++) {
140
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
141
+ }
142
+ return out;
143
+ }
144
+ function bytesToBigInt(bytes) {
145
+ let res = 0n;
146
+ for (let i = 0; i < bytes.length; i++)
147
+ res = (res << 8n) | BigInt(bytes[i]);
148
+ return res;
149
+ }
150
+ function bigIntTo32Bytes(num) {
151
+ const out = new Uint8Array(32);
152
+ let n = num;
153
+ for (let i = 31; i >= 0; i--) {
154
+ out[i] = Number(n & 0xffn);
155
+ n >>= 8n;
156
+ }
157
+ return out;
158
+ }
159
+ function modP(a) {
160
+ const r = a % secpP;
161
+ return r >= 0n ? r : r + secpP;
162
+ }
163
+ function modN(a) {
164
+ const r = a % secpN;
165
+ return r >= 0n ? r : r + secpN;
166
+ }
167
+ function modPow(base, exp, m) {
168
+ let res = 1n;
169
+ let b = ((base % m) + m) % m;
170
+ let e = exp;
171
+ while (e > 0n) {
172
+ if ((e & 1n) === 1n)
173
+ res = (res * b) % m;
174
+ b = (b * b) % m;
175
+ e >>= 1n;
176
+ }
177
+ return res;
178
+ }
179
+ function modInvP(a) {
180
+ let t = 0n;
181
+ let newT = 1n;
182
+ let r = secpP;
183
+ let newR = modP(a);
184
+ while (newR !== 0n) {
185
+ const q = r / newR;
186
+ const tmpT = t - q * newT;
187
+ t = newT;
188
+ newT = tmpT;
189
+ const tmpR = r - q * newR;
190
+ r = newR;
191
+ newR = tmpR;
192
+ }
193
+ return t < 0n ? t + secpP : t;
194
+ }
195
+ const jacInfinity = { x: 0n, y: 1n, z: 0n };
196
+ const jacG = { x: secpGx, y: secpGy, z: 1n };
197
+ function pointDouble(p) {
198
+ if (p.z === 0n || p.y === 0n)
199
+ return jacInfinity;
200
+ const y2 = modP(p.y * p.y);
201
+ const s = modP(4n * p.x * y2);
202
+ const m = modP(3n * modP(p.x * p.x));
203
+ const x3 = modP(m * m - 2n * s);
204
+ const y3 = modP(m * (s - x3) - 8n * modP(y2 * y2));
205
+ const z3 = modP(2n * modP(p.y * p.z));
206
+ return { x: x3, y: y3, z: z3 };
207
+ }
208
+ function pointAdd(p, q) {
209
+ if (p.z === 0n)
210
+ return q;
211
+ if (q.z === 0n)
212
+ return p;
213
+ const z1z1 = modP(p.z * p.z);
214
+ const z2z2 = modP(q.z * q.z);
215
+ const u1 = modP(p.x * z2z2);
216
+ const u2 = modP(q.x * z1z1);
217
+ const s1 = modP(p.y * modP(q.z * z2z2));
218
+ const s2 = modP(q.y * modP(p.z * z1z1));
219
+ if (u1 === u2) {
220
+ return s1 !== s2 ? jacInfinity : pointDouble(p);
221
+ }
222
+ const h = modP(u2 - u1);
223
+ const r = modP(s2 - s1);
224
+ const h2 = modP(h * h);
225
+ const h3 = modP(h * h2);
226
+ const u1h2 = modP(u1 * h2);
227
+ const x3 = modP(r * r - h3 - 2n * u1h2);
228
+ const y3 = modP(r * (u1h2 - x3) - modP(s1 * h3));
229
+ const z3 = modP(h * modP(p.z * q.z));
230
+ return { x: x3, y: y3, z: z3 };
231
+ }
232
+ function pointMul(base, scalar) {
233
+ let res = jacInfinity;
234
+ let addend = base;
235
+ let k = scalar;
236
+ while (k > 0n) {
237
+ if ((k & 1n) === 1n)
238
+ res = pointAdd(res, addend);
239
+ addend = pointDouble(addend);
240
+ k >>= 1n;
241
+ }
242
+ return res;
243
+ }
244
+ function toAffine(p) {
245
+ if (p.z === 0n)
246
+ return null;
247
+ const invZ = modInvP(p.z);
248
+ const invZ2 = modP(invZ * invZ);
249
+ const invZ3 = modP(invZ2 * invZ);
250
+ return { x: modP(p.x * invZ2), y: modP(p.y * invZ3) };
251
+ }
252
+ /** @internal */
253
+ export function schnorrPublicKey(secretKey32) {
254
+ if (secretKey32.byteLength !== 32)
255
+ throw new RangeError('Expected 32-byte secret key');
256
+ const d0 = bytesToBigInt(secretKey32);
257
+ if (d0 <= 0n || d0 >= secpN)
258
+ throw new RangeError('Secret key out of range');
259
+ const p = toAffine(pointMul(jacG, d0));
260
+ if (!p)
261
+ throw new Error('Invalid point');
262
+ return bigIntTo32Bytes(p.x);
263
+ }
264
+ /** @internal */
265
+ export function schnorrSign(msg32, secretKey32, auxRand32 = crypto.getRandomValues(new Uint8Array(32))) {
266
+ if (msg32.byteLength !== 32 || secretKey32.byteLength !== 32 || auxRand32.byteLength !== 32) {
267
+ throw new RangeError('Expected 32-byte inputs for BIP-340 schnorrSign');
268
+ }
269
+ const d0 = bytesToBigInt(secretKey32);
270
+ if (d0 <= 0n || d0 >= secpN)
271
+ throw new RangeError('Secret key out of range');
272
+ const p = toAffine(pointMul(jacG, d0));
273
+ if (!p)
274
+ throw new Error('Invalid public point');
275
+ const d = (p.y & 1n) === 0n ? d0 : secpN - d0;
276
+ const pkBytes = bigIntTo32Bytes(p.x);
277
+ const dBytes = bigIntTo32Bytes(d);
278
+ const tags = getTagHashes();
279
+ let aux = auxRand32;
280
+ for (let attempt = 0; attempt < 8; attempt++) {
281
+ const tHash = taggedHash(tags.aux, aux);
282
+ const t = new Uint8Array(32);
283
+ for (let i = 0; i < 32; i++)
284
+ t[i] = dBytes[i] ^ tHash[i];
285
+ const rand = taggedHash(tags.nonce, t, pkBytes, msg32);
286
+ const k0 = bytesToBigInt(rand) % secpN;
287
+ if (k0 === 0n) {
288
+ aux = crypto.getRandomValues(new Uint8Array(32));
289
+ continue;
290
+ }
291
+ const rPoint = toAffine(pointMul(jacG, k0));
292
+ if (!rPoint) {
293
+ aux = crypto.getRandomValues(new Uint8Array(32));
294
+ continue;
295
+ }
296
+ const k = (rPoint.y & 1n) === 0n ? k0 : secpN - k0;
297
+ const rBytes = bigIntTo32Bytes(rPoint.x);
298
+ const e = bytesToBigInt(taggedHash(tags.challenge, rBytes, pkBytes, msg32)) % secpN;
299
+ const s = modN(k + modN(e * d));
300
+ const sig = new Uint8Array(64);
301
+ sig.set(rBytes, 0);
302
+ sig.set(bigIntTo32Bytes(s), 32);
303
+ return sig;
304
+ }
305
+ throw new Error('Failed to derive non-zero BIP-340 nonce');
306
+ }
307
+ /** @internal */
308
+ export function verifySchnorr(sig64, msg32, pubkey32) {
309
+ if (sig64.byteLength !== 64 || msg32.byteLength !== 32 || pubkey32.byteLength !== 32) {
310
+ return false;
311
+ }
312
+ const px = bytesToBigInt(pubkey32);
313
+ if (px >= secpP)
314
+ return false;
315
+ const r = bytesToBigInt(sig64.subarray(0, 32));
316
+ if (r >= secpP)
317
+ return false;
318
+ const s = bytesToBigInt(sig64.subarray(32, 64));
319
+ if (s >= secpN)
320
+ return false;
321
+ const c = modP(modP(px * modP(px * px)) + 7n);
322
+ let py = modPow(c, sqrtExp, secpP);
323
+ if (modP(py * py) !== c)
324
+ return false;
325
+ if ((py & 1n) === 1n)
326
+ py = secpP - py;
327
+ const tags = getTagHashes();
328
+ const e = bytesToBigInt(taggedHash(tags.challenge, sig64.subarray(0, 32), pubkey32, msg32)) % secpN;
329
+ const sG = pointMul(jacG, s);
330
+ const negE = e === 0n ? 0n : secpN - e;
331
+ const negEP = pointMul({ x: px, y: py, z: 1n }, negE);
332
+ const rPoint = toAffine(pointAdd(sG, negEP));
333
+ if (!rPoint || (rPoint.y & 1n) === 1n)
334
+ return false;
335
+ return rPoint.x === r;
336
+ }
337
+ /** @internal */
338
+ export function generateSessionKeypair() {
339
+ for (;;) {
340
+ const sk = crypto.getRandomValues(new Uint8Array(32));
341
+ const d0 = bytesToBigInt(sk);
342
+ if (d0 > 0n && d0 < secpN) {
343
+ return { secretKey: sk, pubkeyHex: bytesToHex(schnorrPublicKey(sk)) };
344
+ }
345
+ }
346
+ }
package/dist/blob.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ListenOptions, Room } from './room.js';
1
+ import { type ListenOptions, type Room } from './room.js';
2
2
  export interface BlobChannelOptions {
3
3
  /** Maximum total bytes accepted for a single incoming blob. @default 4194304 (4 MiB) */
4
4
  maxReceiveBytes?: number;
package/dist/blob.js CHANGED
@@ -1,27 +1,31 @@
1
1
  import { createChannel } from './channel.js';
2
- import { bindAbort, createListeners } from './listeners.js';
2
+ import { bindAbort, createListeners, reportAsyncError } from './listeners.js';
3
+ import { bindRoomLifecycle, isRoomClosed } from './room.js';
3
4
  const opStart = 0x01;
4
5
  const opData = 0x02;
5
6
  const opAbort = 0x03;
6
7
  const startHeaderBytes = 9;
7
8
  const dataHeaderBytes = 5;
8
9
  const abortFrameBytes = 5;
9
- const maxPacketBytes = 16 * 1024;
10
10
  const maxUint32 = 0xffff_ffff;
11
11
  const defaultMaxReceiveBytes = 4 * 1024 * 1024;
12
12
  const defaultChunkSize = 15 * 1024;
13
13
  const defaultReceiveTimeoutMs = 30_000;
14
14
  const defaultMaxConcurrentPerPeer = 4;
15
- const encoder = new TextEncoder();
16
- const listeners = createListeners;
17
15
  /**
18
16
  * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
19
17
  * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
20
18
  */
21
19
  export function createBlobChannel(room, name, options = {}) {
20
+ if (!room ||
21
+ typeof room !== 'object' ||
22
+ typeof room.onDrain !== 'function' ||
23
+ typeof room.onPeerLeave !== 'function' ||
24
+ !Array.isArray(room.peers)) {
25
+ throw new TypeError('Invalid room');
26
+ }
22
27
  const channel = createChannel(room, name, { delivery: 'reliable' });
23
- const nameBytesLen = encoder.encode(name).length;
24
- const maxAllowedChunk = maxPacketBytes - (1 + nameBytesLen) - startHeaderBytes;
28
+ const maxAllowedChunk = channel.maxPayloadBytes - startHeaderBytes;
25
29
  const maxReceiveBytes = options.maxReceiveBytes ?? defaultMaxReceiveBytes;
26
30
  if (!Number.isSafeInteger(maxReceiveBytes) || maxReceiveBytes < 0 || maxReceiveBytes > maxUint32)
27
31
  throw new RangeError('Invalid maxReceiveBytes');
@@ -38,14 +42,23 @@ export function createBlobChannel(room, name, options = {}) {
38
42
  maxConcurrentPerPeer <= 0 ||
39
43
  maxConcurrentPerPeer > 64)
40
44
  throw new RangeError('Invalid maxConcurrentPerPeer');
41
- const blobs = listeners();
42
- const progresses = listeners();
45
+ const blobs = createListeners();
46
+ const progresses = createListeners();
43
47
  const incoming = new Map();
44
48
  const closeWaiters = new Set();
45
- const internalAbort = new AbortController();
46
49
  let nextTransferId = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x7fff_ffff) + 1;
47
- const isRoomClosed = () => room.signalingState === 'closed';
48
- let closed = isRoomClosed();
50
+ const lifecycle = bindRoomLifecycle(room, () => {
51
+ for (const byPeer of incoming.values()) {
52
+ for (const entry of byPeer.values())
53
+ clearTimeout(entry.timer);
54
+ }
55
+ incoming.clear();
56
+ for (const wake of [...closeWaiters])
57
+ wake();
58
+ closeWaiters.clear();
59
+ blobs.clear();
60
+ progresses.clear();
61
+ });
49
62
  const dropTransfer = (peerId, transferId) => {
50
63
  const byPeer = incoming.get(peerId);
51
64
  const entry = byPeer?.get(transferId);
@@ -64,24 +77,8 @@ export function createBlobChannel(room, name, options = {}) {
64
77
  clearTimeout(entry.timer);
65
78
  incoming.delete(peerId);
66
79
  };
67
- const shutdown = () => {
68
- if (closed)
69
- return;
70
- closed = true;
71
- internalAbort.abort();
72
- for (const byPeer of incoming.values()) {
73
- for (const entry of byPeer.values())
74
- clearTimeout(entry.timer);
75
- }
76
- incoming.clear();
77
- for (const wake of [...closeWaiters])
78
- wake();
79
- closeWaiters.clear();
80
- blobs.clear();
81
- progresses.clear();
82
- };
83
80
  const sendAbort = (peerId, transferId) => {
84
- if (isRoomClosed())
81
+ if (isRoomClosed(room))
85
82
  return;
86
83
  const frame = new Uint8Array(abortFrameBytes);
87
84
  const view = new DataView(frame.buffer);
@@ -95,11 +92,11 @@ export function createBlobChannel(room, name, options = {}) {
95
92
  }
96
93
  };
97
94
  const waitForDrain = (peerId, signal) => new Promise((resolve) => {
98
- if (closed || signal?.aborted) {
95
+ if (lifecycle.isClosed() || signal?.aborted) {
99
96
  resolve('abort');
100
97
  return;
101
98
  }
102
- if (isRoomClosed()) {
99
+ if (isRoomClosed(room)) {
103
100
  resolve('unavailable');
104
101
  return;
105
102
  }
@@ -124,15 +121,19 @@ export function createBlobChannel(room, name, options = {}) {
124
121
  done('drain');
125
122
  }, { signal: ctrl.signal });
126
123
  room.onPeerLeave((id) => {
124
+ if (isRoomClosed(room)) {
125
+ lifecycle.close();
126
+ return;
127
+ }
127
128
  if (id === peerId)
128
129
  done('unavailable');
129
130
  }, { signal: ctrl.signal });
130
131
  });
131
132
  const sendToPeer = async (peerId, bytes, options) => {
132
133
  const { onProgress, signal } = options;
133
- if (closed || signal?.aborted)
134
+ if (lifecycle.isClosed() || signal?.aborted)
134
135
  return 'aborted';
135
- if (isRoomClosed())
136
+ if (isRoomClosed(room))
136
137
  return 'unavailable';
137
138
  if (bytes.byteLength > maxUint32)
138
139
  return 'too-large';
@@ -141,12 +142,12 @@ export function createBlobChannel(room, name, options = {}) {
141
142
  let offset = 0;
142
143
  let started = false;
143
144
  while (true) {
144
- if (closed || signal?.aborted) {
145
+ if (lifecycle.isClosed() || signal?.aborted) {
145
146
  if (started)
146
147
  sendAbort(peerId, transferId);
147
148
  return 'aborted';
148
149
  }
149
- if (isRoomClosed())
150
+ if (isRoomClosed(room))
150
151
  return 'unavailable';
151
152
  const isStart = !started;
152
153
  const sliceEnd = Math.min(totalBytes, offset + chunkSize);
@@ -174,7 +175,7 @@ export function createBlobChannel(room, name, options = {}) {
174
175
  onProgress?.(peerId, offset, totalBytes);
175
176
  }
176
177
  catch (error) {
177
- globalThis.reportError?.(error);
178
+ reportAsyncError(error);
178
179
  }
179
180
  if (offset >= totalBytes)
180
181
  return 'sent';
@@ -199,15 +200,11 @@ export function createBlobChannel(room, name, options = {}) {
199
200
  }
200
201
  }
201
202
  };
202
- if (!closed) {
203
- const internalListen = { signal: internalAbort.signal };
203
+ if (!lifecycle.isClosed()) {
204
+ const internalListen = { signal: lifecycle.signal };
204
205
  room.onPeerLeave((peerId) => dropPeerTransfers(peerId), internalListen);
205
- room.onSignalingChange((state) => {
206
- if (state === 'closed')
207
- shutdown();
208
- }, internalListen);
209
206
  channel.onPacket((from, bytes) => {
210
- if (closed || bytes.byteLength < abortFrameBytes)
207
+ if (lifecycle.isClosed() || bytes.byteLength < abortFrameBytes)
211
208
  return;
212
209
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
213
210
  const op = bytes[0];
@@ -290,7 +287,7 @@ export function createBlobChannel(room, name, options = {}) {
290
287
  receivedBytes: entry.receivedBytes,
291
288
  totalBytes: entry.totalBytes
292
289
  });
293
- if (closed || byPeer?.get(transferId) !== entry)
290
+ if (lifecycle.isClosed() || byPeer?.get(transferId) !== entry)
294
291
  return;
295
292
  if (entry.receivedBytes === entry.totalBytes) {
296
293
  dropTransfer(from, transferId);
@@ -305,8 +302,10 @@ export function createBlobChannel(room, name, options = {}) {
305
302
  return {
306
303
  name,
307
304
  async send(bytes, sendOptions = {}) {
308
- if (closed || isRoomClosed())
305
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
306
+ lifecycle.close();
309
307
  throw new Error('BlobChannel is closed');
308
+ }
310
309
  if (!(bytes instanceof Uint8Array))
311
310
  throw new TypeError('Expected a Uint8Array');
312
311
  const targets = sendOptions.to === undefined ? [...room.peers] : [sendOptions.to];
@@ -320,6 +319,6 @@ export function createBlobChannel(room, name, options = {}) {
320
319
  },
321
320
  onBlob: blobs.add,
322
321
  onProgress: progresses.add,
323
- close: shutdown
322
+ close: lifecycle.close
324
323
  };
325
324
  }
package/dist/channel.d.ts CHANGED
@@ -13,6 +13,8 @@ export interface Channel {
13
13
  readonly name: string;
14
14
  /** Delivery mode configured for this channel. */
15
15
  readonly delivery: Delivery;
16
+ /** Maximum usable payload bytes per packet on this channel (`16384 - 1 - utf8(name).length`). */
17
+ readonly maxPayloadBytes: number;
16
18
  /** Send a binary packet on this named channel synchronously. Returns a per-recipient result map. */
17
19
  send(bytes: Uint8Array, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
18
20
  /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
@@ -31,6 +33,8 @@ export interface CodecChannel<T> {
31
33
  readonly name: string;
32
34
  /** Delivery mode configured for this channel. */
33
35
  readonly delivery: Delivery;
36
+ /** Maximum usable encoded payload bytes per packet on this channel (`16384 - 1 - utf8(name).length`). */
37
+ readonly maxPayloadBytes: number;
34
38
  /** Encode and send a typed value synchronously. Returns a per-recipient result map. */
35
39
  send(value: T, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
36
40
  /** Subscribe to decoded, validated values on this channel. Malformed incoming frames are ignored. */
package/dist/channel.js CHANGED
@@ -1,4 +1,5 @@
1
- import { bindAbort } from './listeners.js';
1
+ import { createListeners } from './listeners.js';
2
+ import { maxPacketBytes } from './peer-link.js';
2
3
  import { isRoomClosed, onRoomClose } from './room.js';
3
4
  const encoder = new TextEncoder();
4
5
  const strictDecoder = new TextDecoder('utf-8', { fatal: true });
@@ -50,26 +51,12 @@ function getRouter(room) {
50
51
  const subs = table.byName.get(channelName);
51
52
  if (!subs || subs.size === 0)
52
53
  return;
53
- const payload = bytes.subarray(1 + len);
54
- for (const entry of [...subs]) {
55
- if (!subs.has(entry))
56
- continue;
57
- if (entry.once)
58
- entry.off();
59
- try {
60
- entry.fn(from, payload);
61
- }
62
- catch (error) {
63
- globalThis.reportError?.(error);
64
- }
65
- }
54
+ subs.fire(from, bytes.subarray(1 + len));
66
55
  };
67
56
  const clearAll = () => {
68
57
  for (const table of [unreliable, reliable]) {
69
- for (const subs of [...table.byName.values()]) {
70
- for (const entry of [...subs])
71
- entry.off();
72
- }
58
+ for (const subs of [...table.byName.values()])
59
+ subs.clear();
73
60
  table.byName.clear();
74
61
  table.lengthCounts.fill(0);
75
62
  }
@@ -97,36 +84,21 @@ function getRouter(room) {
97
84
  const table = delivery === 'reliable' ? reliable : unreliable;
98
85
  let subs = table.byName.get(name);
99
86
  if (!subs) {
100
- subs = new Set();
87
+ const group = createListeners(() => {
88
+ activeSubs = Math.max(0, activeSubs - 1);
89
+ if (group.size === 0 && table.byName.get(name) === group) {
90
+ table.byName.delete(name);
91
+ const prevLenCount = table.lengthCounts[nameLen] ?? 0;
92
+ table.lengthCounts[nameLen] = prevLenCount > 0 ? prevLenCount - 1 : 0;
93
+ }
94
+ detachIfIdle();
95
+ });
96
+ subs = group;
101
97
  table.byName.set(name, subs);
102
98
  table.lengthCounts[nameLen] = (table.lengthCounts[nameLen] ?? 0) + 1;
103
99
  }
104
- let removed = false;
105
- let unbindAbort;
106
- const entry = {
107
- fn,
108
- once: Boolean(options?.once),
109
- off() {
110
- if (removed)
111
- return;
112
- removed = true;
113
- unbindAbort?.();
114
- const current = table.byName.get(name);
115
- if (current?.delete(entry)) {
116
- activeSubs = Math.max(0, activeSubs - 1);
117
- if (current.size === 0) {
118
- table.byName.delete(name);
119
- const prevLenCount = table.lengthCounts[nameLen] ?? 0;
120
- table.lengthCounts[nameLen] = prevLenCount > 0 ? prevLenCount - 1 : 0;
121
- }
122
- }
123
- detachIfIdle();
124
- }
125
- };
126
- subs.add(entry);
127
100
  activeSubs++;
128
- unbindAbort = bindAbort(signal, entry.off);
129
- return entry.off;
101
+ return subs.add(fn, options);
130
102
  }
131
103
  };
132
104
  routers.set(room, router);
@@ -205,10 +177,12 @@ export function createChannel(room, name, options = {}) {
205
177
  const prefix = new Uint8Array(1 + nameBytes.length);
206
178
  prefix[0] = nameBytes.length;
207
179
  prefix.set(nameBytes, 1);
180
+ const maxPayloadBytes = maxPacketBytes - prefix.length;
208
181
  const router = getRouter(room);
209
182
  return {
210
183
  name,
211
184
  delivery,
185
+ maxPayloadBytes,
212
186
  send(bytes, sendOptions = {}) {
213
187
  if (!(bytes instanceof Uint8Array))
214
188
  throw new TypeError('Expected a Uint8Array');
@@ -234,6 +208,7 @@ export function createCodecChannel(room, name, codec, options = {}) {
234
208
  return {
235
209
  name: channel.name,
236
210
  delivery: channel.delivery,
211
+ maxPayloadBytes: channel.maxPayloadBytes,
237
212
  send(value, sendOptions = {}) {
238
213
  const bytes = codec.encode(value);
239
214
  if (!(bytes instanceof Uint8Array)) {