@nolag/collab 0.1.2 → 1.1.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,1160 @@
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
+ * PresenceManager — maps actorTokenId ↔ CollabUser, filtering self.
50
+ */
51
+ class PresenceManager {
52
+ constructor(localActorId) {
53
+ this._users = new Map();
54
+ this._actorToUserId = new Map();
55
+ this._localActorId = localActorId;
56
+ }
57
+ /**
58
+ * Add or update a user from presence data.
59
+ * Returns the CollabUser if it is a remote user, null if it is 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._actorToUserId.get(actorTokenId);
67
+ const userId = presence.userId || existing || actorTokenId;
68
+ const user = {
69
+ userId,
70
+ actorTokenId,
71
+ username: presence.username,
72
+ avatar: presence.avatar,
73
+ color: presence.color,
74
+ status: presence.status ?? 'active',
75
+ metadata: presence.metadata,
76
+ joinedAt: joinedAt ?? Date.now(),
77
+ isLocal: false,
78
+ };
79
+ this._users.set(userId, user);
80
+ this._actorToUserId.set(actorTokenId, userId);
81
+ return user;
82
+ }
83
+ /**
84
+ * Remove a user by actorTokenId.
85
+ * Returns the removed CollabUser, or null if not found / is self.
86
+ */
87
+ removeByActorId(actorTokenId) {
88
+ if (actorTokenId === this._localActorId)
89
+ return null;
90
+ const userId = this._actorToUserId.get(actorTokenId);
91
+ if (!userId)
92
+ return null;
93
+ const user = this._users.get(userId) ?? null;
94
+ this._users.delete(userId);
95
+ this._actorToUserId.delete(actorTokenId);
96
+ return user;
97
+ }
98
+ /**
99
+ * Update only the status field for an existing user.
100
+ */
101
+ updateStatus(actorTokenId, status) {
102
+ const userId = this._actorToUserId.get(actorTokenId);
103
+ if (!userId)
104
+ return null;
105
+ const user = this._users.get(userId);
106
+ if (!user)
107
+ return null;
108
+ const updated = { ...user, status };
109
+ this._users.set(userId, updated);
110
+ return updated;
111
+ }
112
+ /**
113
+ * Get a user by userId.
114
+ */
115
+ getUser(userId) {
116
+ return this._users.get(userId);
117
+ }
118
+ /**
119
+ * Get a user by actorTokenId.
120
+ */
121
+ getUserByActorId(actorTokenId) {
122
+ const userId = this._actorToUserId.get(actorTokenId);
123
+ return userId ? this._users.get(userId) : undefined;
124
+ }
125
+ /**
126
+ * Get all remote users.
127
+ */
128
+ getAll() {
129
+ return Array.from(this._users.values());
130
+ }
131
+ /**
132
+ * Get the users Map (readonly view).
133
+ */
134
+ get users() {
135
+ return this._users;
136
+ }
137
+ /**
138
+ * Clear all tracked users.
139
+ */
140
+ clear() {
141
+ this._users.clear();
142
+ this._actorToUserId.clear();
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Ordered, deduplicated operation log bounded by maxOperationCache.
148
+ *
149
+ * Operations are stored sorted by timestamp ascending. Duplicate IDs are
150
+ * silently ignored. When the cache exceeds its limit the oldest entries
151
+ * are evicted.
152
+ */
153
+ class OperationStore {
154
+ constructor(maxSize) {
155
+ this._ops = [];
156
+ this._ids = new Set();
157
+ this._maxSize = maxSize;
158
+ }
159
+ /**
160
+ * Add an operation to the store.
161
+ * Returns true if the operation was added, false if it was a duplicate.
162
+ */
163
+ add(op) {
164
+ if (this._ids.has(op.id))
165
+ return false;
166
+ this._ids.add(op.id);
167
+ this._ops.push(op);
168
+ // Keep sorted by timestamp ascending
169
+ this._ops.sort((a, b) => a.timestamp - b.timestamp);
170
+ // Evict oldest entries when over capacity
171
+ while (this._ops.length > this._maxSize) {
172
+ const evicted = this._ops.shift();
173
+ if (evicted)
174
+ this._ids.delete(evicted.id);
175
+ }
176
+ return true;
177
+ }
178
+ /**
179
+ * Get all stored operations in timestamp order.
180
+ */
181
+ getAll() {
182
+ return [...this._ops];
183
+ }
184
+ /**
185
+ * Get all operations sent by a specific user.
186
+ */
187
+ getByUser(userId) {
188
+ return this._ops.filter((op) => op.userId === userId);
189
+ }
190
+ /**
191
+ * Check whether an operation ID is already stored.
192
+ */
193
+ has(id) {
194
+ return this._ids.has(id);
195
+ }
196
+ /**
197
+ * Number of operations currently stored.
198
+ */
199
+ get size() {
200
+ return this._ops.length;
201
+ }
202
+ /**
203
+ * Clear all stored operations.
204
+ */
205
+ clear() {
206
+ this._ops = [];
207
+ this._ids.clear();
208
+ }
209
+ }
210
+
211
+ /**
212
+ * AwarenessManager — cursor tracking and idle detection per user.
213
+ *
214
+ * Tracks cursor positions for all connected users and manages per-user
215
+ * idle timers that fire a callback when a user has been inactive.
216
+ */
217
+ class AwarenessManager {
218
+ constructor(localUserId) {
219
+ this._cursors = new Map();
220
+ this._statuses = new Map();
221
+ this._idleTimers = new Map();
222
+ this._localUserId = localUserId;
223
+ }
224
+ /**
225
+ * Update the cursor position for a user and reset their idle timer.
226
+ */
227
+ updateCursor(userId, position) {
228
+ this._cursors.set(userId, position);
229
+ // Reset idle timer if one is running for this user
230
+ if (this._idleTimers.has(userId)) {
231
+ const timer = this._idleTimers.get(userId);
232
+ clearTimeout(timer);
233
+ this._idleTimers.delete(userId);
234
+ }
235
+ }
236
+ /**
237
+ * Get the last known cursor position for a user.
238
+ */
239
+ getCursor(userId) {
240
+ return this._cursors.get(userId);
241
+ }
242
+ /**
243
+ * Get all cursor positions except the local user's.
244
+ */
245
+ getCursors() {
246
+ return Array.from(this._cursors.values()).filter((c) => c.userId !== this._localUserId);
247
+ }
248
+ /**
249
+ * Set the activity status for a user.
250
+ */
251
+ setStatus(userId, status) {
252
+ this._statuses.set(userId, status);
253
+ }
254
+ /**
255
+ * Get the current activity status for a user (defaults to 'active').
256
+ */
257
+ getStatus(userId) {
258
+ return this._statuses.get(userId) ?? 'active';
259
+ }
260
+ /**
261
+ * Start an idle timer for a user. If the timer fires, onIdle is called
262
+ * and the user's status is set to 'idle'. Calling updateCursor resets it.
263
+ */
264
+ startIdleTracking(userId, timeout, onIdle) {
265
+ // Cancel any existing timer
266
+ this.stopIdleTracking(userId);
267
+ const timer = setTimeout(() => {
268
+ this._idleTimers.delete(userId);
269
+ this._statuses.set(userId, 'idle');
270
+ onIdle();
271
+ }, timeout);
272
+ this._idleTimers.set(userId, timer);
273
+ }
274
+ /**
275
+ * Cancel the idle timer for a user without firing the callback.
276
+ */
277
+ stopIdleTracking(userId) {
278
+ const timer = this._idleTimers.get(userId);
279
+ if (timer !== undefined) {
280
+ clearTimeout(timer);
281
+ this._idleTimers.delete(userId);
282
+ }
283
+ }
284
+ /**
285
+ * Remove all cursor data for a user.
286
+ */
287
+ removeCursor(userId) {
288
+ this._cursors.delete(userId);
289
+ this._statuses.delete(userId);
290
+ this.stopIdleTracking(userId);
291
+ }
292
+ /**
293
+ * Dispose — clear all timers and state.
294
+ */
295
+ dispose() {
296
+ for (const timer of this._idleTimers.values()) {
297
+ clearTimeout(timer);
298
+ }
299
+ this._idleTimers.clear();
300
+ this._cursors.clear();
301
+ this._statuses.clear();
302
+ }
303
+ }
304
+
305
+ function generateId() {
306
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
307
+ return crypto.randomUUID();
308
+ }
309
+ return 'xxxx-xxxx-xxxx-xxxx'.replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
310
+ }
311
+ function createLogger(prefix, enabled) {
312
+ if (!enabled) {
313
+ return (..._args) => { };
314
+ }
315
+ return (...args) => {
316
+ console.log(`[${prefix}]`, ...args);
317
+ };
318
+ }
319
+ // ============ Wrapper registry ============
320
+ // One wrapper instance per (client, appName): two wrappers sharing an app on
321
+ // one connection would collide on topics, presence and the online lobby.
322
+ // Warn (not throw): HMR and tests legitimately construct before disposing.
323
+ const wrapperRegistry = new WeakMap();
324
+ /** Register a wrapper against a client + appName; warns on collision. */
325
+ function registerWrapper(client, appName, wrapperName) {
326
+ let apps = wrapperRegistry.get(client);
327
+ if (!apps) {
328
+ apps = new Map();
329
+ wrapperRegistry.set(client, apps);
330
+ }
331
+ const existing = apps.get(appName);
332
+ if (existing) {
333
+ console.warn(`[${wrapperName}] Another wrapper (${existing}) is already attached to this client for app "${appName}". ` +
334
+ `Use one wrapper per (client, app) — detach the other instance first.`);
335
+ }
336
+ apps.set(appName, wrapperName);
337
+ }
338
+ /** Release a wrapper's (client, appName) registration on detach. */
339
+ function releaseWrapper(client, appName) {
340
+ wrapperRegistry.get(client)?.delete(appName);
341
+ }
342
+
343
+ /** Default app name for NoLag collab SDK */
344
+ const DEFAULT_APP_NAME = 'collab';
345
+ /** Maximum number of operations to keep in the cache */
346
+ const DEFAULT_MAX_OPERATION_CACHE = 1000;
347
+ /** Idle timeout in milliseconds before a user is marked idle */
348
+ const DEFAULT_IDLE_TIMEOUT = 60000;
349
+ /** Cursor throttle in milliseconds — minimum interval between cursor updates */
350
+ const DEFAULT_CURSOR_THROTTLE = 50;
351
+ /** Topic name for operation messages within a document */
352
+ const TOPIC_OPERATIONS = 'operations';
353
+ /** Topic name for cursor presence messages within a document */
354
+ const TOPIC_CURSORS = '_cursors';
355
+ /** Lobby ID for global online presence */
356
+ const LOBBY_ID = 'online';
357
+ /** Delay before the post-setup lobby presence refetch (catches simultaneous joiners) */
358
+ const LOBBY_REFRESH_DELAY_MS = 2000;
359
+
360
+ /**
361
+ * CollabDocument — a single collaborative document room.
362
+ *
363
+ * Created via `NoLagCollab.joinDocument(name)`. Do not instantiate directly.
364
+ *
365
+ * Subscribes to 'operations' and '_cursors' topics and exposes a clean API
366
+ * for sending operations, broadcasting cursor positions, and managing
367
+ * user awareness (idle detection, status).
368
+ */
369
+ class CollabDocument extends EventEmitter {
370
+ /** @internal */
371
+ constructor(name, roomContext, localUser, options, log, isConnected) {
372
+ super();
373
+ /** Throttle state for cursor updates */
374
+ this._cursorThrottleTimer = null;
375
+ this._pendingCursorUpdate = null;
376
+ // Stored topic handler refs — cleanup removes exactly these, never all
377
+ // handlers for a topic (the client may be shared with other consumers).
378
+ this._onOperationsRef = null;
379
+ this._onCursorsRef = null;
380
+ this.name = name;
381
+ this._roomContext = roomContext;
382
+ this._localUser = localUser;
383
+ this._options = options;
384
+ this._log = log;
385
+ this._isConnected = isConnected;
386
+ this._presenceManager = new PresenceManager(localUser.actorTokenId);
387
+ this._operationStore = new OperationStore(options.maxOperationCache);
388
+ this._awarenessManager = new AwarenessManager(localUser.userId);
389
+ }
390
+ // ============ Public Properties ============
391
+ /** All remote users currently in this document */
392
+ get users() {
393
+ return this._presenceManager.users;
394
+ }
395
+ // ============ Operations ============
396
+ /**
397
+ * Send an operation to all collaborators in this document.
398
+ * Returns the operation that was created and broadcast.
399
+ */
400
+ sendOperation(type, opts = {}) {
401
+ const op = {
402
+ id: generateId(),
403
+ type,
404
+ path: opts.path,
405
+ position: opts.position,
406
+ length: opts.length,
407
+ content: opts.content,
408
+ data: opts.data,
409
+ userId: this._localUser.userId,
410
+ username: this._localUser.username,
411
+ timestamp: Date.now(),
412
+ isReplay: false,
413
+ };
414
+ this._log('Sending operation:', type, op.id);
415
+ this._operationStore.add(op);
416
+ this._roomContext.emit(TOPIC_OPERATIONS, op, { echo: false });
417
+ return op;
418
+ }
419
+ /**
420
+ * Get all cached operations for this document, in timestamp order.
421
+ */
422
+ getOperations() {
423
+ return this._operationStore.getAll();
424
+ }
425
+ // ============ Cursors ============
426
+ /**
427
+ * Broadcast a cursor position update. Calls are throttled by the
428
+ * cursorThrottle option (default 50 ms) to avoid flooding.
429
+ */
430
+ updateCursor(opts) {
431
+ this._pendingCursorUpdate = opts;
432
+ if (this._cursorThrottleTimer !== null) {
433
+ // Already scheduled — the pending update will be sent when it fires
434
+ return;
435
+ }
436
+ // Send immediately for the first call in the window, then throttle
437
+ this._flushCursorUpdate();
438
+ this._cursorThrottleTimer = setTimeout(() => {
439
+ this._cursorThrottleTimer = null;
440
+ if (this._pendingCursorUpdate) {
441
+ this._flushCursorUpdate();
442
+ }
443
+ }, this._options.cursorThrottle);
444
+ }
445
+ /**
446
+ * Get all remote cursor positions.
447
+ */
448
+ getCursors() {
449
+ return this._awarenessManager.getCursors();
450
+ }
451
+ // ============ Awareness ============
452
+ /**
453
+ * Update the local user's activity status and broadcast it.
454
+ */
455
+ setStatus(status) {
456
+ this._localUser = { ...this._localUser, status };
457
+ this._setPresence();
458
+ this._log('Status updated:', status);
459
+ }
460
+ // ============ Users ============
461
+ /**
462
+ * Get all remote users currently in the document.
463
+ */
464
+ getUsers() {
465
+ return this._presenceManager.getAll();
466
+ }
467
+ /**
468
+ * Get a specific user by userId.
469
+ */
470
+ getUser(userId) {
471
+ return this._presenceManager.getUser(userId);
472
+ }
473
+ // ============ Internal (called by NoLagCollab) ============
474
+ /** @internal Subscribe to operations and cursors topics and attach listeners */
475
+ _subscribe() {
476
+ this._log('Document subscribe:', this.name);
477
+ this._roomContext.subscribe(TOPIC_OPERATIONS);
478
+ this._roomContext.subscribe(TOPIC_CURSORS);
479
+ // Listen for operations (refs stored for handler-specific removal)
480
+ this._onOperationsRef = (data) => {
481
+ this._handleIncomingOperation(data);
482
+ };
483
+ this._roomContext.on(TOPIC_OPERATIONS, this._onOperationsRef);
484
+ // Listen for cursors
485
+ this._onCursorsRef = (data) => {
486
+ this._handleIncomingCursor(data);
487
+ };
488
+ this._roomContext.on(TOPIC_CURSORS, this._onCursorsRef);
489
+ }
490
+ /** @internal Set presence and fetch current room members */
491
+ _activate() {
492
+ this._log('Document activate:', this.name);
493
+ this._setPresence();
494
+ this._roomContext.fetchPresence().then((actors) => {
495
+ this._log('Document presence fetched:', this.name, actors.length, 'actors');
496
+ for (const actor of actors) {
497
+ if (actor.presence) {
498
+ const user = this._presenceManager.addFromPresence(actor.actorTokenId, actor.presence, actor.joinedAt);
499
+ if (user) {
500
+ this._awarenessManager.setStatus(user.userId, user.status);
501
+ this.emit('userJoined', user);
502
+ }
503
+ }
504
+ }
505
+ }).catch((err) => {
506
+ this._log('Failed to fetch document presence:', err);
507
+ });
508
+ }
509
+ /** @internal Re-set presence after reconnect */
510
+ _updateLocalPresence() {
511
+ this._setPresence();
512
+ }
513
+ /** @internal Handle a presence:join event */
514
+ _handlePresenceJoin(actorTokenId, presenceData) {
515
+ const user = this._presenceManager.addFromPresence(actorTokenId, presenceData);
516
+ if (user) {
517
+ this._log('User joined document:', this.name, user.userId);
518
+ this._awarenessManager.setStatus(user.userId, user.status);
519
+ this._startUserIdleTracking(user);
520
+ this.emit('userJoined', user);
521
+ }
522
+ }
523
+ /** @internal Handle a presence:leave event */
524
+ _handlePresenceLeave(actorTokenId) {
525
+ const user = this._presenceManager.removeByActorId(actorTokenId);
526
+ if (user) {
527
+ this._log('User left document:', this.name, user.userId);
528
+ this._awarenessManager.removeCursor(user.userId);
529
+ this.emit('userLeft', user);
530
+ }
531
+ }
532
+ /** @internal Handle a presence:update event */
533
+ _handlePresenceUpdate(actorTokenId, presenceData) {
534
+ const user = this._presenceManager.addFromPresence(actorTokenId, presenceData);
535
+ if (user) {
536
+ this._awarenessManager.setStatus(user.userId, user.status);
537
+ }
538
+ }
539
+ /** @internal Replay operations from another source (e.g. history fetch) */
540
+ _replayOperations(ops) {
541
+ const pending = ops.filter((op) => !this._operationStore.has(op.id));
542
+ if (pending.length === 0)
543
+ return;
544
+ this._log('Replaying', pending.length, 'operations');
545
+ this.emit('replayStart', { count: pending.length });
546
+ let replayed = 0;
547
+ for (const op of pending) {
548
+ const replayOp = { ...op, isReplay: true };
549
+ if (this._operationStore.add(replayOp)) {
550
+ this.emit('operation', replayOp);
551
+ replayed++;
552
+ }
553
+ }
554
+ this.emit('replayEnd', { replayed });
555
+ }
556
+ /** @internal Unsubscribe and clean up */
557
+ _cleanup() {
558
+ this._log('Document cleanup:', this.name);
559
+ // Cancel cursor throttle timer
560
+ if (this._cursorThrottleTimer !== null) {
561
+ clearTimeout(this._cursorThrottleTimer);
562
+ this._cursorThrottleTimer = null;
563
+ }
564
+ this._pendingCursorUpdate = null;
565
+ // Server unsubscribes need a live socket; skip when disconnected
566
+ // (best-effort — the core would no-op with an error callback anyway).
567
+ if (this._isConnected()) {
568
+ this._roomContext.unsubscribe(TOPIC_OPERATIONS);
569
+ this._roomContext.unsubscribe(TOPIC_CURSORS);
570
+ }
571
+ // Handler-specific removal only: the client may be shared, and a bare
572
+ // off(topic) would strip other consumers' handlers too.
573
+ if (this._onOperationsRef)
574
+ this._roomContext.off(TOPIC_OPERATIONS, this._onOperationsRef);
575
+ if (this._onCursorsRef)
576
+ this._roomContext.off(TOPIC_CURSORS, this._onCursorsRef);
577
+ this._onOperationsRef = null;
578
+ this._onCursorsRef = null;
579
+ // Disposes all per-user idle timers alongside cursor/status state.
580
+ this._awarenessManager.dispose();
581
+ this._presenceManager.clear();
582
+ this._operationStore.clear();
583
+ this.removeAllListeners();
584
+ }
585
+ // ============ Private ============
586
+ _handleIncomingOperation(data) {
587
+ const op = data;
588
+ // Deduplicate
589
+ if (this._operationStore.has(op.id))
590
+ return;
591
+ const stored = { ...op, isReplay: false };
592
+ this._operationStore.add(stored);
593
+ this._log('Received operation:', op.type, op.id, 'from', op.userId);
594
+ this.emit('operation', stored);
595
+ }
596
+ _handleIncomingCursor(data) {
597
+ const cursor = data;
598
+ // Ignore own cursor echoes (should not happen with echo: false, but guard anyway)
599
+ if (cursor.userId === this._localUser.userId)
600
+ return;
601
+ this._awarenessManager.updateCursor(cursor.userId, cursor);
602
+ // Reset idle tracking for this user
603
+ const user = this._presenceManager.getUser(cursor.userId);
604
+ if (user) {
605
+ this._startUserIdleTracking(user);
606
+ }
607
+ this._log('Cursor moved:', cursor.userId);
608
+ this.emit('cursorMoved', cursor);
609
+ }
610
+ _flushCursorUpdate() {
611
+ if (!this._pendingCursorUpdate)
612
+ return;
613
+ const opts = this._pendingCursorUpdate;
614
+ this._pendingCursorUpdate = null;
615
+ const cursor = {
616
+ userId: this._localUser.userId,
617
+ username: this._localUser.username,
618
+ color: this._localUser.color,
619
+ timestamp: Date.now(),
620
+ ...opts,
621
+ };
622
+ this._awarenessManager.updateCursor(this._localUser.userId, cursor);
623
+ this._roomContext.emit(TOPIC_CURSORS, cursor, { echo: false });
624
+ }
625
+ _setPresence() {
626
+ const presenceData = {
627
+ userId: this._localUser.userId,
628
+ username: this._localUser.username,
629
+ avatar: this._localUser.avatar,
630
+ color: this._localUser.color,
631
+ status: this._localUser.status,
632
+ metadata: this._localUser.metadata,
633
+ // Scope tag: on a shared client, other apps' wrappers filter our
634
+ // presence out by this (and we filter theirs).
635
+ __scope: this._options.appName,
636
+ };
637
+ this._roomContext.setPresence(presenceData);
638
+ }
639
+ _startUserIdleTracking(user) {
640
+ // Mark user as active first
641
+ if (this._awarenessManager.getStatus(user.userId) !== 'active') {
642
+ this._awarenessManager.setStatus(user.userId, 'active');
643
+ }
644
+ this._awarenessManager.startIdleTracking(user.userId, this._options.idleTimeout, () => {
645
+ this._log('User went idle:', user.userId);
646
+ this.emit('awarenessChanged', { userId: user.userId, status: 'idle' });
647
+ });
648
+ }
649
+ }
650
+
651
+ /**
652
+ * NoLagCollab — high-level real-time collaboration SDK built on @nolag/js-sdk.
653
+ *
654
+ * Provides document-scoped operations, cursor broadcasting, and user awareness
655
+ * (idle detection, status tracking) — all framework-agnostic via events.
656
+ *
657
+ * The wrapper NEVER manages the connection. The app owns one core NoLag
658
+ * client (shared by any number of wrappers on distinct apps) and the
659
+ * wrapper attaches to it at construction and releases it via `detach()`.
660
+ *
661
+ * @example
662
+ * ```typescript
663
+ * import { NoLag } from '@nolag/js-sdk';
664
+ * import { NoLagCollab } from '@nolag/collab';
665
+ *
666
+ * const client = NoLag(async () => (await (await fetch('/api/nolag-token')).json()).token);
667
+ * const collab = new NoLagCollab({ client, appName: 'my-collab', username: 'Alice' });
668
+ *
669
+ * collab.on('userOnline', (user) => console.log(user.username, 'is online'));
670
+ *
671
+ * await client.connect(); // the app owns the connection
672
+ * await collab.ready(); // wrapper setup done (identity, lobby, documents)
673
+ *
674
+ * const doc = collab.joinDocument('my-doc');
675
+ * doc.on('operation', (op) => applyOp(op));
676
+ * doc.sendOperation('insert', { position: 0, content: 'Hello' });
677
+ *
678
+ * collab.detach(); // wrapper releases its handlers and topics
679
+ * client.disconnect(); // the app closes the socket
680
+ * ```
681
+ */
682
+ class NoLagCollab extends EventEmitter {
683
+ constructor(options) {
684
+ super();
685
+ this._localUser = null;
686
+ this._documents = new Map();
687
+ this._lobby = null;
688
+ this._onlineUsers = new Map();
689
+ this._actorToUserId = new Map();
690
+ // Lifecycle: one setup run per connection epoch; detach is terminal.
691
+ this._epoch = 0;
692
+ this._detached = false;
693
+ this._isReady = false;
694
+ this._lobbyRefreshTimer = null;
695
+ // Stored client handler refs. INVARIANT: every client.on() below has a
696
+ // matching client.off() in detach() — never bare off(event), never inline
697
+ // closures on the client.
698
+ this._onConnectRef = () => this._onConnect();
699
+ this._onDisconnectRef = (reason) => {
700
+ this._log('Disconnected:', reason);
701
+ this.emit('disconnected', reason);
702
+ };
703
+ this._onReconnectRef = () => {
704
+ this._log('Reconnecting...');
705
+ this.emit('reconnecting');
706
+ };
707
+ this._onErrorRef = (error) => {
708
+ this._log('Error:', error);
709
+ this.emit('error', error);
710
+ };
711
+ this._onPresenceJoinRef = (data) => this._handleRoomPresenceJoin(data);
712
+ this._onPresenceLeaveRef = (data) => this._handleRoomPresenceLeave(data);
713
+ this._onPresenceUpdateRef = (data) => this._handleRoomPresenceUpdate(data);
714
+ this._onLobbyJoinRef = (data) => this._handleLobbyJoin(data);
715
+ this._onLobbyLeaveRef = (data) => this._handleLobbyLeave(data);
716
+ this._onLobbyUpdateRef = (data) => this._handleLobbyUpdate(data);
717
+ if (!options?.client) {
718
+ throw new TypeError('NoLagCollab requires an injected NoLag client: new NoLagCollab({ client, username, ... })');
719
+ }
720
+ this._client = options.client;
721
+ this._userId = generateId();
722
+ this._options = {
723
+ username: options.username,
724
+ avatar: options.avatar,
725
+ color: options.color,
726
+ metadata: options.metadata,
727
+ appName: options.appName ?? DEFAULT_APP_NAME,
728
+ maxOperationCache: options.maxOperationCache ?? DEFAULT_MAX_OPERATION_CACHE,
729
+ idleTimeout: options.idleTimeout ?? DEFAULT_IDLE_TIMEOUT,
730
+ cursorThrottle: options.cursorThrottle ?? DEFAULT_CURSOR_THROTTLE,
731
+ debug: options.debug ?? false,
732
+ documents: options.documents ?? [],
733
+ };
734
+ this._log = createLogger('NoLagCollab', this._options.debug);
735
+ this._readyPromise = new Promise((resolve, reject) => {
736
+ this._readyResolve = resolve;
737
+ this._readyReject = reject;
738
+ });
739
+ // ready() rejection is only meaningful to callers that await it
740
+ this._readyPromise.catch(() => { });
741
+ registerWrapper(this._client, this._options.appName, 'NoLagCollab');
742
+ // Construction = attach: wire everything now, with stored refs.
743
+ this._client.on('connect', this._onConnectRef);
744
+ this._client.on('disconnect', this._onDisconnectRef);
745
+ this._client.on('reconnect', this._onReconnectRef);
746
+ this._client.on('error', this._onErrorRef);
747
+ this._client.on('presence:join', this._onPresenceJoinRef);
748
+ this._client.on('presence:leave', this._onPresenceLeaveRef);
749
+ this._client.on('presence:update', this._onPresenceUpdateRef);
750
+ this._client.on('lobbyPresence:join', this._onLobbyJoinRef);
751
+ this._client.on('lobbyPresence:leave', this._onLobbyLeaveRef);
752
+ this._client.on('lobbyPresence:update', this._onLobbyUpdateRef);
753
+ // Attach-to-connected: if the client is already authenticated, run setup.
754
+ // The microtask lets the caller wire wrapper event handlers synchronously
755
+ // first; a racing real 'connect' event wins via the epoch guard.
756
+ queueMicrotask(() => {
757
+ if (this._epoch === 0 && !this._detached && this._client.connected) {
758
+ this._onConnect();
759
+ }
760
+ });
761
+ }
762
+ // ============ Public Properties ============
763
+ /** Whether the underlying connection is established (connected ≠ ready) */
764
+ get connected() {
765
+ return !this._detached && this._client.connected;
766
+ }
767
+ /** The injected core client (owned by the app, not the wrapper) */
768
+ get client() {
769
+ return this._client;
770
+ }
771
+ /** The local user's info (available after ready) */
772
+ get localUser() {
773
+ return this._localUser;
774
+ }
775
+ /** All currently joined documents */
776
+ get documents() {
777
+ return this._documents;
778
+ }
779
+ // ============ Lifecycle ============
780
+ /**
781
+ * Resolves once the wrapper's first setup completed (identity, lobby and
782
+ * configured documents ready — equivalently, once 'connected' has fired).
783
+ * Rejects only if detach() is called before that. Client auth failures
784
+ * surface via the app's own `await client.connect()`, not here.
785
+ */
786
+ ready() {
787
+ return this._readyPromise;
788
+ }
789
+ /**
790
+ * Detach from the client: remove every handler this wrapper added,
791
+ * unsubscribe its topics and lobby (when connected), clear state.
792
+ * Terminal and idempotent; never touches the socket. To use collab again,
793
+ * construct a new instance.
794
+ */
795
+ detach() {
796
+ if (this._detached)
797
+ return;
798
+ this._log('Detaching...');
799
+ this._detached = true;
800
+ this._epoch++; // aborts any in-flight setup at its next checkpoint
801
+ if (this._lobbyRefreshTimer) {
802
+ clearTimeout(this._lobbyRefreshTimer);
803
+ this._lobbyRefreshTimer = null;
804
+ }
805
+ // Remove all client handlers by stored ref
806
+ this._client.off('connect', this._onConnectRef);
807
+ this._client.off('disconnect', this._onDisconnectRef);
808
+ this._client.off('reconnect', this._onReconnectRef);
809
+ this._client.off('error', this._onErrorRef);
810
+ this._client.off('presence:join', this._onPresenceJoinRef);
811
+ this._client.off('presence:leave', this._onPresenceLeaveRef);
812
+ this._client.off('presence:update', this._onPresenceUpdateRef);
813
+ this._client.off('lobbyPresence:join', this._onLobbyJoinRef);
814
+ this._client.off('lobbyPresence:leave', this._onLobbyLeaveRef);
815
+ this._client.off('lobbyPresence:update', this._onLobbyUpdateRef);
816
+ // Documents: handler-specific off + connected-gated server unsubscribe.
817
+ // _cleanup also clears each document's cursor-throttle and idle timers.
818
+ for (const name of [...this._documents.keys()]) {
819
+ this._documents.get(name)._cleanup();
820
+ this._documents.delete(name);
821
+ }
822
+ // Lobby: server unsubscribe is best-effort and needs a live socket
823
+ if (this._lobby && this._client.connected) {
824
+ try {
825
+ this._lobby.unsubscribe();
826
+ }
827
+ catch {
828
+ /* best-effort */
829
+ }
830
+ }
831
+ this._lobby = null;
832
+ this._onlineUsers.clear();
833
+ this._actorToUserId.clear();
834
+ this._localUser = null;
835
+ releaseWrapper(this._client, this._options.appName);
836
+ if (!this._isReady) {
837
+ this._readyReject(new Error('NoLagCollab detached before ready'));
838
+ }
839
+ }
840
+ // ============ Private: Epoch Setup ============
841
+ _onConnect() {
842
+ this._epoch++;
843
+ void this._runSetup(this._epoch);
844
+ }
845
+ /**
846
+ * One setup pass per connection epoch. Serves both initial setup (epoch 1)
847
+ * and reconnect restore (epoch > 1). Aborts silently whenever a newer
848
+ * epoch started or the wrapper detached — checked after every await.
849
+ */
850
+ async _runSetup(epoch) {
851
+ const stale = () => epoch !== this._epoch || this._detached;
852
+ this._log(this._isReady ? 'Restoring after reconnect...' : 'Setting up...');
853
+ // Identity (client.actorId is guaranteed post-auth)
854
+ if (!this._localUser) {
855
+ this._localUser = {
856
+ userId: this._userId,
857
+ actorTokenId: this._client.actorId,
858
+ username: this._options.username,
859
+ avatar: this._options.avatar,
860
+ color: this._options.color,
861
+ status: 'active',
862
+ metadata: this._options.metadata,
863
+ joinedAt: Date.now(),
864
+ isLocal: true,
865
+ };
866
+ this._log('Local user:', this._localUser.userId, '→', this._localUser.actorTokenId);
867
+ }
868
+ else {
869
+ this._localUser.actorTokenId = this._client.actorId;
870
+ }
871
+ // Lobby: subscribe every epoch (idempotent server-side) and diff-hydrate
872
+ // from the returned snapshot — one path for setup and restore.
873
+ if (!this._lobby) {
874
+ this._lobby = this._client.setApp(this._options.appName).setLobby(LOBBY_ID);
875
+ }
876
+ try {
877
+ const state = await this._lobby.subscribe();
878
+ if (stale())
879
+ return;
880
+ this._diffHydrateOnlineUsers(state);
881
+ this._log('Lobby subscribed, online users:', this._onlineUsers.size);
882
+ }
883
+ catch (err) {
884
+ if (stale())
885
+ return;
886
+ this._log('Lobby subscription failed:', err);
887
+ }
888
+ if (!this._isReady) {
889
+ // First successful setup: auto-join configured documents
890
+ for (const name of this._options.documents) {
891
+ this._subscribeDocumentInternal(name);
892
+ }
893
+ }
894
+ else {
895
+ // Server auto-restored topic subscriptions; only room-scoped presence
896
+ // needs re-applying (the core does not restore it).
897
+ for (const doc of this._documents.values()) {
898
+ doc._updateLocalPresence();
899
+ }
900
+ }
901
+ if (stale())
902
+ return;
903
+ // Ready keys on the first setup that COMPLETES, not on epoch 1: an
904
+ // epoch aborted by a racing reconnect must not strand ready().
905
+ if (!this._isReady) {
906
+ this._isReady = true;
907
+ this._readyResolve();
908
+ this.emit('connected');
909
+ }
910
+ else {
911
+ this.emit('reconnected');
912
+ }
913
+ // Deferred lobby refetch: catches users who joined during the setup
914
+ // window (e.g. simultaneous multi-tab connects).
915
+ this._scheduleLobbyRefresh(epoch);
916
+ }
917
+ _scheduleLobbyRefresh(epoch) {
918
+ if (this._lobbyRefreshTimer)
919
+ clearTimeout(this._lobbyRefreshTimer);
920
+ this._lobbyRefreshTimer = setTimeout(() => {
921
+ this._lobbyRefreshTimer = null;
922
+ if (epoch !== this._epoch || this._detached || !this._client.connected || !this._lobby) {
923
+ return;
924
+ }
925
+ this._lobby
926
+ .fetchPresence()
927
+ .then((state) => {
928
+ if (epoch !== this._epoch || this._detached)
929
+ return;
930
+ this._diffHydrateOnlineUsers(state);
931
+ })
932
+ .catch(() => {
933
+ /* best-effort */
934
+ });
935
+ }, LOBBY_REFRESH_DELAY_MS);
936
+ }
937
+ // ============ Document Management ============
938
+ /**
939
+ * Join a collaborative document. Creates, subscribes, and activates it.
940
+ * Returns an existing document if already joined.
941
+ */
942
+ joinDocument(name) {
943
+ this._assertUsable();
944
+ let doc = this._documents.get(name);
945
+ if (!doc) {
946
+ doc = this._subscribeDocumentInternal(name);
947
+ doc._activate();
948
+ }
949
+ return doc;
950
+ }
951
+ /**
952
+ * Leave a collaborative document. Fully unsubscribes and removes it.
953
+ */
954
+ leaveDocument(name) {
955
+ const doc = this._documents.get(name);
956
+ if (!doc)
957
+ return;
958
+ this._log('Leaving document:', name);
959
+ doc._cleanup();
960
+ this._documents.delete(name);
961
+ }
962
+ /**
963
+ * Get all joined documents.
964
+ */
965
+ getDocuments() {
966
+ return Array.from(this._documents.values());
967
+ }
968
+ // ============ Global Presence ============
969
+ /**
970
+ * Get all users currently online across all documents.
971
+ */
972
+ getOnlineUsers() {
973
+ return Array.from(this._onlineUsers.values());
974
+ }
975
+ // ============ Private: Guards ============
976
+ _assertUsable() {
977
+ if (this._detached) {
978
+ throw new Error('NoLagCollab has been detached — construct a new instance');
979
+ }
980
+ if (!this._isReady || !this._localUser) {
981
+ throw new Error('NoLagCollab not ready — await ready() or the "connected" event');
982
+ }
983
+ }
984
+ // ============ Private: Document Setup ============
985
+ _subscribeDocumentInternal(name) {
986
+ this._log('Subscribing document:', name);
987
+ const roomContext = this._client.setApp(this._options.appName).setRoom(name);
988
+ const doc = new CollabDocument(name, roomContext, this._localUser, this._options, createLogger(`CollabDocument:${name}`, this._options.debug), () => this._client.connected);
989
+ this._documents.set(name, doc);
990
+ doc._subscribe();
991
+ return doc;
992
+ }
993
+ // ============ Private: Scope Filtering ============
994
+ /**
995
+ * On a shared client, presence events from other apps' wrappers arrive on
996
+ * the same connection-level events. Wrappers stamp their presence with a
997
+ * `__scope` (their appName); a mismatched tag means another app's data.
998
+ * Untagged presence is accepted (older peers in this same app).
999
+ */
1000
+ _foreignScope(data) {
1001
+ const scope = data?.__scope;
1002
+ return typeof scope === 'string' && scope !== this._options.appName;
1003
+ }
1004
+ // ============ Private: Room Presence ============
1005
+ _handleRoomPresenceJoin(data) {
1006
+ if (data.actorTokenId === this._localUser?.actorTokenId)
1007
+ return;
1008
+ const presenceData = data.presence;
1009
+ if (!presenceData?.userId || this._foreignScope(presenceData))
1010
+ return;
1011
+ const user = this._presenceToUser(data.actorTokenId, presenceData);
1012
+ this._actorToUserId.set(data.actorTokenId, user.userId);
1013
+ if (!this._onlineUsers.has(user.userId)) {
1014
+ this._onlineUsers.set(user.userId, user);
1015
+ this.emit('userOnline', user);
1016
+ }
1017
+ // Route to all documents
1018
+ for (const doc of this._documents.values()) {
1019
+ doc._handlePresenceJoin(data.actorTokenId, presenceData);
1020
+ }
1021
+ }
1022
+ _handleRoomPresenceLeave(data) {
1023
+ if (data.actorTokenId === this._localUser?.actorTokenId)
1024
+ return;
1025
+ // Route to all documents
1026
+ for (const doc of this._documents.values()) {
1027
+ doc._handlePresenceLeave(data.actorTokenId);
1028
+ }
1029
+ }
1030
+ _handleRoomPresenceUpdate(data) {
1031
+ if (data.actorTokenId === this._localUser?.actorTokenId)
1032
+ return;
1033
+ const presenceData = data.presence;
1034
+ if (!presenceData?.userId || this._foreignScope(presenceData))
1035
+ return;
1036
+ if (this._onlineUsers.has(presenceData.userId)) {
1037
+ const user = this._presenceToUser(data.actorTokenId, presenceData);
1038
+ this._onlineUsers.set(user.userId, user);
1039
+ }
1040
+ // Route to all documents
1041
+ for (const doc of this._documents.values()) {
1042
+ doc._handlePresenceUpdate(data.actorTokenId, presenceData);
1043
+ }
1044
+ }
1045
+ // ============ Private: Lobby ============
1046
+ _handleLobbyJoin(event) {
1047
+ const { actorId, data } = event;
1048
+ if (actorId === this._localUser?.actorTokenId)
1049
+ return;
1050
+ const presenceData = data;
1051
+ if (!presenceData.userId || this._foreignScope(presenceData))
1052
+ return;
1053
+ const user = this._presenceToUser(actorId, presenceData);
1054
+ this._actorToUserId.set(actorId, user.userId);
1055
+ if (!this._onlineUsers.has(user.userId)) {
1056
+ this._onlineUsers.set(user.userId, user);
1057
+ this.emit('userOnline', user);
1058
+ }
1059
+ }
1060
+ _handleLobbyLeave(event) {
1061
+ const { actorId, data } = event;
1062
+ if (actorId === this._localUser?.actorTokenId)
1063
+ return;
1064
+ const presenceData = data;
1065
+ if (this._foreignScope(presenceData))
1066
+ return;
1067
+ const userId = presenceData?.userId
1068
+ || this._actorToUserId.get(actorId)
1069
+ || this._findUserIdByActorId(actorId);
1070
+ if (userId) {
1071
+ const user = this._onlineUsers.get(userId);
1072
+ if (user) {
1073
+ this._onlineUsers.delete(userId);
1074
+ this._actorToUserId.delete(actorId);
1075
+ this.emit('userOffline', user);
1076
+ }
1077
+ }
1078
+ }
1079
+ _handleLobbyUpdate(event) {
1080
+ const { actorId, data } = event;
1081
+ if (actorId === this._localUser?.actorTokenId)
1082
+ return;
1083
+ const presenceData = data;
1084
+ if (!presenceData.userId || this._foreignScope(presenceData))
1085
+ return;
1086
+ const user = this._presenceToUser(actorId, presenceData);
1087
+ this._onlineUsers.set(user.userId, user);
1088
+ }
1089
+ /**
1090
+ * Reconcile the online-user map against a fresh lobby snapshot, emitting
1091
+ * only the deltas (userOffline for vanished, userOnline for new). One path
1092
+ * for initial hydration, reconnect restore, and the deferred refetch.
1093
+ */
1094
+ _diffHydrateOnlineUsers(state) {
1095
+ // Build the fresh user set from the snapshot
1096
+ const fresh = new Map();
1097
+ const freshActors = new Map();
1098
+ for (const roomId of Object.keys(state)) {
1099
+ const roomPresence = state[roomId];
1100
+ for (const actorId of Object.keys(roomPresence)) {
1101
+ if (actorId === this._localUser?.actorTokenId)
1102
+ continue;
1103
+ const raw = roomPresence[actorId];
1104
+ // Server returns full actor records with presence nested under .presence
1105
+ const presenceData = (raw?.presence ?? raw);
1106
+ if (presenceData?.userId && !this._foreignScope(presenceData)) {
1107
+ if (!fresh.has(presenceData.userId)) {
1108
+ fresh.set(presenceData.userId, this._presenceToUser(actorId, presenceData));
1109
+ }
1110
+ freshActors.set(actorId, presenceData.userId);
1111
+ }
1112
+ }
1113
+ }
1114
+ // Vanished users
1115
+ for (const [userId, user] of [...this._onlineUsers]) {
1116
+ if (!fresh.has(userId)) {
1117
+ this._onlineUsers.delete(userId);
1118
+ for (const [actorId, mappedUserId] of [...this._actorToUserId]) {
1119
+ if (mappedUserId === userId)
1120
+ this._actorToUserId.delete(actorId);
1121
+ }
1122
+ this.emit('userOffline', user);
1123
+ }
1124
+ }
1125
+ // New users
1126
+ for (const [userId, user] of fresh) {
1127
+ if (!this._onlineUsers.has(userId)) {
1128
+ this._onlineUsers.set(userId, user);
1129
+ this.emit('userOnline', user);
1130
+ }
1131
+ }
1132
+ for (const [actorId, userId] of freshActors) {
1133
+ this._actorToUserId.set(actorId, userId);
1134
+ }
1135
+ }
1136
+ // ============ Private: Helpers ============
1137
+ _presenceToUser(actorTokenId, data) {
1138
+ return {
1139
+ userId: data.userId,
1140
+ actorTokenId,
1141
+ username: data.username,
1142
+ avatar: data.avatar,
1143
+ color: data.color,
1144
+ status: data.status ?? 'active',
1145
+ metadata: data.metadata,
1146
+ joinedAt: Date.now(),
1147
+ isLocal: false,
1148
+ };
1149
+ }
1150
+ _findUserIdByActorId(actorTokenId) {
1151
+ for (const user of this._onlineUsers.values()) {
1152
+ if (user.actorTokenId === actorTokenId)
1153
+ return user.userId;
1154
+ }
1155
+ return undefined;
1156
+ }
1157
+ }
1158
+
1159
+ export { CollabDocument, EventEmitter, NoLagCollab };
1160
+ //# sourceMappingURL=react-native.js.map