@pluv/client 5.0.0 → 5.0.2

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/src/PluvRoom.ts DELETED
@@ -1,1613 +0,0 @@
1
- import type {
2
- AbstractCrdtDocFactory,
3
- InferCrdtJson,
4
- InferDoc,
5
- InferDocLike,
6
- InferStorage,
7
- NoopCrdtDocFactory,
8
- } from "@pluv/crdt";
9
- import type {
10
- BaseIOEventRecord,
11
- BaseUser,
12
- BroadcastProxy,
13
- CrdtDocLike,
14
- EventMessage,
15
- EventNotifierSubscriptionCallback,
16
- EventProxy,
17
- IOEventMessage,
18
- IOLike,
19
- Id,
20
- InferIOAuthorize,
21
- InferIOAuthorizeUser,
22
- InferIOInput,
23
- InferIOOutput,
24
- InputZodLike,
25
- JsonObject,
26
- MergeEvents,
27
- OptionalProps,
28
- OtherSubscriptionCallback,
29
- OthersSubscriptionCallback,
30
- RoomEventListenerMap,
31
- RoomLike,
32
- StateNotifierSubjects,
33
- StorageProxy,
34
- StorageRootSubscriptionCallback,
35
- StorageSubscriptionCallback,
36
- SubscribeProxy,
37
- SubscriptionCallback,
38
- UpdateMyPresenceAction,
39
- UserInfo,
40
- WebSocketConnection,
41
- WebSocketState,
42
- } from "@pluv/types";
43
- import { ConnectionState, StorageState } from "@pluv/types";
44
- import type { AbstractStorageStore } from "./AbstractStorageStore";
45
- import type { CrdtManagerOptions } from "./CrdtManager";
46
- import { CrdtManager } from "./CrdtManager";
47
- import { CrdtNotifier } from "./CrdtNotifier";
48
- import { EventNotifier } from "./EventNotifier";
49
- import { ListenerManager } from "./ListenerManager";
50
- import { PluvProcedure } from "./PluvProcedure";
51
- import type { PluvRouterEventConfig } from "./PluvRouter";
52
- import { PluvRouter } from "./PluvRouter";
53
- import { StateNotifier } from "./StateNotifier";
54
- import { StorageStore } from "./StorageStore";
55
- import type {
56
- AuthorizationState,
57
- EventResolver,
58
- EventResolverContext,
59
- InternalSubscriptions,
60
- PluvClientLimits,
61
- PublicKey,
62
- WithMetadata,
63
- } from "./types";
64
- import type { UsersManagerConfig } from "./UsersManager";
65
- import { UsersManager } from "./UsersManager";
66
- import { UsersNotifier } from "./UsersNotifier";
67
- import { debounce } from "./utils";
68
-
69
- const ADD_TO_STORAGE_STATE_DEBOUNCE_MS = 1_000;
70
- const HEARTBEAT_INTERVAL_MS = 10_000;
71
- const PONG_TIMEOUT_MS = 2_000;
72
-
73
- const RECONNECT_TIMEOUT_MS = 5_000;
74
- const MIN_RECONNECT_TIMEOUT_MS = 1_000;
75
- const MAX_RECONNECT_TIMEOUT_MS = 60_000;
76
-
77
- const ORIGIN_INITIALIZED = "$initialized";
78
- const ORIGIN_STORAGE_UPDATED = "$storageUpdated";
79
-
80
- declare global {
81
- var process: {
82
- env: {
83
- [key: string]: string | undefined;
84
- };
85
- };
86
- }
87
-
88
- export const DEFAULT_PLUV_CLIENT_ADDON = <
89
- TIO extends IOLike,
90
- TMetadata extends JsonObject,
91
- TPresence extends Record<string, any>,
92
- TCrdt extends AbstractCrdtDocFactory<any, any>,
93
- >(
94
- input: PluvRoomAddonInput<TIO, TMetadata, TPresence, TCrdt>,
95
- ): PluvRoomAddonResult => ({
96
- storage: new StorageStore(input.room.id),
97
- });
98
-
99
- interface WindowListeners {
100
- onNavigatorOffline: () => void;
101
- onNavigatorOnline: () => void;
102
- onVisibilityChange: () => void;
103
- onWindowFocus: () => void;
104
- }
105
-
106
- interface WebSocketListeners {
107
- onClose: (event: CloseEvent) => void;
108
- onError: (event: Event) => void;
109
- onMessage: (message: MessageEvent<string>) => void;
110
- onOpen: (event: Event) => void;
111
- }
112
-
113
- interface IntervalIds {
114
- heartbeat: number | null;
115
- }
116
-
117
- interface TimeoutIds {
118
- pong: number | null;
119
- reconnect: number | null;
120
- }
121
-
122
- export interface EndpointParams<TMetadata extends JsonObject> {
123
- metadata: TMetadata;
124
- room: string;
125
- }
126
- export type AuthEndpoint<TMetadata extends JsonObject> =
127
- | string
128
- | ((params: EndpointParams<TMetadata>) => string | FetchOptions)
129
- | true;
130
- export type WsEndpoint<TMetadata extends JsonObject> =
131
- | string
132
- | ((params: EndpointParams<TMetadata>) => string);
133
-
134
- type FetchOptions = { url: string; options?: RequestInit };
135
-
136
- export type RoomEndpoints<TIO extends IOLike<any, any, any>, TMetadata extends JsonObject> = {
137
- wsEndpoint?: WsEndpoint<TMetadata>;
138
- } & (InferIOAuthorizeUser<InferIOAuthorize<TIO>> extends BaseUser
139
- ? { authEndpoint: AuthEndpoint<TMetadata> }
140
- : { authEndpoint?: undefined });
141
-
142
- interface InternalListeners {
143
- onAuthorizationFail: (error: Error) => void;
144
- }
145
-
146
- export type PluvRoomAddon<
147
- TIO extends IOLike,
148
- TMetadata extends JsonObject,
149
- TPresence extends Record<string, any>,
150
- TCrdt extends AbstractCrdtDocFactory<any, any>,
151
- > = (input: PluvRoomAddonInput<TIO, TMetadata, TPresence, TCrdt>) => Partial<PluvRoomAddonResult>;
152
-
153
- export interface PluvRoomAddonInput<
154
- TIO extends IOLike,
155
- TMetadata extends JsonObject,
156
- TPresence extends Record<string, any>,
157
- TCrdt extends AbstractCrdtDocFactory<any, any>,
158
- > {
159
- room: PluvRoom<TIO, TMetadata, TPresence, TCrdt>;
160
- }
161
-
162
- export interface PluvRoomAddonResult {
163
- storage: AbstractStorageStore;
164
- }
165
-
166
- export type PluvRoomDebug<TIO extends IOLike> = Id<{
167
- output: readonly (keyof InferIOOutput<TIO>)[];
168
- input: readonly (keyof InferIOInput<TIO>)[];
169
- }>;
170
-
171
- type GetPublickKeyParams<TMetadata extends JsonObject = {}> = WithMetadata<TMetadata>;
172
- type GetAuthEndpointParams<TMetadata extends JsonObject = {}> = WithMetadata<TMetadata>;
173
- type GetWsEndpointParams<TMetadata extends JsonObject = {}> = WithMetadata<TMetadata>;
174
-
175
- export type RoomConnectParams<TMetadata extends JsonObject = {}> = keyof TMetadata extends never
176
- ? []
177
- : [WithMetadata<TMetadata>];
178
-
179
- export interface ReconnectTimeoutMsParams {
180
- attempts: number;
181
- }
182
- export type ReconnectTimeoutMs = number | ((params: ReconnectTimeoutMsParams) => number);
183
-
184
- export type RoomConfig<
185
- TIO extends IOLike,
186
- TMetadata extends JsonObject,
187
- TPresence extends Record<string, any>,
188
- TCrdt extends AbstractCrdtDocFactory<any, any>,
189
- TEvents extends PluvRouterEventConfig<TIO, TPresence, InferStorage<TCrdt>>,
190
- > = Id<
191
- {
192
- addons?: readonly PluvRoomAddon<TIO, TMetadata, TPresence, TCrdt>[];
193
- debug?: boolean | PluvRoomDebug<TIO>;
194
- limits: PluvClientLimits;
195
- onAuthorizationFail?: (error: Error) => void;
196
- metadata?: InputZodLike<TMetadata>;
197
- publicKey?: PublicKey<TMetadata>;
198
- reconnectTimeoutMs?: ReconnectTimeoutMs;
199
- router?: PluvRouter<TIO, TPresence, InferStorage<TCrdt>, TEvents>;
200
- } & RoomEndpoints<TIO, TMetadata> &
201
- Pick<CrdtManagerOptions<TCrdt>, "initialStorage"> &
202
- UsersManagerConfig<TPresence>
203
- >;
204
-
205
- export class PluvRoom<
206
- TIO extends IOLike<any, any, any>,
207
- TMetadata extends JsonObject = {},
208
- TPresence extends Record<string, any> = {},
209
- TCrdt extends AbstractCrdtDocFactory<any, any> = NoopCrdtDocFactory,
210
- TEvents extends PluvRouterEventConfig<TIO, TPresence, InferStorage<TCrdt>> = {},
211
- > implements RoomLike<TIO, InferDoc<TCrdt>, TPresence, InferStorage<TCrdt>> {
212
- readonly _endpoints: RoomEndpoints<TIO, TMetadata>;
213
-
214
- public readonly id: string;
215
- public readonly metadata?: InputZodLike<TMetadata>;
216
-
217
- private readonly _crdtManager: CrdtManager<TCrdt>;
218
- private readonly _crdtNotifier = new CrdtNotifier<InferStorage<TCrdt>>();
219
- private readonly _debug: boolean | PluvRoomDebug<TIO>;
220
- private readonly _eventNotifier = new EventNotifier<MergeEvents<TEvents, TIO>>();
221
- private readonly _intervals: IntervalIds = {
222
- heartbeat: null,
223
- };
224
- private readonly _limits: PluvClientLimits;
225
- private readonly _listenerManager = new ListenerManager();
226
- private readonly _listeners: InternalListeners;
227
- private readonly _publicKey: PublicKey<TMetadata> | null = null;
228
- private readonly _reconnectTimeoutMs: ReconnectTimeoutMs;
229
- private readonly _router: PluvRouter<TIO, TPresence, InferStorage<TCrdt>, TEvents>;
230
- private readonly _stateNotifier = new StateNotifier<TIO, TPresence>();
231
- private readonly _storageStore: AbstractStorageStore;
232
- private readonly _subscriptions: InternalSubscriptions = {
233
- observeCrdt: null,
234
- };
235
- private readonly _timeouts: TimeoutIds = {
236
- pong: null,
237
- reconnect: null,
238
- };
239
- private readonly _usersManager: UsersManager<TIO, TPresence>;
240
- private readonly _usersNotifier = new UsersNotifier<TIO, TPresence>();
241
-
242
- private _lastMetadata: TMetadata | null = null;
243
- private _state: WebSocketState<TIO> = {
244
- authorization: {
245
- token: null,
246
- user: null,
247
- },
248
- connection: {
249
- attempts: 0,
250
- id: null,
251
- state: ConnectionState.Untouched,
252
- },
253
- storage: {
254
- state: StorageState.Unavailable,
255
- },
256
- webSocket: null,
257
- };
258
- private _windowListeners: WindowListeners | null = null;
259
- private _wsListeners: WebSocketListeners | null = null;
260
-
261
- constructor(room: string, options: RoomConfig<TIO, TMetadata, TPresence, TCrdt, TEvents>) {
262
- const {
263
- addons = [],
264
- authEndpoint,
265
- debug = false,
266
- initialPresence,
267
- initialStorage,
268
- limits,
269
- metadata,
270
- onAuthorizationFail,
271
- presence,
272
- publicKey,
273
- reconnectTimeoutMs = RECONNECT_TIMEOUT_MS,
274
- router,
275
- wsEndpoint,
276
- } = options;
277
-
278
- this.id = room;
279
- this.metadata = metadata;
280
-
281
- const addon = this._getAddon(addons);
282
- const { storage } = {
283
- ...DEFAULT_PLUV_CLIENT_ADDON({ room: this }),
284
- ...addon({ room: this }),
285
- };
286
- this._storageStore = storage;
287
-
288
- this._debug = debug;
289
- this._endpoints = { authEndpoint, wsEndpoint } as RoomEndpoints<TIO, TMetadata>;
290
- this._limits = limits;
291
- this._reconnectTimeoutMs = reconnectTimeoutMs;
292
-
293
- if (!!publicKey) this._publicKey = publicKey;
294
-
295
- this._listeners = {
296
- onAuthorizationFail: (error) => {
297
- onAuthorizationFail?.(error);
298
- },
299
- };
300
-
301
- this._router =
302
- router ??
303
- (new PluvRouter({}) as PluvRouter<TIO, TPresence, InferStorage<TCrdt>, TEvents>);
304
- this._usersManager = new UsersManager<TIO, TPresence>({
305
- initialPresence,
306
- limits: this._limits,
307
- presence,
308
- });
309
- this._crdtManager = new CrdtManager<TCrdt>({ initialStorage });
310
- }
311
-
312
- public get webSocket(): WebSocket | null {
313
- return this._state.webSocket;
314
- }
315
-
316
- public addEventListener<TKind extends keyof RoomEventListenerMap>(
317
- kind: TKind,
318
- handler: RoomEventListenerMap[TKind],
319
- ): () => void {
320
- return this._listenerManager.subscribe(kind, handler as any);
321
- }
322
-
323
- public broadcast = new Proxy(
324
- async <TEvent extends keyof InferIOInput<MergeEvents<TEvents, TIO>>>(
325
- event: TEvent,
326
- data: Id<InferIOInput<MergeEvents<TEvents, TIO>>[TEvent]>,
327
- ): Promise<void> => {
328
- if (!this._state.webSocket) return;
329
- if (this._state.connection.state !== ConnectionState.Open) return;
330
-
331
- const type = event.toString();
332
-
333
- const procedure = this._router._defs.events[type] as PluvProcedure<
334
- TIO,
335
- any,
336
- any,
337
- TPresence,
338
- TCrdt,
339
- ""
340
- > | null;
341
-
342
- if (!procedure?.config.broadcast) {
343
- this._sendMessage({ data, type });
344
-
345
- return;
346
- }
347
-
348
- const myself = this._usersManager.myself;
349
-
350
- if (!myself) return;
351
-
352
- const parsed = procedure.config.input ? procedure.config.input.parse(data) : data;
353
- const context: EventResolverContext<TIO, TPresence, InferDocLike<TCrdt>> = {
354
- doc: this._crdtManager.doc,
355
- others: this._usersManager.getOthers(),
356
- room: this.id,
357
- user: myself,
358
- };
359
-
360
- const output = await (
361
- procedure.config.broadcast as EventResolver<
362
- TIO,
363
- any,
364
- any,
365
- TPresence,
366
- InferStorage<TCrdt>
367
- >
368
- )(parsed, context);
369
-
370
- Object.entries(output).forEach(([_type, _data]) => {
371
- this._sendMessage({ data: _data, type: _type });
372
- });
373
- },
374
- {
375
- get(fn, prop) {
376
- return async (
377
- data: Id<InferIOInput<MergeEvents<TEvents, TIO>>[any]>,
378
- ): Promise<void> => {
379
- return await fn(prop, data);
380
- };
381
- },
382
- },
383
- ) as BroadcastProxy<TIO, TEvents>;
384
-
385
- public canRedo = (): boolean => {
386
- return !!this._crdtManager.doc.canRedo();
387
- };
388
-
389
- public canUndo = (): boolean => {
390
- return !!this._crdtManager.doc.canUndo();
391
- };
392
-
393
- public async connect(...args: RoomConnectParams<TMetadata>): Promise<void> {
394
- const params = (args[0] ?? {}) as WithMetadata<TMetadata>;
395
- const metadata = params.metadata as TMetadata;
396
-
397
- this._setMetadata(metadata);
398
-
399
- const canConnect = [
400
- ConnectionState.Closed,
401
- ConnectionState.Unavailable,
402
- ConnectionState.Untouched,
403
- ].some((state) => this._state.connection.state === state);
404
-
405
- if (!canConnect) return;
406
-
407
- this._clearTimeout(this._timeouts.reconnect);
408
- this._updateState((oldState) => {
409
- oldState.connection.state = ConnectionState.Connecting;
410
-
411
- return oldState;
412
- });
413
-
414
- await this._storageStore.initialize();
415
-
416
- const wsEndpoint = this._getWsEndpoint(this.id, params);
417
- const url = new URL(wsEndpoint);
418
-
419
- let authToken: string | null = null;
420
- let webSocket: WebSocket;
421
-
422
- try {
423
- const publicKey = this._getPublicKey(params);
424
-
425
- authToken = await this._getAuthorization(this.id, params);
426
-
427
- if (authToken) url.searchParams.set("token", encodeURIComponent(authToken));
428
- if (publicKey) url.searchParams.set("public_key", encodeURIComponent(publicKey));
429
-
430
- webSocket = new WebSocket(url.toString());
431
- } catch (err) {
432
- this._updateState((oldState) => {
433
- oldState.connection.attempts += 1;
434
-
435
- return oldState;
436
- });
437
-
438
- await this._storageStore.destroy();
439
- this._pollReconnect();
440
- await Promise.resolve(this._onAuthorizationFail(err));
441
-
442
- return;
443
- }
444
-
445
- this._updateState((oldState) => {
446
- oldState.connection.attempts = 0;
447
- oldState.authorization.token = authToken;
448
- oldState.storage.state = StorageState.Loading;
449
- oldState.webSocket = webSocket;
450
-
451
- return oldState;
452
- });
453
-
454
- this._attachWindowListeners();
455
- this._attachWsListeners();
456
- }
457
-
458
- public async disconnect(): Promise<void> {
459
- if (!this._state.webSocket) return;
460
-
461
- const canDisconnect = [ConnectionState.Connecting, ConnectionState.Open].some(
462
- (state) => this._state.connection.state === state,
463
- );
464
-
465
- if (!canDisconnect) return;
466
-
467
- this._closeWs();
468
- this._clearInterval(this._intervals.heartbeat);
469
- this._clearTimeout(this._timeouts.reconnect);
470
- this._updateState((oldState) => {
471
- oldState.authorization.token = null;
472
- oldState.connection.state = ConnectionState.Closed;
473
- oldState.storage.state =
474
- oldState.storage.state === StorageState.Synced
475
- ? StorageState.Offline
476
- : StorageState.Unavailable;
477
- oldState.webSocket = null;
478
-
479
- return oldState;
480
- });
481
-
482
- await this._storageStore.destroy();
483
- this._crdtManager.destroy();
484
- this._stateNotifier.subjects["my-presence"].next(null);
485
- }
486
-
487
- public getConnection = (): WebSocketConnection => {
488
- // Create a read-only clone of the connection state
489
- return Object.freeze(JSON.parse(JSON.stringify(this._state.connection)));
490
- };
491
-
492
- public getDoc = (): CrdtDocLike<InferDoc<TCrdt>, InferStorage<TCrdt>> => {
493
- return this._crdtManager.doc;
494
- };
495
-
496
- public getMyPresence = (): TPresence => {
497
- return this._usersManager.myPresence;
498
- };
499
-
500
- public getMyself = (): Id<UserInfo<TIO, TPresence>> | null => {
501
- return this._usersManager.myself;
502
- };
503
-
504
- public getOther = (connectionId: string): Id<UserInfo<TIO, TPresence>> | null => {
505
- return this._usersManager.getOther(connectionId);
506
- };
507
-
508
- public getOthers = (): readonly Id<UserInfo<TIO, TPresence>>[] => {
509
- return this._usersManager.getOthers();
510
- };
511
-
512
- public getStorage = <TKey extends keyof InferStorage<TCrdt>>(
513
- type: TKey,
514
- ): InferStorage<TCrdt>[TKey] | null => {
515
- const sharedType = this._crdtManager.get(type);
516
-
517
- if (typeof sharedType === "undefined") return null;
518
-
519
- return sharedType;
520
- };
521
-
522
- public getStorageJson(): InferCrdtJson<InferStorage<TCrdt>> | null;
523
- public getStorageJson<TKey extends keyof InferStorage<TCrdt>>(
524
- type: TKey,
525
- ): InferCrdtJson<InferStorage<TCrdt>[TKey]> | null;
526
- public getStorageJson<TKey extends keyof InferStorage<TCrdt>>(type?: TKey) {
527
- if (this._state.connection.id === null) return null;
528
- if (typeof type === "undefined") return this._crdtManager.doc.toJson();
529
-
530
- const sharedType = this._crdtManager.get(type);
531
-
532
- if (typeof sharedType === "undefined") return null;
533
-
534
- return this._crdtManager.doc.toJson(type);
535
- }
536
-
537
- public getStorageLoaded = (): boolean => {
538
- return (
539
- this._state.storage.state === StorageState.Offline ||
540
- this._state.storage.state === StorageState.Synced
541
- );
542
- };
543
-
544
- public redo = (): void => {
545
- this._crdtManager.doc.redo();
546
- };
547
-
548
- public subscribe = new Proxy(
549
- <TSubject extends keyof StateNotifierSubjects<TIO, TPresence>>(
550
- name: TSubject,
551
- callback: SubscriptionCallback<TIO, TPresence, TSubject>,
552
- ): (() => void) => this._stateNotifier.subscribe(name, callback),
553
- {
554
- get: (fn, prop) => {
555
- if (prop === "connection") {
556
- return (callback: SubscriptionCallback<TIO, TPresence, "connection">) => {
557
- return fn("connection", callback);
558
- };
559
- }
560
-
561
- if (prop === "myPresence") {
562
- return (callback: SubscriptionCallback<TIO, TPresence, "my-presence">) => {
563
- return fn("my-presence", callback);
564
- };
565
- }
566
-
567
- if (prop === "myself") {
568
- return (callback: SubscriptionCallback<TIO, TPresence, "myself">) => {
569
- return fn("myself", callback);
570
- };
571
- }
572
-
573
- if (prop === "others") {
574
- return (callback: OthersSubscriptionCallback<TIO, TPresence>) => {
575
- return this._usersNotifier.subscribeOthers(callback);
576
- };
577
- }
578
-
579
- if (prop === "storageLoaded") {
580
- return (callback: SubscriptionCallback<TIO, TPresence, "storage-loaded">) => {
581
- return fn("storage-loaded", callback);
582
- };
583
- }
584
-
585
- if (prop === "event") return this._event;
586
- if (prop === "other") return this._other;
587
- if (prop === "storage") return this.#_storage;
588
- },
589
- },
590
- ) as SubscribeProxy<TIO, TPresence, InferStorage<TCrdt>, TEvents>;
591
-
592
- public transact = (fn: (storage: InferStorage<TCrdt>) => void, origin?: string): void => {
593
- const _origin = origin ?? this._state.connection.id;
594
-
595
- /**
596
- * !HACK
597
- * @description Don't transact anything if there is no origin, because
598
- * that means the user isn't connected yet. This will mean events are
599
- * lost unfortunately.
600
- * @date September 23, 2023
601
- */
602
- if (typeof _origin !== "string") return;
603
-
604
- this._crdtManager.doc.transact(() => {
605
- const storage = this._crdtManager.doc.get();
606
-
607
- fn(storage);
608
- }, _origin);
609
- };
610
-
611
- public undo = (): void => {
612
- this._crdtManager.doc.undo();
613
- };
614
-
615
- public updateMyPresence = (presence: UpdateMyPresenceAction<TPresence>): void => {
616
- const newPresence =
617
- typeof presence === "function" ? presence(this.getMyPresence()) : presence;
618
-
619
- this._usersManager.updateMyPresence(newPresence);
620
-
621
- const myPresence = this._usersManager.myPresence;
622
- const myself = this._usersManager.myself ?? null;
623
-
624
- this._stateNotifier.subjects["my-presence"].next(myPresence);
625
- if (!!myself) this._stateNotifier.subjects.myself.next(myself);
626
-
627
- this.broadcast(
628
- "$updatePresence" as keyof InferIOInput<MergeEvents<TEvents, TIO>>,
629
- { presence: newPresence } as any,
630
- );
631
- };
632
-
633
- private async _addToStorageStore(update: string): Promise<void> {
634
- await this._storageStore.addUpdate(update);
635
-
636
- this._flattenStorageStore();
637
- }
638
-
639
- private _attachWindowListeners(): void {
640
- if (typeof window === "undefined") return;
641
- if (typeof document === "undefined") return;
642
-
643
- this._windowListeners = this._windowListeners || {
644
- onNavigatorOffline: this._onNavigatorOffline.bind(this),
645
- onNavigatorOnline: this._onNavigatorOnline.bind(this),
646
- onVisibilityChange: this._onVisibilityChange.bind(this),
647
- onWindowFocus: this._onWindowFocus.bind(this),
648
- };
649
-
650
- window.addEventListener("offline", this._windowListeners.onNavigatorOffline);
651
- window.addEventListener("online", this._windowListeners.onNavigatorOnline);
652
- document.addEventListener("visibilitychange", this._windowListeners.onVisibilityChange);
653
- window.addEventListener("focus", this._windowListeners.onWindowFocus);
654
- }
655
-
656
- private _attachWsListeners(): void {
657
- if (!this._state.webSocket) return;
658
-
659
- this._wsListeners = this._wsListeners || {
660
- onClose: this._onClose.bind(this),
661
- onError: this._onError.bind(this),
662
- onMessage: this._onMessage.bind(this),
663
- onOpen: this._onOpen.bind(this),
664
- };
665
-
666
- this._state.webSocket.addEventListener("close", this._wsListeners.onClose);
667
- this._state.webSocket.addEventListener("error", this._wsListeners.onError);
668
- this._state.webSocket.addEventListener("message", this._wsListeners.onMessage);
669
- this._state.webSocket.addEventListener("open", this._wsListeners.onOpen);
670
- }
671
-
672
- private _clearInterval(interval: number | null) {
673
- if (Number.isNaN(interval)) return;
674
-
675
- clearInterval(interval as number);
676
- }
677
-
678
- private _clearTimeout(timeout: number | null) {
679
- if (Number.isNaN(timeout)) return;
680
-
681
- clearTimeout(timeout as number);
682
- }
683
-
684
- private _closeWs(): void {
685
- this._subscriptions.observeCrdt?.();
686
-
687
- this._clearInterval(this._intervals.heartbeat);
688
- this._clearTimeout(this._timeouts.pong);
689
- this._detachWindowListeners();
690
- this._usersManager.removeMyself();
691
- this._usersManager.clearConnections();
692
- this._usersNotifier.clear();
693
- this._stateNotifier.subjects.myself.next(null);
694
- this._stateNotifier.subjects.others.next([]);
695
- this._usersNotifier.others.next({ others: [], event: { kind: "clear" } });
696
- this._state.webSocket?.close();
697
-
698
- this._detachWsListeners();
699
- }
700
-
701
- private _detachWindowListeners(): void {
702
- if (!this._windowListeners) return;
703
- if (typeof window === "undefined") return;
704
- if (typeof document === "undefined") return;
705
-
706
- window.removeEventListener("offline", this._windowListeners.onNavigatorOffline);
707
- window.removeEventListener("online", this._windowListeners.onNavigatorOnline);
708
- document.removeEventListener("visibilitychange", this._windowListeners.onVisibilityChange);
709
- window.removeEventListener("focus", this._windowListeners.onWindowFocus);
710
-
711
- this._windowListeners = null;
712
- }
713
-
714
- private _detachWsListeners(): void {
715
- if (!this._state.webSocket || !this._wsListeners) return;
716
-
717
- this._state.webSocket.removeEventListener("close", this._wsListeners.onClose);
718
- this._state.webSocket.removeEventListener("error", this._wsListeners.onError);
719
- this._state.webSocket.removeEventListener("message", this._wsListeners.onMessage);
720
- this._state.webSocket.removeEventListener("open", this._wsListeners.onOpen);
721
-
722
- this._wsListeners = null;
723
- }
724
-
725
- private _emitSharedTypes(): void {
726
- const sharedTypes = this._crdtManager.doc.get();
727
-
728
- const storageRoot = Object.keys(sharedTypes).reduce(
729
- (acc, prop) => {
730
- const serialized = this._crdtManager.doc.toJson(prop);
731
-
732
- this._crdtNotifier.subject(prop).next(serialized);
733
-
734
- return { ...acc, [prop]: serialized };
735
- },
736
- {} as { [P in keyof InferStorage<TCrdt>]: InferCrdtJson<InferStorage<TCrdt>[P]> },
737
- );
738
-
739
- this._crdtNotifier.rootSubject.next(storageRoot);
740
- }
741
-
742
- private _event = new Proxy(
743
- <TEvent extends keyof InferIOOutput<MergeEvents<TEvents, TIO>>>(
744
- event: TEvent,
745
- callback: EventNotifierSubscriptionCallback<MergeEvents<TEvents, TIO>, any>,
746
- ): (() => void) => this._eventNotifier.subscribe(event, callback),
747
- {
748
- get(fn, prop) {
749
- return (
750
- callback: EventNotifierSubscriptionCallback<MergeEvents<TEvents, TIO>, any>,
751
- ): (() => void) => fn(prop as any, callback);
752
- },
753
- },
754
- ) as EventProxy<TIO, TEvents>;
755
-
756
- private _flattenStorageStore = debounce(
757
- async (): Promise<void> => {
758
- const shouldFlatten = await this._storageStore.getShouldFlatten();
759
-
760
- if (!shouldFlatten) return;
761
-
762
- const updates = await this._storageStore.getUpdates();
763
-
764
- this._crdtManager.applyUpdate({ update: updates, origin: this });
765
-
766
- const encodedState = this._crdtManager.doc.getEncodedState();
767
-
768
- await this._storageStore.flatten(encodedState);
769
- },
770
- { wait: ADD_TO_STORAGE_STATE_DEBOUNCE_MS },
771
- );
772
-
773
- private _getAddon = (
774
- addons: readonly PluvRoomAddon<TIO, TMetadata, TPresence, TCrdt>[],
775
- ): PluvRoomAddon<TIO, TMetadata, TPresence, TCrdt> => {
776
- return addons.reduce<PluvRoomAddon<TIO, TMetadata, TPresence, TCrdt>>(
777
- (acc, addon) => () => ({
778
- ...acc({ room: this }),
779
- ...addon({ room: this }),
780
- }),
781
- DEFAULT_PLUV_CLIENT_ADDON,
782
- );
783
- };
784
-
785
- private _getAuthFetchOptions(
786
- room: string,
787
- params: GetAuthEndpointParams<TMetadata>,
788
- ): FetchOptions | null {
789
- const metadata = params.metadata as TMetadata;
790
-
791
- if (typeof this._endpoints.authEndpoint === "undefined") return null;
792
-
793
- if (this._endpoints.authEndpoint === true) {
794
- return {
795
- url: `/api/pluv/authorize?room=${room}`,
796
- options: {},
797
- };
798
- }
799
-
800
- if (typeof this._endpoints.authEndpoint === "string") {
801
- return {
802
- url: this._endpoints.authEndpoint,
803
- options: {},
804
- };
805
- }
806
-
807
- const result = this._endpoints.authEndpoint({ metadata, room });
808
-
809
- return typeof result === "string" ? { url: result, options: {} } : result;
810
- }
811
-
812
- private async _getAuthorization(
813
- room: string,
814
- params: GetAuthEndpointParams<TMetadata>,
815
- ): Promise<string | null> {
816
- const fetchOptions = this._getAuthFetchOptions(room, params);
817
-
818
- if (!fetchOptions) return null;
819
-
820
- const { url, options } = fetchOptions;
821
- const res = await fetch(url, options);
822
-
823
- if (!res.ok || res.status !== 200) throw new Error("Room is unauthorized");
824
-
825
- try {
826
- return await res.text().then((text) => text.trim());
827
- } catch (err) {
828
- throw new Error(err instanceof Error ? err.message : "Room is unauthorized", {
829
- cause: err,
830
- });
831
- }
832
- }
833
-
834
- private _getPublicKey(params: GetPublickKeyParams<TMetadata>): string | null {
835
- const metadata = params.metadata as TMetadata;
836
-
837
- if (!this._publicKey) return null;
838
- if (typeof this._publicKey === "string") return this._publicKey;
839
-
840
- return this._publicKey({ metadata });
841
- }
842
-
843
- private _getWsEndpoint(room: string, params: GetWsEndpointParams<TMetadata>): string {
844
- const metadata = params.metadata as TMetadata;
845
-
846
- switch (typeof this._endpoints.wsEndpoint) {
847
- case "undefined":
848
- return !!this._getPublicKey(params)
849
- ? `wss://rooms.pluv.io/api/room/${room}`
850
- : `/api/pluv/room/${room}`;
851
- case "string":
852
- return this._endpoints.wsEndpoint;
853
- default:
854
- return this._endpoints.wsEndpoint({ metadata, room });
855
- }
856
- }
857
-
858
- private _handleExit(message: IOEventMessage<TIO>): void {
859
- const { connectionId } = message;
860
-
861
- if (!connectionId) return;
862
- // Should not reach here
863
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
864
-
865
- const clientId = this._usersManager.getClientId(connectionId);
866
- const deleted = this._usersManager.deleteConnection(connectionId);
867
- const others = this._usersManager.getOthers();
868
-
869
- this._stateNotifier.subjects.others.next(others);
870
-
871
- // Should not reach here
872
- if (!deleted) {
873
- console.warn("Could not identify exited connection");
874
- return;
875
- }
876
-
877
- const { data: user, remaining } = deleted;
878
-
879
- this._usersNotifier.others.next({
880
- others,
881
- event: { kind: "leave", user },
882
- });
883
-
884
- /**
885
- * @description A single user can have multiple connections. So we're checking that
886
- * there isn't a remaining connection before choosing to delete that user for other
887
- * connected participants.
888
- * @date April 16, 2025
889
- */
890
- if (!remaining && !!clientId) this._usersNotifier.delete(clientId);
891
- }
892
-
893
- private _handlePresenceUpdatedMessage(message: IOEventMessage<TIO>): void {
894
- const { connectionId } = message;
895
-
896
- if (!connectionId) return;
897
- // Should not reach here
898
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
899
-
900
- const data = message.data as BaseIOEventRecord<InferIOAuthorize<TIO>>["$presenceUpdated"];
901
- const myself = this._usersManager.myself ?? null;
902
-
903
- /**
904
- * !HACK
905
- * @description We're going to have the user's own presence be patched only via local calls
906
- * to this.updateMyPresence. So we'll not update the user's presence in this handler to
907
- * avoid weird update delays to the user's own presence.
908
- *
909
- * However, we will patch the user's own presence if the user has updated their own
910
- * presence via another connection that is not this one (e.g. if the user has opened
911
- * another connection in another browser tab/window somewhere).
912
- * @date April 2, 2025
913
- */
914
- if (myself?.connectionId === connectionId) return;
915
-
916
- const updated = this._usersManager.patchPresence(connectionId, data.presence as TPresence);
917
- const myClientId = !!myself ? this._usersManager.getClientId(myself) : null;
918
- const clientId = this._usersManager.getClientId(connectionId);
919
-
920
- if (!!clientId && myClientId === clientId) {
921
- this._stateNotifier.subjects["my-presence"].next(updated);
922
- this._stateNotifier.subjects.myself.next(this._usersManager.myself);
923
-
924
- return;
925
- }
926
-
927
- if (!!clientId) {
928
- const other = this._usersManager.getOther(connectionId);
929
- const others = this._usersManager.getOthers();
930
-
931
- this._usersNotifier.other(clientId).next(other);
932
- this._stateNotifier.subjects.others.next(others);
933
-
934
- if (!!other) {
935
- this._usersNotifier.others.next({
936
- others,
937
- event: { kind: "update", user: other },
938
- });
939
- }
940
-
941
- return;
942
- }
943
-
944
- /**
945
- * !HACK
946
- * @description User could not be found. Add the connection to keep others up-to-date
947
- * @date April 19, 2025
948
- */
949
- const added = this._usersManager.addConnection({
950
- connectionId,
951
- presence: data.presence as TPresence,
952
- user: message.user as Id<InferIOAuthorizeUser<InferIOAuthorize<TIO>>>,
953
- });
954
- const other = this._usersManager.getOther(connectionId);
955
- const others = this._usersManager.getOthers();
956
-
957
- this._usersNotifier.other(added.clientId).next(other);
958
- this._stateNotifier.subjects.others.next(others);
959
-
960
- this._usersNotifier.others.next({
961
- others,
962
- event: { kind: "update", user: added.data },
963
- });
964
- }
965
-
966
- private _handleReceiveOthers(message: IOEventMessage<TIO>): void {
967
- if (!message.connectionId) return;
968
- // Should not reach here
969
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
970
-
971
- const data = message.data as BaseIOEventRecord<InferIOAuthorize<TIO>>["$othersReceived"];
972
-
973
- Object.keys(data.others).forEach((connectionId) => {
974
- const { presence, user } = data.others[connectionId];
975
-
976
- const result = this._usersManager.addConnection({
977
- connectionId,
978
- presence: presence as TPresence,
979
- user,
980
- });
981
-
982
- if (!!presence) this._usersManager.patchPresence(connectionId, presence as TPresence);
983
- if (result.isMyself) return;
984
-
985
- const clientId = result.clientId;
986
- const other = this._usersManager.getOther(connectionId);
987
-
988
- this._usersNotifier.other(clientId).next(other);
989
- });
990
-
991
- const others = this._usersManager.getOthers();
992
-
993
- this._stateNotifier.subjects.others.next(others);
994
- this._usersNotifier.others.next({
995
- others,
996
- event: { kind: "sync", users: others },
997
- });
998
- }
999
-
1000
- private async _handleRegisteredMessage(message: IOEventMessage<TIO>): Promise<void> {
1001
- const { connectionId } = message;
1002
- const user = message.user as Id<InferIOAuthorizeUser<InferIOAuthorize<TIO>>>;
1003
-
1004
- if (!connectionId) return;
1005
- // Should not reach here
1006
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1007
-
1008
- const data = message.data as BaseIOEventRecord<InferIOAuthorize<TIO>>["$registered"];
1009
- const state = data.state;
1010
-
1011
- this._updateState((oldState) => {
1012
- oldState.connection.id = connectionId;
1013
- oldState.authorization.user = user ?? null;
1014
-
1015
- return oldState;
1016
- });
1017
-
1018
- const userInfo: OptionalProps<UserInfo<TIO, TPresence>, "presence"> = {
1019
- connectionId,
1020
- presence: (data.presence as TPresence | null) ?? undefined,
1021
- user,
1022
- };
1023
- this._usersManager.setMyself(userInfo);
1024
-
1025
- const presence = this._usersManager.myPresence;
1026
- const myself = this._usersManager.myself ?? null;
1027
-
1028
- this._stateNotifier.subjects["my-presence"].next(presence);
1029
- this._stateNotifier.subjects.myself.next(myself);
1030
-
1031
- const update = await (async () => {
1032
- if (!!state) {
1033
- this._logDebug("Retrieving initial state");
1034
- return this._crdtManager.getInitialState();
1035
- }
1036
-
1037
- const resolved = this._crdtManager.resolveEncodedState(
1038
- await this._storageStore.getUpdates(),
1039
- );
1040
-
1041
- if (!!resolved) {
1042
- this._logDebug("Retrieving storage store state");
1043
- return resolved;
1044
- }
1045
-
1046
- this._logDebug("Retrieving initial state");
1047
- return this._crdtManager.getInitialState();
1048
- })();
1049
-
1050
- this._sendMessage({
1051
- type: "$initializeSession",
1052
- data: { presence, update },
1053
- });
1054
- }
1055
-
1056
- private async _handleStorageReceivedMessage(message: IOEventMessage<TIO>): Promise<void> {
1057
- const { connectionId } = message;
1058
-
1059
- if (!connectionId) return;
1060
- // Should not reach here
1061
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1062
-
1063
- const data = message.data as BaseIOEventRecord<InferIOAuthorize<TIO>>["$storageReceived"];
1064
- const changeKind = data.changeKind;
1065
- const state = data.state;
1066
-
1067
- const updates = await this._storageStore.getUpdates();
1068
- const origin = ORIGIN_INITIALIZED;
1069
-
1070
- const updateStorage = (update: string | readonly string[]) => {
1071
- return this._crdtManager.initialized
1072
- ? this._crdtManager.applyUpdate({ update, origin })
1073
- : this._crdtManager.initialize({ update, origin });
1074
- };
1075
-
1076
- if (changeKind === "empty") {
1077
- this._crdtManager.destroy();
1078
- this._crdtManager.initialize({ origin, update: updates });
1079
- } else if (changeKind === "initialized") {
1080
- if (!!updates.length) updateStorage(updates);
1081
- else {
1082
- const encodedState = updateStorage(state).doc.getEncodedState();
1083
-
1084
- this._addToStorageStore(encodedState);
1085
- }
1086
- } else {
1087
- const encodedState = updateStorage(state).doc.getEncodedState();
1088
-
1089
- if (!!updates.length) this._crdtManager.applyUpdate({ update: updates, origin });
1090
-
1091
- await this._addToStorageStore(encodedState);
1092
- }
1093
-
1094
- const encodedState = this._crdtManager.doc.getEncodedState();
1095
-
1096
- this._emitSharedTypes();
1097
- this._observeCrdt();
1098
- this._updateState((oldState) => {
1099
- oldState.storage.state = StorageState.Synced;
1100
-
1101
- return oldState;
1102
- });
1103
- this._stateNotifier.subjects["storage-loaded"].next(true);
1104
-
1105
- this._sendMessage({
1106
- type: "$updateStorage",
1107
- data: { origin, update: encodedState },
1108
- });
1109
- }
1110
-
1111
- private _handleStorageUpdatedMessage(message: IOEventMessage<TIO>): void {
1112
- const { connectionId } = message;
1113
-
1114
- if (!connectionId) return;
1115
- // Should not reach here
1116
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1117
-
1118
- const data = message.data as BaseIOEventRecord<
1119
- InferIOAuthorize<TIO>
1120
- >[typeof ORIGIN_STORAGE_UPDATED];
1121
-
1122
- this._crdtManager.doc.applyEncodedState({
1123
- origin: ORIGIN_STORAGE_UPDATED,
1124
- update: data.state,
1125
- });
1126
-
1127
- const sharedTypes = this._crdtManager.doc.get();
1128
-
1129
- const storageRoot = Object.keys(sharedTypes).reduce(
1130
- (acc, prop) => {
1131
- const serialized = this._crdtManager.doc.toJson(prop);
1132
-
1133
- this._crdtNotifier.subject(prop).next(serialized);
1134
-
1135
- return { ...acc, [prop]: serialized };
1136
- },
1137
- {} as {
1138
- [P in keyof InferStorage<TCrdt>]: InferCrdtJson<InferStorage<TCrdt>[P]>;
1139
- },
1140
- );
1141
-
1142
- this._crdtNotifier.rootSubject.next(storageRoot);
1143
- }
1144
-
1145
- private _handleSyncStateReceived(message: IOEventMessage<TIO>): void {
1146
- const { connectionId } = message;
1147
-
1148
- if (!connectionId) return;
1149
- // Should not reach here
1150
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1151
- if (!this._usersManager.myself) return;
1152
-
1153
- const data = message.data as BaseIOEventRecord<InferIOAuthorize<TIO>>["$syncStateReceived"];
1154
- const active = new Set(data?.connectionIds ?? []);
1155
-
1156
- const quitters = this._usersManager
1157
- .getOthers()
1158
- .filter((other) => !active.has(other.connectionId));
1159
-
1160
- quitters.forEach((quitter) => {
1161
- this._usersManager.deleteConnection(quitter.connectionId);
1162
-
1163
- const remaining = this._usersManager.getOthers();
1164
-
1165
- this._usersNotifier.others.next({
1166
- others: remaining,
1167
- event: { kind: "leave", user: quitter },
1168
- });
1169
- });
1170
-
1171
- const remaining = this._usersManager.getOthers();
1172
-
1173
- this._stateNotifier.subjects.others.next(remaining);
1174
- }
1175
-
1176
- private _handleUserJoinedMessage(message: IOEventMessage<TIO>): void {
1177
- const { connectionId } = message;
1178
-
1179
- if (!connectionId) return;
1180
- // Should not reach here
1181
- if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1182
- if (!this._usersManager.myself) return;
1183
-
1184
- const data = message.data as BaseIOEventRecord<InferIOAuthorize<TIO>>["$userJoined"];
1185
- const myself = this._usersManager.myself;
1186
-
1187
- if (myself.connectionId === connectionId) {
1188
- this._sendMessage({ type: "$getOthers", data: {} });
1189
- return;
1190
- }
1191
-
1192
- const added = this._usersManager.addConnection({
1193
- connectionId,
1194
- presence: data.presence as TPresence,
1195
- user: data.user,
1196
- });
1197
-
1198
- const other = this._usersManager.getOther(connectionId);
1199
- const others = this._usersManager.getOthers();
1200
-
1201
- this._usersNotifier.other(added.clientId).next(other);
1202
- this._stateNotifier.subjects.others.next(others);
1203
-
1204
- this._usersNotifier.others.next({
1205
- others,
1206
- event: { kind: "enter", user: added.data },
1207
- });
1208
- }
1209
-
1210
- private _heartbeat(): void {
1211
- this._clearTimeout(this._timeouts.pong);
1212
- this._timeouts.pong = setTimeout(
1213
- this._reconnect.bind(this),
1214
- PONG_TIMEOUT_MS,
1215
- ) as unknown as number;
1216
-
1217
- /**
1218
- * !HACK
1219
- * @description Send data as a stable string so that the server can react to this in a
1220
- * consistent way.
1221
- * @date July 8, 2024
1222
- */
1223
- this._sendMessage('{"type":"$ping","data":{}}');
1224
- }
1225
-
1226
- private _logDebug(...data: any[]): void {
1227
- if (typeof process === "undefined") return;
1228
- if (process.env?.NODE_ENV === "production") return;
1229
- if (this._debug) console.log(...data);
1230
- }
1231
-
1232
- private _observeCrdt(): void {
1233
- this._subscriptions.observeCrdt?.();
1234
-
1235
- const unsubscribe = this._crdtManager.doc.subscribe((event) => {
1236
- const origin = event.origin ?? null;
1237
-
1238
- this._emitSharedTypes();
1239
-
1240
- if (origin === ORIGIN_INITIALIZED || origin === ORIGIN_STORAGE_UPDATED) {
1241
- return;
1242
- }
1243
-
1244
- this._addToStorageStore(event.update);
1245
-
1246
- if (!this._state.webSocket) return;
1247
- if (!this._state.connection.id) return;
1248
- if (this._state.webSocket.readyState !== WebSocket.OPEN) return;
1249
-
1250
- this._sendMessage({
1251
- type: "$updateStorage",
1252
- data: { origin, update: event.update },
1253
- });
1254
- });
1255
-
1256
- this._subscriptions.observeCrdt = unsubscribe;
1257
- }
1258
-
1259
- private _onAuthorizationFail(error: unknown): void {
1260
- const authError = error instanceof Error ? error : new Error("Authorization failed");
1261
-
1262
- this._listeners.onAuthorizationFail(authError);
1263
-
1264
- this._updateState((oldState) => {
1265
- oldState.connection.state = ConnectionState.Unavailable;
1266
- oldState.storage.state = StorageState.Unavailable;
1267
-
1268
- return oldState;
1269
- });
1270
- }
1271
-
1272
- private async _onClose(event: CloseEvent): Promise<void> {
1273
- this._listenerManager.subjects.close.next(event);
1274
-
1275
- this._logDebug("WebSocket closed");
1276
- if (!!event.reason) this._logDebug(event.reason);
1277
-
1278
- const shouldRetry = [
1279
- // Going away: Client/server is shutting down or navigating
1280
- 1001,
1281
- // Abnormal closure: Usually network error
1282
- 1006,
1283
- // Internal error: may be a larger problem, but try reconnecting for now
1284
- 1011,
1285
- // Service restart: Server restarted
1286
- 1012,
1287
- // Try again later: server overloaded
1288
- 1013,
1289
- // Bad gateway
1290
- 1014,
1291
- ].some((okToRetryCode) => event.code === okToRetryCode);
1292
-
1293
- this._updateState((oldState) => {
1294
- oldState.authorization.token = null;
1295
- oldState.connection.state = shouldRetry
1296
- ? ConnectionState.Unavailable
1297
- : /**
1298
- * !HACK
1299
- * @description Assume these are not recoverable. We're just going to mark this
1300
- * as Closed to avoid reconnect attempts.
1301
- * @date April 28, 2025
1302
- */
1303
- ConnectionState.Closed;
1304
- oldState.storage.state =
1305
- oldState.storage.state === StorageState.Synced
1306
- ? StorageState.Offline
1307
- : StorageState.Unavailable;
1308
- oldState.webSocket = null;
1309
-
1310
- return oldState;
1311
- });
1312
-
1313
- if (shouldRetry) {
1314
- await this._reconnect();
1315
- return;
1316
- }
1317
-
1318
- this._closeWs();
1319
- this._clearTimeout(this._timeouts.reconnect);
1320
- }
1321
-
1322
- /**
1323
- * TODO
1324
- * @description Handle websocket errors in a meaningful way, should they occur
1325
- * @date August 19, 2022
1326
- */
1327
- private _onError(event: Event): void {
1328
- this._listenerManager.subjects.error.next(event);
1329
- }
1330
-
1331
- private _onMessage(event: MessageEvent<string>): void {
1332
- this._listenerManager.subjects.message.next(event);
1333
-
1334
- const message = this._parseMessage(event);
1335
-
1336
- if (!message) return;
1337
-
1338
- const shouldLog =
1339
- typeof this._debug === "boolean"
1340
- ? this._debug
1341
- : this._debug.output.find((value) => value === message.type);
1342
-
1343
- if (shouldLog) {
1344
- this._logDebug("WebSocket event received: ", message.type, message);
1345
- }
1346
-
1347
- this._eventNotifier.subject(message.type as keyof InferIOOutput<TIO>).next(message as any);
1348
-
1349
- switch (message.type) {
1350
- case "$exit": {
1351
- this._handleExit(message);
1352
- return;
1353
- }
1354
- case "$othersReceived": {
1355
- this._handleReceiveOthers(message);
1356
- return;
1357
- }
1358
- case "$pong": {
1359
- this._clearTimeout(this._timeouts.pong);
1360
- return;
1361
- }
1362
- case "$presenceUpdated": {
1363
- this._handlePresenceUpdatedMessage(message);
1364
- return;
1365
- }
1366
- case "$registered": {
1367
- this._handleRegisteredMessage(message);
1368
- return;
1369
- }
1370
- case "$storageReceived": {
1371
- this._handleStorageReceivedMessage(message);
1372
- return;
1373
- }
1374
- case "$storageUpdated": {
1375
- this._handleStorageUpdatedMessage(message);
1376
- return;
1377
- }
1378
- case "$syncStateReceived": {
1379
- this._handleSyncStateReceived(message);
1380
- return;
1381
- }
1382
- case "$userJoined": {
1383
- this._handleUserJoinedMessage(message);
1384
- return;
1385
- }
1386
- default:
1387
- }
1388
- }
1389
-
1390
- private _onOpen(event: Event): void {
1391
- this._listenerManager.subjects.open.next(event);
1392
-
1393
- if (this._state.connection.state !== ConnectionState.Connecting) return;
1394
-
1395
- this._logDebug("WebSocket connected");
1396
- this._updateState((oldState) => {
1397
- oldState.connection.state = ConnectionState.Open;
1398
-
1399
- return oldState;
1400
- });
1401
-
1402
- this._clearInterval(this._intervals.heartbeat);
1403
- this._intervals.heartbeat = setInterval(
1404
- this._heartbeat.bind(this),
1405
- HEARTBEAT_INTERVAL_MS,
1406
- ) as unknown as number;
1407
- }
1408
-
1409
- private async _onNavigatorOffline(): Promise<void> {
1410
- if (this._state.connection.state === ConnectionState.Closed) return;
1411
-
1412
- this._updateState((oldState) => {
1413
- oldState.connection.state = ConnectionState.Unavailable;
1414
- oldState.storage.state =
1415
- oldState.storage.state === StorageState.Synced
1416
- ? StorageState.Offline
1417
- : StorageState.Unavailable;
1418
-
1419
- return oldState;
1420
- });
1421
- }
1422
-
1423
- private async _onNavigatorOnline(): Promise<void> {
1424
- if (this._state.connection.state !== ConnectionState.Unavailable) return;
1425
-
1426
- await this._reconnect();
1427
- }
1428
-
1429
- private async _onVisibilityChange(): Promise<void> {
1430
- if (typeof document === "undefined") return;
1431
- if (document.visibilityState !== "visible") return;
1432
-
1433
- switch (this._state.connection.state) {
1434
- case ConnectionState.Open: {
1435
- this._clearInterval(this._intervals.heartbeat);
1436
- setInterval(this._heartbeat.bind(this), HEARTBEAT_INTERVAL_MS);
1437
-
1438
- return;
1439
- }
1440
- case ConnectionState.Unavailable: {
1441
- await this._reconnect();
1442
-
1443
- return;
1444
- }
1445
- default:
1446
- }
1447
- }
1448
-
1449
- private async _onWindowFocus(): Promise<void> {
1450
- return await this._onVisibilityChange();
1451
- }
1452
-
1453
- private _other = (
1454
- connectionId: string,
1455
- callback: OtherSubscriptionCallback<TIO, TPresence>,
1456
- ): (() => void) => {
1457
- const clientId = this._usersManager.getClientId(connectionId);
1458
-
1459
- if (!clientId) return () => undefined;
1460
-
1461
- return this._usersNotifier.subscribeOther(clientId, callback);
1462
- };
1463
-
1464
- private _parseMessage(message: { data: string | ArrayBuffer }): IOEventMessage<TIO> | null {
1465
- /**
1466
- * !HACK
1467
- * @description We'll only handle stringified JSONs for now
1468
- * @date August 9, 2022
1469
- */
1470
- if (typeof message.data !== "string") return null;
1471
-
1472
- try {
1473
- const config = JSON.parse(message.data);
1474
-
1475
- if (typeof config !== "object") return null;
1476
- if (typeof config.type !== "string") return null;
1477
- if (typeof config.data !== "object") return null;
1478
-
1479
- return config as IOEventMessage<TIO>;
1480
- } catch {
1481
- return null;
1482
- }
1483
- }
1484
-
1485
- private _pollReconnect(): void {
1486
- this._clearTimeout(this._timeouts.reconnect);
1487
-
1488
- const timeoutMs =
1489
- typeof this._reconnectTimeoutMs === "number"
1490
- ? this._reconnectTimeoutMs
1491
- : this._reconnectTimeoutMs({ attempts: this._state.connection.attempts });
1492
- const clampedMs = Math.max(
1493
- Math.min(MIN_RECONNECT_TIMEOUT_MS, timeoutMs),
1494
- MAX_RECONNECT_TIMEOUT_MS,
1495
- );
1496
-
1497
- this._timeouts.reconnect = setTimeout(
1498
- this._reconnect.bind(this),
1499
- clampedMs,
1500
- ) as unknown as number;
1501
- }
1502
-
1503
- private async _reconnect(): Promise<void> {
1504
- this._closeWs();
1505
-
1506
- /**
1507
- * @description User has manually closed this connection. We're not going to retry, since
1508
- * the user probably intends for this to stay closed. They will need to invoke connect
1509
- * themselves.
1510
- * @date April 28, 2025
1511
- */
1512
- if (this._state.connection.state === ConnectionState.Closed) return;
1513
-
1514
- const metadata = this._lastMetadata;
1515
- const params = (
1516
- typeof metadata === "undefined" ? [] : [{ metadata }]
1517
- ) as RoomConnectParams<TMetadata>;
1518
-
1519
- await this.connect(...params);
1520
- }
1521
-
1522
- private _sendMessage(data: string): void;
1523
- private _sendMessage<TMessage extends EventMessage<string, any> = EventMessage<string, any>>(
1524
- data: TMessage,
1525
- ): void;
1526
- private _sendMessage(data: any): void {
1527
- const webSocket = this._state.webSocket;
1528
-
1529
- if (webSocket?.readyState !== WebSocket.OPEN) return;
1530
-
1531
- const dataType: string | null = ((): string | null => {
1532
- if (typeof data === "object") return data.type ?? null;
1533
- if (typeof data !== "string") return null;
1534
-
1535
- try {
1536
- return JSON.parse(data)?.type ?? null;
1537
- } catch {
1538
- return null;
1539
- }
1540
- })();
1541
-
1542
- const shouldLog: boolean =
1543
- typeof this._debug === "boolean"
1544
- ? this._debug
1545
- : !dataType
1546
- ? false
1547
- : this._debug.input.some((value) => value === data.type);
1548
-
1549
- if (shouldLog) this._logDebug("WebSocket event sent: ", data.type, data);
1550
-
1551
- const message = typeof data === "string" ? data : JSON.stringify(data);
1552
-
1553
- webSocket.send(message);
1554
- }
1555
-
1556
- private _setMetadata(metadata: TMetadata): TMetadata {
1557
- const parsed = this.metadata ? this.metadata.parse(metadata) : metadata;
1558
-
1559
- this._lastMetadata = parsed;
1560
-
1561
- return parsed;
1562
- }
1563
-
1564
- #_storage = new Proxy(
1565
- <TKey extends keyof InferStorage<TCrdt>>(
1566
- key: TKey,
1567
- callback: StorageSubscriptionCallback<InferStorage<TCrdt>, TKey>,
1568
- ): (() => void) => this._crdtNotifier.subscribe(key, callback),
1569
- {
1570
- get: (fn, prop) => {
1571
- type _Storage = InferStorage<TCrdt>;
1572
-
1573
- if (!!prop) {
1574
- return (callback: StorageRootSubscriptionCallback<_Storage>) => {
1575
- return this._crdtNotifier.subcribeRoot(callback);
1576
- };
1577
- }
1578
-
1579
- return (callback: StorageSubscriptionCallback<_Storage, keyof _Storage>) => {
1580
- return fn(prop as keyof InferStorage<TCrdt>, callback);
1581
- };
1582
- },
1583
- },
1584
- ) as StorageProxy<InferStorage<TCrdt>>;
1585
-
1586
- private _updateState(
1587
- updater: (oldState: WebSocketState<TIO>) => WebSocketState<TIO>,
1588
- ): WebSocketState<TIO> {
1589
- let authorization: AuthorizationState<TIO>;
1590
-
1591
- try {
1592
- authorization = JSON.parse(JSON.stringify(this._state.authorization));
1593
- } catch {
1594
- throw new Error("User is not JSON serializable");
1595
- }
1596
-
1597
- const oldState: WebSocketState<TIO> = {
1598
- ...this._state,
1599
- authorization,
1600
- connection: JSON.parse(JSON.stringify(this._state.connection)),
1601
- storage: JSON.parse(JSON.stringify(this._state.storage)),
1602
- webSocket: this._state.webSocket,
1603
- };
1604
-
1605
- const newState = updater(oldState);
1606
- this._state = newState;
1607
-
1608
- this._logDebug("WebSocket new state: ", newState);
1609
- this._stateNotifier.subjects.connection.next(newState);
1610
-
1611
- return newState;
1612
- }
1613
- }