@dimchansky/meshpost 0.6.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.
package/dist/rpc.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
2
  import { bindAbort } from './listeners.js';
3
- import { isRoomClosed, onRoomClose } from './room.js';
3
+ import { bindRoomLifecycle, isRoomClosed } from './room.js';
4
4
  /** Error rejected by `rpc.call()` with a structured `code` and target `peerId`. */
5
5
  export class RpcError extends Error {
6
6
  code;
@@ -117,8 +117,6 @@ export function createRpc(room, name, options = {}) {
117
117
  const inFlightByPeer = new Map();
118
118
  let activeHandler;
119
119
  let nextReqId = (Math.random() * 0xffff_ffff) >>> 0;
120
- let closed = isRoomClosed(room);
121
- const internalAbort = new AbortController();
122
120
  const allocateReqId = () => {
123
121
  for (let i = 0; i <= maxPendingCalls; i++) {
124
122
  nextReqId = (nextReqId + 1) >>> 0;
@@ -129,16 +127,6 @@ export function createRpc(room, name, options = {}) {
129
127
  }
130
128
  return 1;
131
129
  };
132
- const sendErrorBestEffort = (to, reqId, errKind, message) => {
133
- if (closed || isRoomClosed(room))
134
- return;
135
- try {
136
- channel.send(buildErrorFrame(reqId, errKind, message), { to });
137
- }
138
- catch {
139
- // Room closed concurrently; ignore.
140
- }
141
- };
142
130
  const settlePending = (reqId, fn) => {
143
131
  const entry = pending.get(reqId);
144
132
  if (!entry)
@@ -147,12 +135,7 @@ export function createRpc(room, name, options = {}) {
147
135
  entry.cleanup();
148
136
  fn(entry);
149
137
  };
150
- const shutdown = () => {
151
- if (closed)
152
- return;
153
- closed = true;
154
- internalAbort.abort();
155
- offRoomClose();
138
+ const lifecycle = bindRoomLifecycle(room, () => {
156
139
  if (activeHandler) {
157
140
  const h = activeHandler;
158
141
  activeHandler = undefined;
@@ -163,11 +146,24 @@ export function createRpc(room, name, options = {}) {
163
146
  entry.reject(new RpcError('closed', entry.peerId, 'RPC endpoint is closed'));
164
147
  });
165
148
  }
149
+ });
150
+ const sendErrorBestEffort = (to, reqId, errKind, message) => {
151
+ if (lifecycle.isClosed() || isRoomClosed(room))
152
+ return;
153
+ try {
154
+ channel.send(buildErrorFrame(reqId, errKind, message), { to });
155
+ }
156
+ catch {
157
+ // Room closed concurrently; ignore.
158
+ }
166
159
  };
167
- const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
168
- if (!closed) {
169
- const internalListen = { signal: internalAbort.signal };
160
+ if (!lifecycle.isClosed()) {
161
+ const internalListen = { signal: lifecycle.signal };
170
162
  room.onPeerLeave((peerId) => {
163
+ if (isRoomClosed(room)) {
164
+ lifecycle.close();
165
+ return;
166
+ }
171
167
  for (const [reqId, entry] of [...pending]) {
172
168
  if (entry.peerId === peerId) {
173
169
  settlePending(reqId, (item) => {
@@ -177,7 +173,7 @@ export function createRpc(room, name, options = {}) {
177
173
  }
178
174
  }, internalListen);
179
175
  channel.onPacket((from, bytes) => {
180
- if (closed || bytes.byteLength < headerBytes)
176
+ if (lifecycle.isClosed() || bytes.byteLength < headerBytes)
181
177
  return;
182
178
  const opcode = bytes[0];
183
179
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -209,7 +205,7 @@ export function createRpc(room, name, options = {}) {
209
205
  void (async () => {
210
206
  try {
211
207
  const result = await handler.fn(from, decodedReq);
212
- if (closed || isRoomClosed(room) || !room.peers.includes(from))
208
+ if (lifecycle.isClosed() || isRoomClosed(room) || !room.peers.includes(from))
213
209
  return;
214
210
  let encodedRes;
215
211
  try {
@@ -230,7 +226,7 @@ export function createRpc(room, name, options = {}) {
230
226
  }
231
227
  }
232
228
  catch (error) {
233
- if (closed || isRoomClosed(room) || !room.peers.includes(from))
229
+ if (lifecycle.isClosed() || isRoomClosed(room) || !room.peers.includes(from))
234
230
  return;
235
231
  const rawMsg = error instanceof Error && error.message ? error.message : 'Remote RPC handler failed';
236
232
  sendErrorBestEffort(from, reqId, errRemote, rawMsg);
@@ -282,7 +278,8 @@ export function createRpc(room, name, options = {}) {
282
278
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > maxTimeoutMs) {
283
279
  return Promise.reject(new RangeError('Invalid RPC timeoutMs'));
284
280
  }
285
- if (closed || isRoomClosed(room)) {
281
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
282
+ lifecycle.close();
286
283
  return Promise.reject(new RpcError('closed', peerId, 'RPC endpoint is closed'));
287
284
  }
288
285
  const signal = callOptions.signal;
@@ -357,7 +354,7 @@ export function createRpc(room, name, options = {}) {
357
354
  if (typeof fn !== 'function')
358
355
  throw new TypeError('Expected an RPC handler function');
359
356
  const signal = listenOptions?.signal;
360
- if (closed || isRoomClosed(room) || signal?.aborted)
357
+ if (lifecycle.isClosed() || isRoomClosed(room) || signal?.aborted)
361
358
  return () => { };
362
359
  if (activeHandler) {
363
360
  throw new Error(`RPC handler already registered for channel "${channel.name}"`);
@@ -380,6 +377,6 @@ export function createRpc(room, name, options = {}) {
380
377
  unbindAbort = bindAbort(signal, entry.off);
381
378
  return entry.off;
382
379
  },
383
- close: shutdown
380
+ close: lifecycle.close
384
381
  };
385
382
  }
package/dist/signaling.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { reportAsyncError } from './listeners.js';
1
2
  /** @internal */
2
3
  export const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3
4
  /** @internal */
@@ -124,16 +125,6 @@ export function withLoopbackFallback(signal) {
124
125
  }
125
126
  return index ? { ...signal, sdp: lines.join(eol) } : signal;
126
127
  }
127
- function reportObserverError(error) {
128
- if (typeof globalThis.reportError === 'function') {
129
- globalThis.reportError(error);
130
- }
131
- else {
132
- queueMicrotask(() => {
133
- throw error;
134
- });
135
- }
136
- }
137
128
  /**
138
129
  * Decorate any `Signaling` adapter to observe per-session `SignalingState` transitions
139
130
  * (`'connecting'`, `'online'`, `'offline'`, `'closed'`) without altering `Room` or `Discovery`.
@@ -159,7 +150,7 @@ export function observeSignaling(adapter, onChange) {
159
150
  onChange(state, reason);
160
151
  }
161
152
  catch (error) {
162
- reportObserverError(error);
153
+ reportAsyncError(error);
163
154
  }
164
155
  };
165
156
  const session = adapter({
package/dist/state.js CHANGED
@@ -1,11 +1,9 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
2
  import { createListeners } from './listeners.js';
3
- import { isRoomClosed, onRoomClose } from './room.js';
3
+ import { bindRoomLifecycle, isRoomClosed } from './room.js';
4
4
  const opSet = 0x01;
5
5
  const opClear = 0x02;
6
6
  const headerBytes = 5;
7
- const maxPacketBytes = 16 * 1024;
8
- const encoder = new TextEncoder();
9
7
  function isNewerSeq(incoming, prev) {
10
8
  if (prev === undefined)
11
9
  return true;
@@ -55,8 +53,7 @@ export function createPeerState(room, name, options = {}) {
55
53
  const liveChannel = delivery === 'unreliable'
56
54
  ? createChannel(room, name, { delivery: 'unreliable' })
57
55
  : reliableChannel;
58
- const nameBytesLen = encoder.encode(name).length;
59
- const maxPayloadBytes = maxPacketBytes - (1 + nameBytesLen) - headerBytes;
56
+ const maxPayloadBytes = reliableChannel.maxPayloadBytes - headerBytes;
60
57
  const encodeValidated = (value) => {
61
58
  if (value === undefined) {
62
59
  throw new TypeError('PeerState value cannot be undefined; call clear() instead');
@@ -86,10 +83,14 @@ export function createPeerState(room, name, options = {}) {
86
83
  const dirtyLive = new Set();
87
84
  const dirtyReliable = new Set();
88
85
  const changes = createListeners();
89
- let closed = isRoomClosed(room);
90
- if (closed)
86
+ const lifecycle = bindRoomLifecycle(room, () => {
91
87
  changes.clear();
92
- const internalAbort = new AbortController();
88
+ peersState.clear();
89
+ lastSeqByPeer.clear();
90
+ dirtyLive.clear();
91
+ dirtyReliable.clear();
92
+ currentFrame = undefined;
93
+ });
93
94
  const nextSeq = () => {
94
95
  localSeq = (localSeq + 1) >>> 0;
95
96
  return localSeq;
@@ -120,7 +121,7 @@ export function createPeerState(room, name, options = {}) {
120
121
  }
121
122
  };
122
123
  const handleFrame = (from, bytes) => {
123
- if (closed || bytes.byteLength < headerBytes || !room.peers.includes(from))
124
+ if (lifecycle.isClosed() || bytes.byteLength < headerBytes || !room.peers.includes(from))
124
125
  return;
125
126
  const op = bytes[0];
126
127
  const seq = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1);
@@ -152,22 +153,8 @@ export function createPeerState(room, name, options = {}) {
152
153
  }
153
154
  }
154
155
  };
155
- const shutdown = () => {
156
- if (closed)
157
- return;
158
- closed = true;
159
- internalAbort.abort();
160
- offRoomClose();
161
- changes.clear();
162
- peersState.clear();
163
- lastSeqByPeer.clear();
164
- dirtyLive.clear();
165
- dirtyReliable.clear();
166
- currentFrame = undefined;
167
- };
168
- const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
169
- if (!closed) {
170
- const internalListen = { signal: internalAbort.signal };
156
+ if (!lifecycle.isClosed()) {
157
+ const internalListen = { signal: lifecycle.signal };
171
158
  reliableChannel.onPacket(handleFrame, internalListen);
172
159
  if (liveChannel !== reliableChannel) {
173
160
  liveChannel.onPacket(handleFrame, internalListen);
@@ -179,6 +166,10 @@ export function createPeerState(room, name, options = {}) {
179
166
  }
180
167
  }, internalListen);
181
168
  room.onPeerLeave((peerId) => {
169
+ if (isRoomClosed(room)) {
170
+ lifecycle.close();
171
+ return;
172
+ }
182
173
  lastSeqByPeer.delete(peerId);
183
174
  dirtyLive.delete(peerId);
184
175
  dirtyReliable.delete(peerId);
@@ -190,7 +181,7 @@ export function createPeerState(room, name, options = {}) {
190
181
  }, internalListen);
191
182
  if (coalesce) {
192
183
  room.onDrain((peerId, mode) => {
193
- if (closed || !currentFrame || !room.peers.includes(peerId)) {
184
+ if (lifecycle.isClosed() || !currentFrame || !room.peers.includes(peerId)) {
194
185
  dirtyLive.delete(peerId);
195
186
  dirtyReliable.delete(peerId);
196
187
  return;
@@ -223,8 +214,8 @@ export function createPeerState(room, name, options = {}) {
223
214
  return new Map(peersState);
224
215
  },
225
216
  set(value) {
226
- if (closed || isRoomClosed(room)) {
227
- shutdown();
217
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
218
+ lifecycle.close();
228
219
  throw new Error('PeerState is closed');
229
220
  }
230
221
  const encoded = encodeValidated(value);
@@ -240,8 +231,8 @@ export function createPeerState(room, name, options = {}) {
240
231
  return results;
241
232
  },
242
233
  clear() {
243
- if (closed || isRoomClosed(room)) {
244
- shutdown();
234
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
235
+ lifecycle.close();
245
236
  throw new Error('PeerState is closed');
246
237
  }
247
238
  const seq = nextSeq();
@@ -254,6 +245,6 @@ export function createPeerState(room, name, options = {}) {
254
245
  return results;
255
246
  },
256
247
  onChange: changes.add,
257
- close: shutdown
248
+ close: lifecycle.close
258
249
  };
259
250
  }
package/dist/tabs.js CHANGED
@@ -1,5 +1,5 @@
1
- import { isSignal, isUuid, namespaceHash } from './signaling.js';
2
- const maxSeenPeers = 256;
1
+ import { createPresenceTracker } from './presence.js';
2
+ import { isUuid, namespaceHash } from './signaling.js';
3
3
  /** Discover tabs in the same origin and storage partition. Carries signaling only. */
4
4
  export function tabSignaling() {
5
5
  return (discovery) => {
@@ -8,7 +8,6 @@ export function tabSignaling() {
8
8
  discovery.room +
9
9
  (discovery.password !== undefined ? ':' + discovery.password : '');
10
10
  const channel = new BroadcastChannel('meshpost/1/' + namespaceHash(scope));
11
- const seen = new Map();
12
11
  let closed = false;
13
12
  const post = (body) => {
14
13
  try {
@@ -18,62 +17,19 @@ export function tabSignaling() {
18
17
  // Ignore asynchronous partition or bfcache restrictions.
19
18
  }
20
19
  };
21
- const roster = () => discovery.roster([...seen.keys()]);
22
- const touch = (id) => {
23
- const known = seen.has(id);
24
- if (!known && seen.size >= maxSeenPeers) {
25
- const oldest = seen.keys().next().value;
26
- if (oldest !== undefined)
27
- seen.delete(oldest);
28
- }
29
- seen.delete(id);
30
- seen.set(id, Date.now());
31
- if (!known)
32
- roster();
33
- return known;
34
- };
20
+ const presence = createPresenceTracker(discovery, (to) => post({ type: 'present', to }));
35
21
  channel.onmessage = ({ data }) => {
36
22
  if (closed || !data || !isUuid(data.from) || data.from === discovery.self)
37
23
  return;
38
24
  if (data.to !== undefined && data.to !== discovery.self)
39
25
  return;
40
- switch (data.type) {
41
- case 'hello':
42
- touch(data.from);
43
- post({ type: 'present', to: data.from });
44
- break;
45
- case 'heartbeat':
46
- if (!touch(data.from))
47
- post({ type: 'present', to: data.from });
48
- break;
49
- case 'present':
50
- touch(data.from);
51
- break;
52
- case 'bye':
53
- if (seen.delete(data.from))
54
- roster();
55
- break;
56
- case 'signal':
57
- if (isSignal(data.signal)) {
58
- touch(data.from);
59
- discovery.receive(data.from, data.signal);
60
- }
61
- break;
62
- }
26
+ presence.dispatch(data);
63
27
  };
64
28
  const timer = setInterval(() => {
65
- let changed = false;
66
- for (const [id, last] of seen) {
67
- if (Date.now() - last > 30_000) {
68
- seen.delete(id);
69
- changed = true;
70
- }
71
- }
72
- if (changed)
73
- roster();
29
+ presence.prune();
74
30
  if (!closed)
75
31
  post({ type: 'heartbeat' });
76
- }, 5000);
32
+ }, 5_000);
77
33
  queueMicrotask(() => {
78
34
  if (closed)
79
35
  return;