@nolag/signal 1.0.0 → 1.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.
@@ -0,0 +1,932 @@
1
+ /**
2
+ * Tiny typed event emitter — framework-agnostic base for NoLag SDKs.
3
+ *
4
+ * EventMap is a record of event name → tuple of handler arguments.
5
+ */
6
+ class EventEmitter {
7
+ constructor() {
8
+ this._handlers = new Map();
9
+ }
10
+ on(event, handler) {
11
+ if (!this._handlers.has(event)) {
12
+ this._handlers.set(event, new Set());
13
+ }
14
+ this._handlers.get(event).add(handler);
15
+ return this;
16
+ }
17
+ off(event, handler) {
18
+ if (handler) {
19
+ this._handlers.get(event)?.delete(handler);
20
+ }
21
+ else {
22
+ this._handlers.delete(event);
23
+ }
24
+ return this;
25
+ }
26
+ removeAllListeners() {
27
+ this._handlers.clear();
28
+ return this;
29
+ }
30
+ emit(event, ...args) {
31
+ const handlers = this._handlers.get(event);
32
+ if (!handlers)
33
+ return;
34
+ for (const handler of handlers) {
35
+ try {
36
+ handler(...args);
37
+ }
38
+ catch (e) {
39
+ console.error(`Error in ${String(event)} handler:`, e);
40
+ }
41
+ }
42
+ }
43
+ listenerCount(event) {
44
+ return this._handlers.get(event)?.size ?? 0;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Maps actorTokenId ↔ Peer, filtering self.
50
+ */
51
+ class PeerManager {
52
+ constructor(localActorId) {
53
+ this._peers = new Map();
54
+ this._actorToPeerId = new Map();
55
+ this._localActorId = localActorId;
56
+ }
57
+ /**
58
+ * Add or update a peer from presence data.
59
+ * Returns the Peer if it's a remote peer, null if it's self.
60
+ */
61
+ addFromPresence(actorTokenId, presence, joinedAt) {
62
+ const isLocal = actorTokenId === this._localActorId;
63
+ // Skip self
64
+ if (isLocal)
65
+ return null;
66
+ const existing = this._actorToPeerId.get(actorTokenId);
67
+ const peerId = presence.peerId || existing || actorTokenId;
68
+ const peer = {
69
+ peerId,
70
+ actorTokenId,
71
+ connectionState: 'new',
72
+ metadata: presence.metadata,
73
+ joinedAt: joinedAt || Date.now(),
74
+ isLocal: false,
75
+ };
76
+ this._peers.set(peerId, peer);
77
+ this._actorToPeerId.set(actorTokenId, peerId);
78
+ return peer;
79
+ }
80
+ /**
81
+ * Remove a peer by actorTokenId.
82
+ * Returns the removed peer, or null if not found / is self.
83
+ */
84
+ removeByActorId(actorTokenId) {
85
+ if (actorTokenId === this._localActorId)
86
+ return null;
87
+ const peerId = this._actorToPeerId.get(actorTokenId);
88
+ if (!peerId)
89
+ return null;
90
+ const peer = this._peers.get(peerId) || null;
91
+ this._peers.delete(peerId);
92
+ this._actorToPeerId.delete(actorTokenId);
93
+ return peer;
94
+ }
95
+ /**
96
+ * Get a peer by peerId.
97
+ */
98
+ getPeer(peerId) {
99
+ return this._peers.get(peerId);
100
+ }
101
+ /**
102
+ * Get a peer by actorTokenId.
103
+ */
104
+ getPeerByActorId(actorTokenId) {
105
+ const peerId = this._actorToPeerId.get(actorTokenId);
106
+ return peerId ? this._peers.get(peerId) : undefined;
107
+ }
108
+ /**
109
+ * Get all remote peers.
110
+ */
111
+ getAll() {
112
+ return Array.from(this._peers.values());
113
+ }
114
+ /**
115
+ * Get the peers Map (readonly view).
116
+ */
117
+ get peers() {
118
+ return this._peers;
119
+ }
120
+ /**
121
+ * Clear all tracked peers.
122
+ */
123
+ clear() {
124
+ this._peers.clear();
125
+ this._actorToPeerId.clear();
126
+ }
127
+ }
128
+
129
+ function generateId() {
130
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
131
+ return crypto.randomUUID();
132
+ }
133
+ return 'xxxx-xxxx-xxxx-xxxx'.replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
134
+ }
135
+ function createLogger(prefix, enabled) {
136
+ if (!enabled) {
137
+ return (..._args) => { };
138
+ }
139
+ return (...args) => {
140
+ console.log(`[${prefix}]`, ...args);
141
+ };
142
+ }
143
+ // ============ Filters ============
144
+ /**
145
+ * Build the filter fragment of an emit options object.
146
+ *
147
+ * `filter` wins over `filters`: a publish is routed to exactly one topic, so
148
+ * honouring both would silently drop one of them.
149
+ */
150
+ function filterEmitOptions(opts) {
151
+ if (opts?.filter)
152
+ return { filter: opts.filter };
153
+ if (opts?.filters && opts.filters.length > 0)
154
+ return { filters: opts.filters };
155
+ return {};
156
+ }
157
+ /**
158
+ * Merge OR terms into an existing filter set. AND groups (nested arrays) are
159
+ * preserved as-is — only plain string terms are deduplicated.
160
+ */
161
+ function mergeFilters(existing, add) {
162
+ const simple = new Set();
163
+ const groups = [];
164
+ for (const f of existing) {
165
+ if (typeof f === 'string')
166
+ simple.add(f);
167
+ else
168
+ groups.push(f);
169
+ }
170
+ for (const v of add)
171
+ simple.add(v);
172
+ return [...simple, ...groups];
173
+ }
174
+ /**
175
+ * Drop OR terms from a filter set. AND groups are left untouched — remove
176
+ * those by calling `setFilters` with the set you want.
177
+ */
178
+ function withoutFilters(existing, remove) {
179
+ const drop = new Set(remove);
180
+ return existing.filter((f) => typeof f !== 'string' || !drop.has(f));
181
+ }
182
+ // ============ Wrapper registry ============
183
+ // One wrapper instance per (client, appName): two wrappers sharing an app on
184
+ // one connection would collide on topics, presence and the online lobby.
185
+ // Warn (not throw): HMR and tests legitimately construct before disposing.
186
+ const wrapperRegistry = new WeakMap();
187
+ /** Register a wrapper against a client + appName; warns on collision. */
188
+ function registerWrapper(client, appName, wrapperName) {
189
+ let apps = wrapperRegistry.get(client);
190
+ if (!apps) {
191
+ apps = new Map();
192
+ wrapperRegistry.set(client, apps);
193
+ }
194
+ const existing = apps.get(appName);
195
+ if (existing) {
196
+ console.warn(`[${wrapperName}] Another wrapper (${existing}) is already attached to this client for app "${appName}". ` +
197
+ `Use one wrapper per (client, app) — detach the other instance first.`);
198
+ }
199
+ apps.set(appName, wrapperName);
200
+ }
201
+ /** Release a wrapper's (client, appName) registration on detach. */
202
+ function releaseWrapper(client, appName) {
203
+ wrapperRegistry.get(client)?.delete(appName);
204
+ }
205
+
206
+ /** Default app name for NoLag signal SDK */
207
+ const DEFAULT_APP_NAME = 'signal';
208
+ /** Topic name for signaling messages within a room */
209
+ const TOPIC_SIGNALING = 'signaling';
210
+ /** Lobby ID for global online presence */
211
+ const LOBBY_ID = 'online';
212
+ /** Delay before the post-setup lobby presence refetch (catches simultaneous joiners) */
213
+ const LOBBY_REFRESH_DELAY_MS = 2000;
214
+
215
+ /**
216
+ * SignalRoom — a single signaling room for WebRTC peer discovery and exchange.
217
+ *
218
+ * Created via `NoLagSignal.joinRoom(name)`. Do not instantiate directly.
219
+ */
220
+ class SignalRoom extends EventEmitter {
221
+ /** @internal */
222
+ constructor(name, roomContext, localPeer, options, log, isConnected) {
223
+ super();
224
+ // Stored topic handler ref — cleanup removes exactly this, never all
225
+ // handlers for a topic (the client may be shared with other consumers).
226
+ this._onSignalingRef = null;
227
+ /** Filter values applied to the signaling subscription. */
228
+ this._filters = [];
229
+ this.name = name;
230
+ this._roomContext = roomContext;
231
+ this._localPeer = localPeer;
232
+ this._options = options;
233
+ this._log = log;
234
+ this._isConnected = isConnected;
235
+ this._peerManager = new PeerManager(localPeer.actorTokenId);
236
+ }
237
+ // ============ Public Properties ============
238
+ /** All remote peers currently in this room */
239
+ get peers() {
240
+ return this._peerManager.peers;
241
+ }
242
+ // ============ Signaling ============
243
+ /**
244
+ * Send an SDP offer to a specific peer.
245
+ */
246
+ sendOffer(toPeerId, offer, opts) {
247
+ this.signal(toPeerId, 'offer', offer, opts);
248
+ }
249
+ /**
250
+ * Send an SDP answer to a specific peer.
251
+ */
252
+ sendAnswer(toPeerId, answer, opts) {
253
+ this.signal(toPeerId, 'answer', answer, opts);
254
+ }
255
+ /**
256
+ * Send an ICE candidate to a specific peer.
257
+ */
258
+ sendIceCandidate(toPeerId, candidate, opts) {
259
+ this.signal(toPeerId, 'ice-candidate', candidate, opts);
260
+ }
261
+ /**
262
+ * Send a bye signal to a specific peer (graceful close).
263
+ */
264
+ sendBye(toPeerId, opts) {
265
+ this.signal(toPeerId, 'bye', {}, opts);
266
+ }
267
+ /**
268
+ * Send a generic signal message to a specific peer.
269
+ *
270
+ * By default this broadcasts to the room and peers discard messages not
271
+ * addressed to them. Pass `{ filter: toPeerId }` to have the server do the
272
+ * addressing instead, so the signal is only delivered to that peer.
273
+ */
274
+ signal(toPeerId, type, payload, opts) {
275
+ const message = {
276
+ id: generateId(),
277
+ type,
278
+ fromPeerId: this._localPeer.peerId,
279
+ toPeerId,
280
+ payload,
281
+ timestamp: Date.now(),
282
+ };
283
+ this._log('Sending signal:', type, '→', toPeerId);
284
+ this._roomContext.emit(TOPIC_SIGNALING, message, { echo: false, ...filterEmitOptions(opts) });
285
+ }
286
+ // ============ Filters ============
287
+ /** This peer's own id — the value to filter on to receive directed signals. */
288
+ get localPeerId() {
289
+ return this._localPeer.peerId;
290
+ }
291
+ /** The filter values currently applied to this room's signaling. */
292
+ get filters() {
293
+ return [...this._filters];
294
+ }
295
+ /**
296
+ * Replace this room's signaling filters — only signals published with one of
297
+ * these values are delivered. Set your own peerId to receive only signals
298
+ * addressed to you, and send with `{ filter: toPeerId }` so the server does
299
+ * the addressing rather than every peer discarding other peers' traffic.
300
+ *
301
+ * A filtered peer stops receiving unfiltered room broadcasts, so switch the
302
+ * whole room over together. Passing an empty array restores the wildcard
303
+ * subscription, which receives everything.
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * room.setFilters([room.localPeerId]); // only signals addressed to me
308
+ * room.setFilters([]); // back to room broadcast
309
+ * ```
310
+ */
311
+ setFilters(values) {
312
+ this._filters = [...values];
313
+ // The core types filters as `string[]`, but both its implementation and
314
+ // the wire protocol accept AND groups (nested arrays).
315
+ this._roomContext.setFilters(TOPIC_SIGNALING, this._filters);
316
+ }
317
+ /** Add filter values to the existing set. Existing AND groups are kept. */
318
+ addFilters(values) {
319
+ this.setFilters(mergeFilters(this._filters, values));
320
+ }
321
+ /**
322
+ * Remove filter values from the existing set. Removing the last value
323
+ * restores the wildcard subscription.
324
+ */
325
+ removeFilters(values) {
326
+ this.setFilters(withoutFilters(this._filters, values));
327
+ }
328
+ // ============ Peers ============
329
+ /**
330
+ * Get all remote peers in this room.
331
+ */
332
+ getPeers() {
333
+ return this._peerManager.getAll();
334
+ }
335
+ /**
336
+ * Get a specific peer by peerId.
337
+ */
338
+ getPeer(peerId) {
339
+ return this._peerManager.getPeer(peerId);
340
+ }
341
+ // ============ Internal (called by NoLagSignal) ============
342
+ /** @internal Subscribe to signaling topic and attach listeners */
343
+ _subscribe(filters) {
344
+ this._log('Room subscribe:', this.name);
345
+ this._filters = filters ? [...filters] : [];
346
+ if (this._filters.length > 0) {
347
+ this._roomContext.subscribe(TOPIC_SIGNALING, { filters: this._filters });
348
+ }
349
+ else {
350
+ this._roomContext.subscribe(TOPIC_SIGNALING);
351
+ }
352
+ // Listen for signals (ref stored for handler-specific removal)
353
+ this._onSignalingRef = (data) => {
354
+ this._handleIncomingSignal(data);
355
+ };
356
+ this._roomContext.on(TOPIC_SIGNALING, this._onSignalingRef);
357
+ }
358
+ /** @internal Set presence and fetch room members */
359
+ _activate() {
360
+ this._log('Room activate:', this.name);
361
+ this._setPresence();
362
+ this._roomContext.fetchPresence().then((actors) => {
363
+ this._log('Room presence fetched:', this.name, actors.length, 'actors');
364
+ for (const actor of actors) {
365
+ if (actor.presence) {
366
+ const peer = this._peerManager.addFromPresence(actor.actorTokenId, actor.presence, actor.joinedAt);
367
+ if (peer) {
368
+ this.emit('peerJoined', peer);
369
+ }
370
+ }
371
+ }
372
+ }).catch((err) => {
373
+ this._log('Failed to fetch room presence:', err);
374
+ });
375
+ }
376
+ /** @internal Re-set presence after reconnect */
377
+ _updateLocalPresence() {
378
+ this._setPresence();
379
+ }
380
+ /** @internal Handle a presence:join event */
381
+ _handlePresenceJoin(actorTokenId, presenceData) {
382
+ const peer = this._peerManager.addFromPresence(actorTokenId, presenceData);
383
+ if (peer) {
384
+ this._log('Peer joined room:', this.name, peer.peerId);
385
+ this.emit('peerJoined', peer);
386
+ }
387
+ }
388
+ /** @internal Handle a presence:leave event */
389
+ _handlePresenceLeave(actorTokenId) {
390
+ const peer = this._peerManager.removeByActorId(actorTokenId);
391
+ if (peer) {
392
+ this._log('Peer left room:', this.name, peer.peerId);
393
+ this.emit('peerLeft', peer);
394
+ }
395
+ }
396
+ /** @internal Handle a presence:update event */
397
+ _handlePresenceUpdate(actorTokenId, presenceData) {
398
+ this._peerManager.addFromPresence(actorTokenId, presenceData);
399
+ }
400
+ /** @internal Unsubscribe and clean up */
401
+ _cleanup() {
402
+ this._log('Room cleanup:', this.name);
403
+ // Server unsubscribes need a live socket; skip when disconnected
404
+ // (best-effort — the core would no-op with an error callback anyway).
405
+ if (this._isConnected()) {
406
+ this._roomContext.unsubscribe(TOPIC_SIGNALING);
407
+ }
408
+ // Handler-specific removal only: the client may be shared, and a bare
409
+ // off(topic) would strip other consumers' handlers too.
410
+ if (this._onSignalingRef)
411
+ this._roomContext.off(TOPIC_SIGNALING, this._onSignalingRef);
412
+ this._onSignalingRef = null;
413
+ this._peerManager.clear();
414
+ this.removeAllListeners();
415
+ }
416
+ // ============ Private ============
417
+ _handleIncomingSignal(data) {
418
+ const message = data;
419
+ // Only process messages targeted at this peer
420
+ if (message.toPeerId !== this._localPeer.peerId)
421
+ return;
422
+ this._log('Received signal:', message.type, 'from', message.fromPeerId);
423
+ this.emit('signal', message);
424
+ }
425
+ _setPresence() {
426
+ const presenceData = {
427
+ peerId: this._localPeer.peerId,
428
+ metadata: this._localPeer.metadata,
429
+ // Scope tag: on a shared client, other apps' wrappers filter our
430
+ // presence out by this (and we filter theirs).
431
+ __scope: this._options.appName,
432
+ };
433
+ this._roomContext.setPresence(presenceData);
434
+ }
435
+ }
436
+
437
+ /**
438
+ * NoLagSignal — high-level WebRTC signaling SDK built on @nolag/js-sdk.
439
+ *
440
+ * Provides peer discovery, offer/answer/ICE exchange, and global presence
441
+ * tracking — all framework-agnostic via events.
442
+ *
443
+ * The wrapper NEVER manages the connection. The app owns one core NoLag
444
+ * client (shared by any number of wrappers on distinct apps) and the
445
+ * wrapper attaches to it at construction and releases it via `detach()`.
446
+ *
447
+ * @example
448
+ * ```typescript
449
+ * import { NoLag } from '@nolag/js-sdk';
450
+ * import { NoLagSignal } from '@nolag/signal';
451
+ *
452
+ * const client = NoLag(async () => (await (await fetch('/api/nolag-token')).json()).token);
453
+ * const signal = new NoLagSignal({ client, appName: 'my-signal' });
454
+ *
455
+ * signal.on('peerOnline', (peer) => console.log(peer.peerId, 'is online'));
456
+ *
457
+ * await client.connect(); // the app owns the connection
458
+ * await signal.ready(); // wrapper setup done (identity, lobby)
459
+ *
460
+ * const room = signal.joinRoom('call-room');
461
+ * room.on('signal', (msg) => {
462
+ * if (msg.type === 'offer') handleOffer(msg);
463
+ * });
464
+ * room.sendOffer(remotePeerId, offer);
465
+ *
466
+ * signal.detach(); // wrapper releases its handlers and topics
467
+ * client.disconnect(); // the app closes the socket
468
+ * ```
469
+ */
470
+ class NoLagSignal extends EventEmitter {
471
+ constructor(options) {
472
+ super();
473
+ this._localPeer = null;
474
+ this._rooms = new Map();
475
+ this._lobby = null;
476
+ this._onlinePeers = new Map();
477
+ this._actorToPeerId = new Map();
478
+ // Lifecycle: one setup run per connection epoch; detach is terminal.
479
+ this._epoch = 0;
480
+ this._detached = false;
481
+ this._isReady = false;
482
+ this._lobbyRefreshTimer = null;
483
+ // Stored client handler refs. INVARIANT: every client.on() below has a
484
+ // matching client.off() in detach() — never bare off(event), never inline
485
+ // closures on the client.
486
+ this._onConnectRef = () => this._onConnect();
487
+ this._onDisconnectRef = (reason) => {
488
+ this._log('Disconnected:', reason);
489
+ this.emit('disconnected', reason);
490
+ };
491
+ this._onReconnectRef = () => {
492
+ this._log('Reconnecting...');
493
+ this.emit('reconnecting');
494
+ };
495
+ this._onErrorRef = (error) => {
496
+ this._log('Error:', error);
497
+ this.emit('error', error);
498
+ };
499
+ this._onPresenceJoinRef = (data) => this._handleRoomPresenceJoin(data);
500
+ this._onPresenceLeaveRef = (data) => this._handleRoomPresenceLeave(data);
501
+ this._onPresenceUpdateRef = (data) => this._handleRoomPresenceUpdate(data);
502
+ this._onLobbyJoinRef = (data) => this._handleLobbyJoin(data);
503
+ this._onLobbyLeaveRef = (data) => this._handleLobbyLeave(data);
504
+ this._onLobbyUpdateRef = (data) => this._handleLobbyUpdate(data);
505
+ if (!options?.client) {
506
+ throw new TypeError('NoLagSignal requires an injected NoLag client: new NoLagSignal({ client, ... })');
507
+ }
508
+ this._client = options.client;
509
+ this._peerId = generateId();
510
+ this._options = {
511
+ metadata: options.metadata,
512
+ appName: options.appName ?? DEFAULT_APP_NAME,
513
+ debug: options.debug ?? false,
514
+ };
515
+ this._log = createLogger('NoLagSignal', this._options.debug);
516
+ this._readyPromise = new Promise((resolve, reject) => {
517
+ this._readyResolve = resolve;
518
+ this._readyReject = reject;
519
+ });
520
+ // ready() rejection is only meaningful to callers that await it
521
+ this._readyPromise.catch(() => { });
522
+ registerWrapper(this._client, this._options.appName, 'NoLagSignal');
523
+ // Construction = attach: wire everything now, with stored refs.
524
+ this._client.on('connect', this._onConnectRef);
525
+ this._client.on('disconnect', this._onDisconnectRef);
526
+ this._client.on('reconnect', this._onReconnectRef);
527
+ this._client.on('error', this._onErrorRef);
528
+ this._client.on('presence:join', this._onPresenceJoinRef);
529
+ this._client.on('presence:leave', this._onPresenceLeaveRef);
530
+ this._client.on('presence:update', this._onPresenceUpdateRef);
531
+ this._client.on('lobbyPresence:join', this._onLobbyJoinRef);
532
+ this._client.on('lobbyPresence:leave', this._onLobbyLeaveRef);
533
+ this._client.on('lobbyPresence:update', this._onLobbyUpdateRef);
534
+ // Attach-to-connected: if the client is already authenticated, run setup.
535
+ // The microtask lets the caller wire wrapper event handlers synchronously
536
+ // first; a racing real 'connect' event wins via the epoch guard.
537
+ queueMicrotask(() => {
538
+ if (this._epoch === 0 && !this._detached && this._client.connected) {
539
+ this._onConnect();
540
+ }
541
+ });
542
+ }
543
+ // ============ Public Properties ============
544
+ /** Whether the underlying connection is established (connected ≠ ready) */
545
+ get connected() {
546
+ return !this._detached && this._client.connected;
547
+ }
548
+ /** The injected core client (owned by the app, not the wrapper) */
549
+ get client() {
550
+ return this._client;
551
+ }
552
+ /** The local peer's info (available after ready) */
553
+ get localPeer() {
554
+ return this._localPeer;
555
+ }
556
+ /** All currently joined rooms */
557
+ get rooms() {
558
+ return this._rooms;
559
+ }
560
+ // ============ Lifecycle ============
561
+ /**
562
+ * Resolves once the wrapper's first setup completed (identity and lobby
563
+ * ready — equivalently, once 'connected' has fired). Rejects only if
564
+ * detach() is called before that. Client auth failures surface via the
565
+ * app's own `await client.connect()`, not here.
566
+ */
567
+ ready() {
568
+ return this._readyPromise;
569
+ }
570
+ /**
571
+ * Detach from the client: remove every handler this wrapper added,
572
+ * unsubscribe its topics and lobby (when connected), clear state.
573
+ * Terminal and idempotent; never touches the socket. To use signaling
574
+ * again, construct a new instance.
575
+ */
576
+ detach() {
577
+ if (this._detached)
578
+ return;
579
+ this._log('Detaching...');
580
+ this._detached = true;
581
+ this._epoch++; // aborts any in-flight setup at its next checkpoint
582
+ if (this._lobbyRefreshTimer) {
583
+ clearTimeout(this._lobbyRefreshTimer);
584
+ this._lobbyRefreshTimer = null;
585
+ }
586
+ // Remove all client handlers by stored ref
587
+ this._client.off('connect', this._onConnectRef);
588
+ this._client.off('disconnect', this._onDisconnectRef);
589
+ this._client.off('reconnect', this._onReconnectRef);
590
+ this._client.off('error', this._onErrorRef);
591
+ this._client.off('presence:join', this._onPresenceJoinRef);
592
+ this._client.off('presence:leave', this._onPresenceLeaveRef);
593
+ this._client.off('presence:update', this._onPresenceUpdateRef);
594
+ this._client.off('lobbyPresence:join', this._onLobbyJoinRef);
595
+ this._client.off('lobbyPresence:leave', this._onLobbyLeaveRef);
596
+ this._client.off('lobbyPresence:update', this._onLobbyUpdateRef);
597
+ // Rooms: handler-specific off + connected-gated server unsubscribe
598
+ for (const name of [...this._rooms.keys()]) {
599
+ this._rooms.get(name)._cleanup();
600
+ this._rooms.delete(name);
601
+ }
602
+ // Lobby: server unsubscribe is best-effort and needs a live socket
603
+ if (this._lobby && this._client.connected) {
604
+ try {
605
+ this._lobby.unsubscribe();
606
+ }
607
+ catch {
608
+ /* best-effort */
609
+ }
610
+ }
611
+ this._lobby = null;
612
+ this._onlinePeers.clear();
613
+ this._actorToPeerId.clear();
614
+ this._localPeer = null;
615
+ releaseWrapper(this._client, this._options.appName);
616
+ if (!this._isReady) {
617
+ this._readyReject(new Error('NoLagSignal detached before ready'));
618
+ }
619
+ }
620
+ // ============ Private: Epoch Setup ============
621
+ _onConnect() {
622
+ this._epoch++;
623
+ void this._runSetup(this._epoch);
624
+ }
625
+ /**
626
+ * One setup pass per connection epoch. Serves both initial setup (epoch 1)
627
+ * and reconnect restore (epoch > 1). Aborts silently whenever a newer
628
+ * epoch started or the wrapper detached — checked after every await.
629
+ */
630
+ async _runSetup(epoch) {
631
+ const stale = () => epoch !== this._epoch || this._detached;
632
+ this._log(this._isReady ? 'Restoring after reconnect...' : 'Setting up...');
633
+ // Identity (client.actorId is guaranteed post-auth)
634
+ if (!this._localPeer) {
635
+ this._localPeer = {
636
+ peerId: this._peerId,
637
+ actorTokenId: this._client.actorId,
638
+ connectionState: 'new',
639
+ metadata: this._options.metadata,
640
+ joinedAt: Date.now(),
641
+ isLocal: true,
642
+ };
643
+ this._log('Local peer:', this._localPeer.peerId, '→', this._localPeer.actorTokenId);
644
+ }
645
+ else {
646
+ this._localPeer.actorTokenId = this._client.actorId;
647
+ }
648
+ // Lobby: subscribe every epoch (idempotent server-side) and diff-hydrate
649
+ // from the returned snapshot — one path for setup and restore.
650
+ if (!this._lobby) {
651
+ this._lobby = this._client.setApp(this._options.appName).setLobby(LOBBY_ID);
652
+ }
653
+ try {
654
+ const state = await this._lobby.subscribe();
655
+ if (stale())
656
+ return;
657
+ this._diffHydrateOnlinePeers(state);
658
+ this._log('Lobby subscribed, online peers:', this._onlinePeers.size);
659
+ }
660
+ catch (err) {
661
+ if (stale())
662
+ return;
663
+ this._log('Lobby subscription failed:', err);
664
+ }
665
+ if (this._isReady) {
666
+ // Server auto-restored topic subscriptions; only room-scoped presence
667
+ // needs re-applying (the core does not restore it).
668
+ for (const room of this._rooms.values()) {
669
+ room._updateLocalPresence();
670
+ }
671
+ }
672
+ if (stale())
673
+ return;
674
+ // Ready keys on the first setup that COMPLETES, not on epoch 1: an
675
+ // epoch aborted by a racing reconnect must not strand ready().
676
+ if (!this._isReady) {
677
+ this._isReady = true;
678
+ this._readyResolve();
679
+ this.emit('connected');
680
+ }
681
+ else {
682
+ this.emit('reconnected');
683
+ }
684
+ // Deferred lobby refetch: catches peers who joined during the setup
685
+ // window (e.g. simultaneous multi-tab connects).
686
+ this._scheduleLobbyRefresh(epoch);
687
+ }
688
+ _scheduleLobbyRefresh(epoch) {
689
+ if (this._lobbyRefreshTimer)
690
+ clearTimeout(this._lobbyRefreshTimer);
691
+ this._lobbyRefreshTimer = setTimeout(() => {
692
+ this._lobbyRefreshTimer = null;
693
+ if (epoch !== this._epoch || this._detached || !this._client.connected || !this._lobby) {
694
+ return;
695
+ }
696
+ this._lobby
697
+ .fetchPresence()
698
+ .then((state) => {
699
+ if (epoch !== this._epoch || this._detached)
700
+ return;
701
+ this._diffHydrateOnlinePeers(state);
702
+ })
703
+ .catch(() => {
704
+ /* best-effort */
705
+ });
706
+ }, LOBBY_REFRESH_DELAY_MS);
707
+ }
708
+ // ============ Room Management ============
709
+ /**
710
+ * Join a signaling room. Creates, subscribes, and activates it.
711
+ * Returns an existing room if already joined.
712
+ */
713
+ joinRoom(name, opts) {
714
+ this._assertUsable();
715
+ let room = this._rooms.get(name);
716
+ if (!room) {
717
+ room = this._subscribeRoom(name, opts?.filters);
718
+ room._activate();
719
+ }
720
+ else if (opts?.filters) {
721
+ // Already joined — re-point its filters rather than ignoring them.
722
+ room.setFilters(opts.filters);
723
+ }
724
+ return room;
725
+ }
726
+ /**
727
+ * Leave a signaling room. Fully unsubscribes and removes it.
728
+ */
729
+ leaveRoom(name) {
730
+ const room = this._rooms.get(name);
731
+ if (!room)
732
+ return;
733
+ this._log('Leaving room:', name);
734
+ room._cleanup();
735
+ this._rooms.delete(name);
736
+ }
737
+ /**
738
+ * Get all joined rooms.
739
+ */
740
+ getRooms() {
741
+ return Array.from(this._rooms.values());
742
+ }
743
+ // ============ Global Presence ============
744
+ /**
745
+ * Get all peers currently online across all rooms.
746
+ */
747
+ getOnlinePeers() {
748
+ return Array.from(this._onlinePeers.values());
749
+ }
750
+ // ============ Private: Guards ============
751
+ _assertUsable() {
752
+ if (this._detached) {
753
+ throw new Error('NoLagSignal has been detached — construct a new instance');
754
+ }
755
+ if (!this._isReady || !this._localPeer) {
756
+ throw new Error('NoLagSignal not ready — await ready() or the "connected" event');
757
+ }
758
+ }
759
+ // ============ Private: Room Setup ============
760
+ _subscribeRoom(name, filters) {
761
+ this._log('Subscribing room:', name);
762
+ const roomContext = this._client.setApp(this._options.appName).setRoom(name);
763
+ const room = new SignalRoom(name, roomContext, this._localPeer, this._options, createLogger(`SignalRoom:${name}`, this._options.debug), () => this._client.connected);
764
+ this._rooms.set(name, room);
765
+ room._subscribe(filters);
766
+ return room;
767
+ }
768
+ // ============ Private: Scope Filtering ============
769
+ /**
770
+ * On a shared client, presence events from other apps' wrappers arrive on
771
+ * the same connection-level events. Wrappers stamp their presence with a
772
+ * `__scope` (their appName); a mismatched tag means another app's data.
773
+ * Untagged presence is accepted (older peers in this same app).
774
+ */
775
+ _foreignScope(data) {
776
+ const scope = data?.__scope;
777
+ return typeof scope === 'string' && scope !== this._options.appName;
778
+ }
779
+ // ============ Private: Room Presence ============
780
+ _handleRoomPresenceJoin(data) {
781
+ if (data.actorTokenId === this._localPeer?.actorTokenId)
782
+ return;
783
+ const presenceData = data.presence;
784
+ if (!presenceData?.peerId || this._foreignScope(presenceData))
785
+ return;
786
+ const peer = this._presenceToPeer(data.actorTokenId, presenceData);
787
+ this._actorToPeerId.set(data.actorTokenId, peer.peerId);
788
+ if (!this._onlinePeers.has(peer.peerId)) {
789
+ this._onlinePeers.set(peer.peerId, peer);
790
+ this.emit('peerOnline', peer);
791
+ }
792
+ // Route to all rooms
793
+ for (const room of this._rooms.values()) {
794
+ room._handlePresenceJoin(data.actorTokenId, presenceData);
795
+ }
796
+ }
797
+ _handleRoomPresenceLeave(data) {
798
+ if (data.actorTokenId === this._localPeer?.actorTokenId)
799
+ return;
800
+ // Route to all rooms
801
+ for (const room of this._rooms.values()) {
802
+ room._handlePresenceLeave(data.actorTokenId);
803
+ }
804
+ }
805
+ _handleRoomPresenceUpdate(data) {
806
+ if (data.actorTokenId === this._localPeer?.actorTokenId)
807
+ return;
808
+ const presenceData = data.presence;
809
+ if (!presenceData?.peerId || this._foreignScope(presenceData))
810
+ return;
811
+ if (this._onlinePeers.has(presenceData.peerId)) {
812
+ const peer = this._presenceToPeer(data.actorTokenId, presenceData);
813
+ this._onlinePeers.set(peer.peerId, peer);
814
+ }
815
+ // Route to all rooms
816
+ for (const room of this._rooms.values()) {
817
+ room._handlePresenceUpdate(data.actorTokenId, presenceData);
818
+ }
819
+ }
820
+ // ============ Private: Lobby ============
821
+ _handleLobbyJoin(event) {
822
+ const { actorId, data } = event;
823
+ if (actorId === this._localPeer?.actorTokenId)
824
+ return;
825
+ const presenceData = data;
826
+ if (!presenceData.peerId || this._foreignScope(presenceData))
827
+ return;
828
+ const peer = this._presenceToPeer(actorId, presenceData);
829
+ this._actorToPeerId.set(actorId, peer.peerId);
830
+ if (!this._onlinePeers.has(peer.peerId)) {
831
+ this._onlinePeers.set(peer.peerId, peer);
832
+ this.emit('peerOnline', peer);
833
+ }
834
+ }
835
+ _handleLobbyLeave(event) {
836
+ const { actorId, data } = event;
837
+ if (actorId === this._localPeer?.actorTokenId)
838
+ return;
839
+ const presenceData = data;
840
+ if (this._foreignScope(presenceData))
841
+ return;
842
+ const peerId = presenceData?.peerId
843
+ || this._actorToPeerId.get(actorId)
844
+ || this._findPeerIdByActorId(actorId);
845
+ if (peerId) {
846
+ const peer = this._onlinePeers.get(peerId);
847
+ if (peer) {
848
+ this._onlinePeers.delete(peerId);
849
+ this._actorToPeerId.delete(actorId);
850
+ this.emit('peerOffline', peer);
851
+ }
852
+ }
853
+ }
854
+ _handleLobbyUpdate(event) {
855
+ const { actorId, data } = event;
856
+ if (actorId === this._localPeer?.actorTokenId)
857
+ return;
858
+ const presenceData = data;
859
+ if (!presenceData.peerId || this._foreignScope(presenceData))
860
+ return;
861
+ const peer = this._presenceToPeer(actorId, presenceData);
862
+ this._onlinePeers.set(peer.peerId, peer);
863
+ }
864
+ /**
865
+ * Reconcile the online-peer map against a fresh lobby snapshot, emitting
866
+ * only the deltas (peerOffline for vanished, peerOnline for new). One path
867
+ * for initial hydration, reconnect restore, and the deferred refetch.
868
+ */
869
+ _diffHydrateOnlinePeers(state) {
870
+ // Build the fresh peer set from the snapshot
871
+ const fresh = new Map();
872
+ const freshActors = new Map();
873
+ for (const roomId of Object.keys(state)) {
874
+ const roomPresence = state[roomId];
875
+ for (const actorId of Object.keys(roomPresence)) {
876
+ if (actorId === this._localPeer?.actorTokenId)
877
+ continue;
878
+ const raw = roomPresence[actorId];
879
+ // Server returns full actor records with presence nested under .presence
880
+ const presenceData = (raw?.presence ?? raw);
881
+ if (presenceData?.peerId && !this._foreignScope(presenceData)) {
882
+ if (!fresh.has(presenceData.peerId)) {
883
+ fresh.set(presenceData.peerId, this._presenceToPeer(actorId, presenceData));
884
+ }
885
+ freshActors.set(actorId, presenceData.peerId);
886
+ }
887
+ }
888
+ }
889
+ // Vanished peers
890
+ for (const [peerId, peer] of [...this._onlinePeers]) {
891
+ if (!fresh.has(peerId)) {
892
+ this._onlinePeers.delete(peerId);
893
+ for (const [actorId, mappedPeerId] of [...this._actorToPeerId]) {
894
+ if (mappedPeerId === peerId)
895
+ this._actorToPeerId.delete(actorId);
896
+ }
897
+ this.emit('peerOffline', peer);
898
+ }
899
+ }
900
+ // New peers
901
+ for (const [peerId, peer] of fresh) {
902
+ if (!this._onlinePeers.has(peerId)) {
903
+ this._onlinePeers.set(peerId, peer);
904
+ this.emit('peerOnline', peer);
905
+ }
906
+ }
907
+ for (const [actorId, peerId] of freshActors) {
908
+ this._actorToPeerId.set(actorId, peerId);
909
+ }
910
+ }
911
+ // ============ Private: Helpers ============
912
+ _presenceToPeer(actorTokenId, data) {
913
+ return {
914
+ peerId: data.peerId,
915
+ actorTokenId,
916
+ connectionState: 'new',
917
+ metadata: data.metadata,
918
+ joinedAt: Date.now(),
919
+ isLocal: false,
920
+ };
921
+ }
922
+ _findPeerIdByActorId(actorTokenId) {
923
+ for (const peer of this._onlinePeers.values()) {
924
+ if (peer.actorTokenId === actorTokenId)
925
+ return peer.peerId;
926
+ }
927
+ return undefined;
928
+ }
929
+ }
930
+
931
+ export { EventEmitter, NoLagSignal, SignalRoom };
932
+ //# sourceMappingURL=react-native.js.map