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