@pluv/client 0.0.0-experimental-20250527040415

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1917 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+
41
+ // src/index.ts
42
+ import { ConnectionState as ConnectionState3 } from "@pluv/types";
43
+
44
+ // src/AbstractStorageStore.ts
45
+ var AbstractStorageStore = class {
46
+ constructor(room) {
47
+ this.room = room;
48
+ }
49
+ };
50
+
51
+ // src/constants.ts
52
+ var MAX_PRESENCE_SIZE_BYTES = 512;
53
+ var PLUV_PRESENCE_META_KEY = "__pluv";
54
+
55
+ // src/PluvProcedure.ts
56
+ var PluvProcedure = class _PluvProcedure {
57
+ constructor(config = {}) {
58
+ this._broadcast = null;
59
+ this._input = null;
60
+ const { broadcast, input } = config;
61
+ this._broadcast = broadcast != null ? broadcast : null;
62
+ this._input = input != null ? input : null;
63
+ }
64
+ get config() {
65
+ var _a, _b, _c;
66
+ return {
67
+ broadcast: (_b = (_a = this._broadcast) == null ? void 0 : _a.bind(this)) != null ? _b : null,
68
+ input: (_c = this._input) != null ? _c : null,
69
+ resolver: this._resolver()
70
+ };
71
+ }
72
+ broadcast(resolver) {
73
+ const { broadcast } = this.config;
74
+ if (!!broadcast) throw new Error("Broadcast was already defined for this procedure");
75
+ return new _PluvProcedure(__spreadProps(__spreadValues({}, this.config), {
76
+ broadcast: resolver
77
+ }));
78
+ }
79
+ input(input) {
80
+ return new _PluvProcedure({ input });
81
+ }
82
+ _resolver() {
83
+ return (data, context) => {
84
+ var _a;
85
+ return (_a = this._broadcast) == null ? void 0 : _a.call(this, data, context);
86
+ };
87
+ }
88
+ };
89
+
90
+ // src/PluvRoom.ts
91
+ import { ConnectionState, StorageState } from "@pluv/types";
92
+
93
+ // src/CrdtManager.ts
94
+ import { noop } from "@pluv/crdt";
95
+ var CrdtManager = class {
96
+ constructor(options) {
97
+ this.initialized = false;
98
+ const { initialStorage = noop.doc({}) } = options;
99
+ this._docFactory = initialStorage;
100
+ this.doc = this._docFactory.getEmpty();
101
+ }
102
+ /**
103
+ * !HACK
104
+ * @description If this is called before the doc is initialized. Omit the
105
+ * update. This unfortunately means updates can be dropped entirely
106
+ * @date June 13, 2023
107
+ */
108
+ applyUpdate(params) {
109
+ const { origin, update } = params;
110
+ if (!this.initialized) return this;
111
+ const updates = typeof update === "string" ? [update] : update;
112
+ this._applyDocUpdates(this.doc, updates, origin);
113
+ return this;
114
+ }
115
+ destroy() {
116
+ this.initialized = false;
117
+ this.doc.destroy();
118
+ this.doc = this._docFactory.getEmpty();
119
+ }
120
+ get(key) {
121
+ return this.doc.get(key);
122
+ }
123
+ getInitialState() {
124
+ return this._docFactory.getInitialized().getEncodedState();
125
+ }
126
+ initialize(params) {
127
+ const { origin, update } = params;
128
+ if (this.initialized) {
129
+ console.warn("Attempted to initialize storage multiple times");
130
+ return this;
131
+ }
132
+ if (!this.doc.isEmpty()) {
133
+ console.warn("Attempted to initialize over a non-empty storage");
134
+ return this;
135
+ }
136
+ const updates = typeof update === "string" ? [update] : update;
137
+ if (!updates.length) return this;
138
+ const initialized = this._docFactory.getInitialized();
139
+ const reference = initialized.get();
140
+ this.doc = this._applyDocUpdates(this.doc, updates, origin).rebuildStorage(reference);
141
+ this.initialized = true;
142
+ initialized.destroy();
143
+ return this;
144
+ }
145
+ resolveEncodedState(updates) {
146
+ return this._docFactory.resolveEncodedState(updates);
147
+ }
148
+ _applyDocUpdates(doc, updates, origin) {
149
+ doc.transact(() => {
150
+ doc.batchApplyEncodedState({ origin, updates });
151
+ }, origin);
152
+ return doc;
153
+ }
154
+ };
155
+
156
+ // src/CrdtNotifier.ts
157
+ import { makeSubject, subscribe } from "wonka";
158
+ var CrdtNotifier = class {
159
+ constructor() {
160
+ this.rootSubject = makeSubject();
161
+ this.subjects = /* @__PURE__ */ new Map();
162
+ }
163
+ subject(key) {
164
+ const subject = this.subjects.get(key);
165
+ if (subject) {
166
+ return subject;
167
+ }
168
+ const newSubject = makeSubject();
169
+ this.subjects.set(key, newSubject);
170
+ return newSubject;
171
+ }
172
+ subcribeRoot(callback) {
173
+ return subscribe(callback)(this.rootSubject.source).unsubscribe;
174
+ }
175
+ subscribe(key, callback) {
176
+ const subject = this.subject(key);
177
+ return subscribe(callback)(subject.source).unsubscribe;
178
+ }
179
+ };
180
+
181
+ // src/EventNotifier.ts
182
+ import { makeSubject as makeSubject2, subscribe as subscribe2 } from "wonka";
183
+ var EventNotifier = class {
184
+ constructor() {
185
+ this.subjects = /* @__PURE__ */ new Map();
186
+ }
187
+ subject(name) {
188
+ const subject = this.subjects.get(name);
189
+ if (subject) return subject;
190
+ const newSubject = makeSubject2();
191
+ this.subjects.set(name, newSubject);
192
+ return newSubject;
193
+ }
194
+ subscribe(name, callback) {
195
+ const subject = this.subject(name);
196
+ return subscribe2(callback)(subject.source).unsubscribe;
197
+ }
198
+ };
199
+
200
+ // src/ListenerManager.ts
201
+ import { makeSubject as makeSubject3, subscribe as subscribe3 } from "wonka";
202
+ var ListenerManager = class {
203
+ constructor() {
204
+ this.subjects = {
205
+ close: makeSubject3(),
206
+ error: makeSubject3(),
207
+ message: makeSubject3(),
208
+ open: makeSubject3()
209
+ };
210
+ }
211
+ subscribe(kind, callback) {
212
+ var _a;
213
+ const source = (_a = this.subjects[kind]) == null ? void 0 : _a.source;
214
+ if (!source) return () => void 0;
215
+ return subscribe3(callback)(source).unsubscribe;
216
+ }
217
+ };
218
+
219
+ // src/PluvRouter.ts
220
+ var PluvRouter = class _PluvRouter {
221
+ constructor(events) {
222
+ this._defs = { events: {} };
223
+ const invalidName = Object.keys(events).find((name) => !this._isValidEventName(name));
224
+ if (typeof invalidName === "string") {
225
+ throw new Error(
226
+ `Invalid event name. Event names must be formatted as valid JavaScript variable names: "${invalidName}"`
227
+ );
228
+ }
229
+ this._defs = { events };
230
+ }
231
+ static merge(...routers) {
232
+ const events = Object.assign(
233
+ /* @__PURE__ */ Object.create(null),
234
+ ...routers.map((router) => router._defs.events)
235
+ );
236
+ if (Object.keys(events).some((key) => key.startsWith("$"))) {
237
+ throw new Error('Procedures may not start with "$"');
238
+ }
239
+ return new _PluvRouter(events);
240
+ }
241
+ _isValidEventName(name) {
242
+ return /^[a-z_$][a-z0-9_$]*$/gi.test(name);
243
+ }
244
+ };
245
+
246
+ // src/StateNotifier.ts
247
+ import { makeSubject as makeSubject4, subscribe as subscribe4 } from "wonka";
248
+ var StateNotifier = class {
249
+ constructor() {
250
+ this.subjects = {
251
+ connection: makeSubject4(),
252
+ "my-presence": makeSubject4(),
253
+ myself: makeSubject4(),
254
+ others: makeSubject4(),
255
+ "storage-loaded": makeSubject4()
256
+ };
257
+ }
258
+ subscribe(name, callback) {
259
+ var _a;
260
+ const source = (_a = this.subjects[name]) == null ? void 0 : _a.source;
261
+ if (!source) throw new Error(`Could not subscribe to source: ${name}`);
262
+ return subscribe4(callback)(source).unsubscribe;
263
+ }
264
+ };
265
+
266
+ // src/StorageStore.ts
267
+ var StorageStore = class extends AbstractStorageStore {
268
+ addUpdate() {
269
+ return Promise.resolve();
270
+ }
271
+ applyUpdates() {
272
+ return Promise.resolve();
273
+ }
274
+ destroy() {
275
+ return Promise.resolve();
276
+ }
277
+ flatten() {
278
+ return Promise.resolve();
279
+ }
280
+ getShouldFlatten() {
281
+ return Promise.resolve(false);
282
+ }
283
+ getUpdates() {
284
+ return Promise.resolve([]);
285
+ }
286
+ initialize() {
287
+ return Promise.resolve();
288
+ }
289
+ };
290
+
291
+ // src/utils/debounce.ts
292
+ var debounce = (fn, options) => {
293
+ const { wait, immediate = false } = options != null ? options : {};
294
+ let prevResult;
295
+ let timeout = null;
296
+ return (...args) => {
297
+ if (typeof timeout === "number") clearTimeout(timeout);
298
+ timeout = setTimeout(() => {
299
+ timeout = null;
300
+ if (!immediate) prevResult = fn(args);
301
+ }, wait);
302
+ if (immediate && !timeout) {
303
+ fn(args);
304
+ return;
305
+ }
306
+ return prevResult;
307
+ };
308
+ };
309
+
310
+ // src/utils/pickBy.ts
311
+ var pickBy = (obj, by) => {
312
+ const result = {};
313
+ const keys = Object.keys(obj);
314
+ for (let i = 0; i < keys.length; ++i) {
315
+ const key = keys[i];
316
+ const value = obj[key];
317
+ if (by(value)) result[key] = value;
318
+ }
319
+ return result;
320
+ };
321
+
322
+ // src/UsersManager.ts
323
+ var UsersManager = class {
324
+ constructor(config) {
325
+ this._idMap = {
326
+ fromConnectionId: /* @__PURE__ */ new Map(),
327
+ fromClientId: /* @__PURE__ */ new Map()
328
+ };
329
+ /**
330
+ * @description This is only set when the user is connected.
331
+ */
332
+ this._myself = null;
333
+ this._others = /* @__PURE__ */ new Map();
334
+ this._presence = null;
335
+ const { initialPresence, limits, presence = null } = config;
336
+ this.initialPresence = initialPresence;
337
+ this._limits = limits;
338
+ this._myPresence = initialPresence;
339
+ this._presence = presence;
340
+ }
341
+ get myPresence() {
342
+ return this._myPresence;
343
+ }
344
+ get myself() {
345
+ return this._myself;
346
+ }
347
+ addConnection(userInfo) {
348
+ var _a;
349
+ const cleaned = pickBy((_a = userInfo.presence) != null ? _a : {}, (value) => typeof value !== "undefined");
350
+ const presence = __spreadValues(__spreadValues({}, this.initialPresence), cleaned);
351
+ const data = __spreadProps(__spreadValues({}, userInfo), { presence });
352
+ const myClientId = !!this._myself ? this.getClientId(this._myself) : null;
353
+ const clientId = this.getClientId(data);
354
+ const remaining = this._setConnectionId(userInfo.connectionId, clientId).size;
355
+ if (myClientId === clientId) {
356
+ const result2 = {
357
+ clientId,
358
+ data,
359
+ isMyself: true,
360
+ remaining
361
+ };
362
+ return result2;
363
+ }
364
+ const other = this._others.get(clientId);
365
+ if (!other) this._others.set(clientId, data);
366
+ const result = {
367
+ clientId,
368
+ data,
369
+ isMyself: false,
370
+ remaining
371
+ };
372
+ return result;
373
+ }
374
+ clearConnections() {
375
+ this.removeMyself();
376
+ this._others.clear();
377
+ this._idMap.fromClientId.clear();
378
+ this._idMap.fromConnectionId.clear();
379
+ }
380
+ deleteConnection(connectionId) {
381
+ var _a, _b, _c;
382
+ const clientId = this.getClientId(connectionId);
383
+ this._deleteConnectionId(connectionId);
384
+ if (!clientId) return null;
385
+ const userInfo = (_a = this._others.get(clientId)) != null ? _a : null;
386
+ if (!userInfo) return null;
387
+ const remaining = (_c = (_b = this._getConnectionIds(clientId)) == null ? void 0 : _b.size) != null ? _c : 0;
388
+ const result = {
389
+ clientId,
390
+ remaining,
391
+ data: userInfo
392
+ };
393
+ if (!remaining) this._others.delete(clientId);
394
+ return result;
395
+ }
396
+ getClientId(input) {
397
+ var _a, _b, _c, _d;
398
+ if (typeof input !== "string") {
399
+ const userInfo = input;
400
+ const connectionId2 = userInfo.connectionId;
401
+ const userId = (_b = (_a = userInfo.user) == null ? void 0 : _a.id) != null ? _b : null;
402
+ return userId != null ? userId : connectionId2;
403
+ }
404
+ const connectionId = input;
405
+ if (((_c = this._myself) == null ? void 0 : _c.connectionId) === connectionId) {
406
+ return this.getClientId(this._myself);
407
+ }
408
+ const clientId = (_d = this._idMap.fromConnectionId.get(connectionId)) != null ? _d : null;
409
+ return clientId;
410
+ }
411
+ getOther(connectionId) {
412
+ var _a;
413
+ const clientId = this.getClientId(connectionId);
414
+ if (!clientId) return null;
415
+ return (_a = this._others.get(clientId)) != null ? _a : null;
416
+ }
417
+ getOthers() {
418
+ return Array.from(this._others.values());
419
+ }
420
+ patchPresence(connectionId, patch) {
421
+ var _a;
422
+ const clientId = this.getClientId(connectionId);
423
+ const myClientId = !!this._myself ? this.getClientId(this._myself) : null;
424
+ if (!clientId) return null;
425
+ if (myClientId === clientId) return this.updateMyPresence(patch);
426
+ const other = this._others.get(clientId);
427
+ if (!other) return null;
428
+ const cleanedPatch = pickBy(patch != null ? patch : {}, (value) => typeof value !== "undefined");
429
+ const cleanedPresence = pickBy(
430
+ (_a = other.presence) != null ? _a : {},
431
+ (value) => typeof value !== "undefined"
432
+ );
433
+ const presence = __spreadValues(__spreadValues(__spreadValues({}, this.initialPresence), cleanedPresence), cleanedPatch);
434
+ const validated = this._presence ? this._presence.parse(presence) : presence;
435
+ if (!!presence[PLUV_PRESENCE_META_KEY]) {
436
+ validated[PLUV_PRESENCE_META_KEY] = presence[PLUV_PRESENCE_META_KEY];
437
+ }
438
+ this._others.set(clientId, __spreadProps(__spreadValues({}, other), { presence: validated }));
439
+ return validated;
440
+ }
441
+ removeMyself() {
442
+ if (!this._myself) return;
443
+ const connectionId = this._myself.connectionId;
444
+ this._deleteConnectionId(connectionId);
445
+ this._myself = null;
446
+ }
447
+ setMyself(userInfo) {
448
+ var _a;
449
+ const connectionId = userInfo.connectionId;
450
+ const presence = (_a = userInfo.presence) != null ? _a : this.initialPresence;
451
+ this._myself = __spreadProps(__spreadValues({}, userInfo), { presence });
452
+ this._myPresence = presence;
453
+ const clientId = this.getClientId(this._myself);
454
+ this._setConnectionId(connectionId, clientId);
455
+ }
456
+ setPresence(connectionId, presence) {
457
+ const clientId = this.getClientId(connectionId);
458
+ const myClientId = !!this._myself ? this.getClientId(this._myself) : null;
459
+ if (!clientId) return;
460
+ if (myClientId === clientId) {
461
+ if (!this._myself) return;
462
+ this._myself.presence = presence;
463
+ this._myPresence = presence;
464
+ return;
465
+ }
466
+ const other = this._others.get(clientId);
467
+ if (!other) return;
468
+ this._others.set(clientId, __spreadProps(__spreadValues({}, other), { presence }));
469
+ }
470
+ /**
471
+ * @description This method need not care about being connected. This is because a user should
472
+ * be able to view and update their own presence without being online
473
+ * @date April 20, 2025
474
+ */
475
+ updateMyPresence(patch) {
476
+ const cleanedPatch = pickBy(patch, (value) => typeof value !== "undefined");
477
+ const cleanedPresence = pickBy(this._myPresence, (value) => typeof value !== "undefined");
478
+ const updated = __spreadValues(__spreadValues(__spreadValues({}, this.initialPresence), cleanedPresence), cleanedPatch);
479
+ const bytes = new TextEncoder().encode(JSON.stringify(updated)).length;
480
+ if (!!this._limits.presenceMaxSize && bytes > this._limits.presenceMaxSize) {
481
+ throw new Error(
482
+ `Large presence. Presence must be at most 512 bytes. Current size: ${bytes.toLocaleString()}`
483
+ );
484
+ }
485
+ this._myPresence = updated;
486
+ if (!this._myself) return updated;
487
+ this._myself.presence = updated;
488
+ return updated;
489
+ }
490
+ _deleteConnectionId(connectionId) {
491
+ var _a;
492
+ const clientId = this.getClientId(connectionId);
493
+ this._idMap.fromConnectionId.delete(connectionId);
494
+ if (!clientId) return;
495
+ const set = (_a = this._idMap.fromClientId.get(clientId)) != null ? _a : null;
496
+ if (!set) return;
497
+ set.delete(connectionId);
498
+ if (!!set.size) return;
499
+ this._idMap.fromClientId.delete(clientId);
500
+ }
501
+ _getConnectionIds(clientId) {
502
+ const set = this._idMap.fromClientId.get(clientId);
503
+ return set != null ? set : null;
504
+ }
505
+ _setConnectionId(connectionId, clientId) {
506
+ var _a;
507
+ const set = (_a = this._idMap.fromClientId.get(clientId)) != null ? _a : /* @__PURE__ */ new Set();
508
+ const updated = set.add(connectionId);
509
+ this._idMap.fromConnectionId.set(connectionId, clientId);
510
+ this._idMap.fromClientId.set(clientId, updated);
511
+ return updated;
512
+ }
513
+ };
514
+
515
+ // src/UsersNotifier.ts
516
+ import { makeSubject as makeSubject5, subscribe as subscribe5 } from "wonka";
517
+ var UsersNotifier = class {
518
+ constructor() {
519
+ this.others = makeSubject5();
520
+ this._otherSubjects = /* @__PURE__ */ new Map();
521
+ }
522
+ clear() {
523
+ this._otherSubjects.forEach((subject) => {
524
+ subject.next(null);
525
+ });
526
+ this._otherSubjects.clear();
527
+ }
528
+ delete(clientId) {
529
+ this.other(clientId).next(null);
530
+ this._otherSubjects.delete(clientId);
531
+ }
532
+ other(clientId) {
533
+ const subject = this._otherSubjects.get(clientId);
534
+ if (subject) return subject;
535
+ const newSubject = makeSubject5();
536
+ this._otherSubjects.set(clientId, newSubject);
537
+ return newSubject;
538
+ }
539
+ subscribeOther(clientId, callback) {
540
+ const source = this.other(clientId).source;
541
+ const subscription = subscribe5(callback)(source);
542
+ return subscription.unsubscribe;
543
+ }
544
+ subscribeOthers(callback) {
545
+ const subscription = subscribe5(
546
+ ({ others, event }) => callback(others, event)
547
+ )(this.others.source);
548
+ return subscription.unsubscribe;
549
+ }
550
+ };
551
+
552
+ // src/PluvRoom.ts
553
+ var ADD_TO_STORAGE_STATE_DEBOUNCE_MS = 1e3;
554
+ var HEARTBEAT_INTERVAL_MS = 1e4;
555
+ var PONG_TIMEOUT_MS = 2e3;
556
+ var RECONNECT_TIMEOUT_MS = 5e3;
557
+ var MIN_RECONNECT_TIMEOUT_MS = 1e3;
558
+ var MAX_RECONNECT_TIMEOUT_MS = 6e4;
559
+ var ORIGIN_INITIALIZED = "$initialized";
560
+ var ORIGIN_STORAGE_UPDATED = "$storageUpdated";
561
+ var DEFAULT_PLUV_CLIENT_ADDON = (input) => ({
562
+ storage: new StorageStore(input.room.id)
563
+ });
564
+ var PluvRoom = class {
565
+ constructor(room, options) {
566
+ this._crdtNotifier = new CrdtNotifier();
567
+ this._eventNotifier = new EventNotifier();
568
+ this._intervals = {
569
+ heartbeat: null
570
+ };
571
+ this._listenerManager = new ListenerManager();
572
+ this._publicKey = null;
573
+ this._stateNotifier = new StateNotifier();
574
+ this._subscriptions = {
575
+ observeCrdt: null
576
+ };
577
+ this._timeouts = {
578
+ pong: null,
579
+ reconnect: null
580
+ };
581
+ this._usersNotifier = new UsersNotifier();
582
+ this._lastMetadata = null;
583
+ this._state = {
584
+ authorization: {
585
+ token: null,
586
+ user: null
587
+ },
588
+ connection: {
589
+ attempts: 0,
590
+ id: null,
591
+ state: ConnectionState.Untouched
592
+ },
593
+ storage: {
594
+ state: StorageState.Unavailable
595
+ },
596
+ webSocket: null
597
+ };
598
+ this._windowListeners = null;
599
+ this._wsListeners = null;
600
+ this.broadcast = new Proxy(
601
+ (event, data) => __async(this, null, function* () {
602
+ if (!this._state.webSocket) return;
603
+ if (this._state.connection.state !== ConnectionState.Open) return;
604
+ const type = event.toString();
605
+ const procedure = this._router._defs.events[type];
606
+ if (!(procedure == null ? void 0 : procedure.config.broadcast)) {
607
+ this._sendMessage({ data, type });
608
+ return;
609
+ }
610
+ const myself = this._usersManager.myself;
611
+ if (!myself) return;
612
+ const parsed = procedure.config.input ? procedure.config.input.parse(data) : data;
613
+ const context = {
614
+ doc: this._crdtManager.doc,
615
+ others: this._usersManager.getOthers(),
616
+ room: this.id,
617
+ user: myself
618
+ };
619
+ const output = yield procedure.config.broadcast(parsed, context);
620
+ Object.entries(output).forEach(([_type, _data]) => {
621
+ this._sendMessage({ data: _data, type: _type });
622
+ });
623
+ }),
624
+ {
625
+ get(fn, prop) {
626
+ return (data) => __async(null, null, function* () {
627
+ return yield fn(prop, data);
628
+ });
629
+ }
630
+ }
631
+ );
632
+ this.canRedo = () => {
633
+ return !!this._crdtManager.doc.canRedo();
634
+ };
635
+ this.canUndo = () => {
636
+ return !!this._crdtManager.doc.canUndo();
637
+ };
638
+ /**
639
+ * @deprecated To be removed in v3. Use PluvRoom.subscribe.event instead
640
+ */
641
+ this.event = new Proxy(
642
+ (event, callback) => this._eventNotifier.subscribe(event, callback),
643
+ {
644
+ get(fn, prop) {
645
+ return (callback) => fn(prop, callback);
646
+ }
647
+ }
648
+ );
649
+ this.getConnection = () => {
650
+ return Object.freeze(JSON.parse(JSON.stringify(this._state.connection)));
651
+ };
652
+ this.getDoc = () => {
653
+ return this._crdtManager.doc;
654
+ };
655
+ this.getMyPresence = () => {
656
+ return this._usersManager.myPresence;
657
+ };
658
+ this.getMyself = () => {
659
+ return this._usersManager.myself;
660
+ };
661
+ this.getOther = (connectionId) => {
662
+ return this._usersManager.getOther(connectionId);
663
+ };
664
+ this.getOthers = () => {
665
+ return this._usersManager.getOthers();
666
+ };
667
+ this.getStorage = (type) => {
668
+ const sharedType = this._crdtManager.get(type);
669
+ if (typeof sharedType === "undefined") return null;
670
+ return sharedType;
671
+ };
672
+ this.getStorageLoaded = () => {
673
+ return this._state.storage.state === StorageState.Offline || this._state.storage.state === StorageState.Synced;
674
+ };
675
+ /**
676
+ * @deprecated To be removed in v3. Use PluvRoom.subscribe.other instead
677
+ */
678
+ this.other = (connectionId, callback) => {
679
+ const clientId = this._usersManager.getClientId(connectionId);
680
+ if (!clientId) return () => void 0;
681
+ return this._usersNotifier.subscribeOther(clientId, callback);
682
+ };
683
+ this.redo = () => {
684
+ this._crdtManager.doc.redo();
685
+ };
686
+ /**
687
+ * @deprecated To be removed in v3. Use PluvRoom.subscribe.storage instead
688
+ */
689
+ this.storage = new Proxy(
690
+ (key, callback) => this._crdtNotifier.subscribe(key, callback),
691
+ {
692
+ get: (fn, prop) => {
693
+ if (!!prop) {
694
+ return (callback) => {
695
+ return this._crdtNotifier.subcribeRoot(callback);
696
+ };
697
+ }
698
+ return (callback) => {
699
+ return fn(prop, callback);
700
+ };
701
+ }
702
+ }
703
+ );
704
+ /**
705
+ * @deprecated To be removed in v3. Use PluvRoom.subscribe.storage instead
706
+ * @description Subscribes to the root storage object (serialized)
707
+ */
708
+ this.storageRoot = (callback) => {
709
+ return this._crdtNotifier.subcribeRoot(callback);
710
+ };
711
+ this.subscribe = new Proxy(
712
+ (name, callback) => this._stateNotifier.subscribe(name, callback),
713
+ {
714
+ get: (fn, prop) => {
715
+ if (prop === "connection") {
716
+ return (callback) => {
717
+ return fn("connection", callback);
718
+ };
719
+ }
720
+ if (prop === "myPresence") {
721
+ return (callback) => {
722
+ return fn("my-presence", callback);
723
+ };
724
+ }
725
+ if (prop === "myself") {
726
+ return (callback) => {
727
+ return fn("myself", callback);
728
+ };
729
+ }
730
+ if (prop === "others") {
731
+ return (callback) => {
732
+ return this._usersNotifier.subscribeOthers(callback);
733
+ };
734
+ }
735
+ if (prop === "storageLoaded") {
736
+ return (callback) => {
737
+ return fn("storage-loaded", callback);
738
+ };
739
+ }
740
+ if (prop === "event") return this.event;
741
+ if (prop === "other") return this.other;
742
+ if (prop === "storage") return this.storage;
743
+ }
744
+ }
745
+ );
746
+ this.transact = (fn, origin) => {
747
+ const _origin = origin != null ? origin : this._state.connection.id;
748
+ if (typeof _origin !== "string") return;
749
+ this._crdtManager.doc.transact(() => {
750
+ const storage = this._crdtManager.doc.get();
751
+ fn(storage);
752
+ }, _origin);
753
+ };
754
+ this.undo = () => {
755
+ this._crdtManager.doc.undo();
756
+ };
757
+ this.updateMyPresence = (presence) => {
758
+ var _a;
759
+ const newPresence = typeof presence === "function" ? presence(this.getMyPresence()) : presence;
760
+ this._usersManager.updateMyPresence(newPresence);
761
+ const myPresence = this._usersManager.myPresence;
762
+ const myself = (_a = this._usersManager.myself) != null ? _a : null;
763
+ this._stateNotifier.subjects["my-presence"].next(myPresence);
764
+ if (!!myself) this._stateNotifier.subjects.myself.next(myself);
765
+ this.broadcast(
766
+ "$updatePresence",
767
+ { presence: newPresence }
768
+ );
769
+ };
770
+ this._flattenStorageStore = debounce(
771
+ () => __async(this, null, function* () {
772
+ const shouldFlatten = yield this._storageStore.getShouldFlatten();
773
+ if (!shouldFlatten) return;
774
+ const updates = yield this._storageStore.getUpdates();
775
+ this._crdtManager.applyUpdate({ update: updates, origin: this });
776
+ const encodedState = this._crdtManager.doc.getEncodedState();
777
+ yield this._storageStore.flatten(encodedState);
778
+ }),
779
+ { wait: ADD_TO_STORAGE_STATE_DEBOUNCE_MS }
780
+ );
781
+ this._getAddon = (addons) => {
782
+ return addons.reduce(
783
+ (acc, addon) => () => __spreadValues(__spreadValues({}, acc({ room: this })), addon({ room: this })),
784
+ DEFAULT_PLUV_CLIENT_ADDON
785
+ );
786
+ };
787
+ const {
788
+ addons = [],
789
+ authEndpoint,
790
+ debug = false,
791
+ initialPresence,
792
+ initialStorage,
793
+ limits,
794
+ metadata,
795
+ onAuthorizationFail,
796
+ presence,
797
+ publicKey,
798
+ reconnectTimeoutMs = RECONNECT_TIMEOUT_MS,
799
+ router,
800
+ wsEndpoint
801
+ } = options;
802
+ this.id = room;
803
+ this.metadata = metadata;
804
+ const addon = this._getAddon(addons);
805
+ const { storage } = __spreadValues(__spreadValues({}, DEFAULT_PLUV_CLIENT_ADDON({ room: this })), addon({ room: this }));
806
+ this._storageStore = storage;
807
+ this._debug = debug;
808
+ this._endpoints = { authEndpoint, wsEndpoint };
809
+ this._limits = limits;
810
+ this._reconnectTimeoutMs = reconnectTimeoutMs;
811
+ if (!!publicKey) this._publicKey = publicKey;
812
+ this._listeners = {
813
+ onAuthorizationFail: (error) => {
814
+ onAuthorizationFail == null ? void 0 : onAuthorizationFail(error);
815
+ }
816
+ };
817
+ this._router = router != null ? router : new PluvRouter({});
818
+ this._usersManager = new UsersManager({
819
+ initialPresence,
820
+ limits: this._limits,
821
+ presence
822
+ });
823
+ this._crdtManager = new CrdtManager({ initialStorage });
824
+ }
825
+ /**
826
+ * @deprecated To be removed in v3. Use `getStorageLoaded` instead.
827
+ */
828
+ get storageLoaded() {
829
+ return this.getStorageLoaded();
830
+ }
831
+ get webSocket() {
832
+ return this._state.webSocket;
833
+ }
834
+ addEventListener(kind, handler) {
835
+ return this._listenerManager.subscribe(kind, handler);
836
+ }
837
+ connect(...args) {
838
+ return __async(this, null, function* () {
839
+ var _a;
840
+ const params = (_a = args[0]) != null ? _a : {};
841
+ const metadata = params.metadata;
842
+ this._setMetadata(metadata);
843
+ const canConnect = [
844
+ ConnectionState.Closed,
845
+ ConnectionState.Unavailable,
846
+ ConnectionState.Untouched
847
+ ].some((state) => this._state.connection.state === state);
848
+ if (!canConnect) return;
849
+ this._clearTimeout(this._timeouts.reconnect);
850
+ this._updateState((oldState) => {
851
+ oldState.connection.state = ConnectionState.Connecting;
852
+ return oldState;
853
+ });
854
+ yield this._storageStore.initialize();
855
+ const wsEndpoint = this._getWsEndpoint(this.id, params);
856
+ const url = new URL(wsEndpoint);
857
+ let authToken = null;
858
+ let webSocket;
859
+ try {
860
+ const publicKey = this._getPublicKey(params);
861
+ authToken = yield this._getAuthorization(this.id, params);
862
+ if (authToken) url.searchParams.set("token", encodeURIComponent(authToken));
863
+ if (publicKey) url.searchParams.set("public_key", encodeURIComponent(publicKey));
864
+ webSocket = new WebSocket(url.toString());
865
+ } catch (err) {
866
+ this._updateState((oldState) => {
867
+ oldState.connection.attempts += 1;
868
+ return oldState;
869
+ });
870
+ yield this._storageStore.destroy();
871
+ this._pollReconnect();
872
+ yield Promise.resolve(this._onAuthorizationFail(err));
873
+ return;
874
+ }
875
+ this._updateState((oldState) => {
876
+ oldState.connection.attempts = 0;
877
+ oldState.authorization.token = authToken;
878
+ oldState.storage.state = StorageState.Loading;
879
+ oldState.webSocket = webSocket;
880
+ return oldState;
881
+ });
882
+ this._attachWindowListeners();
883
+ this._attachWsListeners();
884
+ });
885
+ }
886
+ disconnect() {
887
+ return __async(this, null, function* () {
888
+ if (!this._state.webSocket) return;
889
+ const canDisconnect = [ConnectionState.Connecting, ConnectionState.Open].some(
890
+ (state) => this._state.connection.state === state
891
+ );
892
+ if (!canDisconnect) return;
893
+ this._closeWs();
894
+ this._clearInterval(this._intervals.heartbeat);
895
+ this._clearTimeout(this._timeouts.reconnect);
896
+ this._updateState((oldState) => {
897
+ oldState.authorization.token = null;
898
+ oldState.connection.state = ConnectionState.Closed;
899
+ oldState.storage.state = oldState.storage.state === StorageState.Synced ? StorageState.Offline : StorageState.Unavailable;
900
+ oldState.webSocket = null;
901
+ return oldState;
902
+ });
903
+ yield this._storageStore.destroy();
904
+ this._crdtManager.destroy();
905
+ this._stateNotifier.subjects["my-presence"].next(null);
906
+ });
907
+ }
908
+ getStorageJson(type) {
909
+ if (this._state.connection.id === null) return null;
910
+ if (typeof type === "undefined") return this._crdtManager.doc.toJson();
911
+ const sharedType = this._crdtManager.get(type);
912
+ if (typeof sharedType === "undefined") return null;
913
+ return this._crdtManager.doc.toJson(type);
914
+ }
915
+ _addToStorageStore(update) {
916
+ return __async(this, null, function* () {
917
+ yield this._storageStore.addUpdate(update);
918
+ this._flattenStorageStore();
919
+ });
920
+ }
921
+ _attachWindowListeners() {
922
+ if (typeof window === "undefined") return;
923
+ if (typeof document === "undefined") return;
924
+ this._windowListeners = this._windowListeners || {
925
+ onNavigatorOffline: this._onNavigatorOffline.bind(this),
926
+ onNavigatorOnline: this._onNavigatorOnline.bind(this),
927
+ onVisibilityChange: this._onVisibilityChange.bind(this),
928
+ onWindowFocus: this._onWindowFocus.bind(this)
929
+ };
930
+ window.addEventListener("offline", this._windowListeners.onNavigatorOffline);
931
+ window.addEventListener("online", this._windowListeners.onNavigatorOnline);
932
+ document.addEventListener("visibilitychange", this._windowListeners.onVisibilityChange);
933
+ window.addEventListener("focus", this._windowListeners.onWindowFocus);
934
+ }
935
+ _attachWsListeners() {
936
+ if (!this._state.webSocket) return;
937
+ this._wsListeners = this._wsListeners || {
938
+ onClose: this._onClose.bind(this),
939
+ onError: this._onError.bind(this),
940
+ onMessage: this._onMessage.bind(this),
941
+ onOpen: this._onOpen.bind(this)
942
+ };
943
+ this._state.webSocket.addEventListener("close", this._wsListeners.onClose);
944
+ this._state.webSocket.addEventListener("error", this._wsListeners.onError);
945
+ this._state.webSocket.addEventListener("message", this._wsListeners.onMessage);
946
+ this._state.webSocket.addEventListener("open", this._wsListeners.onOpen);
947
+ }
948
+ _clearInterval(interval) {
949
+ if (Number.isNaN(interval)) return;
950
+ clearInterval(interval);
951
+ }
952
+ _clearTimeout(timeout) {
953
+ if (Number.isNaN(timeout)) return;
954
+ clearTimeout(timeout);
955
+ }
956
+ _closeWs() {
957
+ var _a, _b, _c;
958
+ (_b = (_a = this._subscriptions).observeCrdt) == null ? void 0 : _b.call(_a);
959
+ this._clearInterval(this._intervals.heartbeat);
960
+ this._clearTimeout(this._timeouts.pong);
961
+ this._detachWindowListeners();
962
+ this._usersManager.removeMyself();
963
+ this._usersManager.clearConnections();
964
+ this._usersNotifier.clear();
965
+ this._stateNotifier.subjects.myself.next(null);
966
+ this._stateNotifier.subjects.others.next([]);
967
+ this._usersNotifier.others.next({ others: [], event: { kind: "clear" } });
968
+ (_c = this._state.webSocket) == null ? void 0 : _c.close();
969
+ this._detachWsListeners();
970
+ }
971
+ _detachWindowListeners() {
972
+ if (!this._windowListeners) return;
973
+ if (typeof window === "undefined") return;
974
+ if (typeof document === "undefined") return;
975
+ window.removeEventListener("offline", this._windowListeners.onNavigatorOffline);
976
+ window.removeEventListener("online", this._windowListeners.onNavigatorOnline);
977
+ document.removeEventListener("visibilitychange", this._windowListeners.onVisibilityChange);
978
+ window.removeEventListener("focus", this._windowListeners.onWindowFocus);
979
+ this._windowListeners = null;
980
+ }
981
+ _detachWsListeners() {
982
+ if (!this._state.webSocket || !this._wsListeners) return;
983
+ this._state.webSocket.removeEventListener("close", this._wsListeners.onClose);
984
+ this._state.webSocket.removeEventListener("error", this._wsListeners.onError);
985
+ this._state.webSocket.removeEventListener("message", this._wsListeners.onMessage);
986
+ this._state.webSocket.removeEventListener("open", this._wsListeners.onOpen);
987
+ this._wsListeners = null;
988
+ }
989
+ _emitSharedTypes() {
990
+ const sharedTypes = this._crdtManager.doc.get();
991
+ const storageRoot = Object.keys(sharedTypes).reduce(
992
+ (acc, prop) => {
993
+ const serialized = this._crdtManager.doc.toJson(prop);
994
+ this._crdtNotifier.subject(prop).next(serialized);
995
+ return __spreadProps(__spreadValues({}, acc), { [prop]: serialized });
996
+ },
997
+ {}
998
+ );
999
+ this._crdtNotifier.rootSubject.next(storageRoot);
1000
+ }
1001
+ _getAuthFetchOptions(room, params) {
1002
+ const metadata = params.metadata;
1003
+ if (typeof this._endpoints.authEndpoint === "undefined") return null;
1004
+ if (this._endpoints.authEndpoint === true) {
1005
+ return {
1006
+ url: `/api/pluv/authorize?room=${room}`,
1007
+ options: {}
1008
+ };
1009
+ }
1010
+ if (typeof this._endpoints.authEndpoint === "string") {
1011
+ return {
1012
+ url: this._endpoints.authEndpoint,
1013
+ options: {}
1014
+ };
1015
+ }
1016
+ const result = this._endpoints.authEndpoint({ metadata, room });
1017
+ return typeof result === "string" ? { url: result, options: {} } : result;
1018
+ }
1019
+ _getAuthorization(room, params) {
1020
+ return __async(this, null, function* () {
1021
+ const fetchOptions = this._getAuthFetchOptions(room, params);
1022
+ if (!fetchOptions) return null;
1023
+ const { url, options } = fetchOptions;
1024
+ const res = yield fetch(url, options);
1025
+ if (!res.ok || res.status !== 200) throw new Error("Room is unauthorized");
1026
+ try {
1027
+ return yield res.text().then((text) => text.trim());
1028
+ } catch (err) {
1029
+ throw new Error(err instanceof Error ? err.message : "Room is unauthorized");
1030
+ }
1031
+ });
1032
+ }
1033
+ _getPublicKey(params) {
1034
+ const metadata = params.metadata;
1035
+ if (!this._publicKey) return null;
1036
+ if (typeof this._publicKey === "string") return this._publicKey;
1037
+ return this._publicKey({ metadata });
1038
+ }
1039
+ _getWsEndpoint(room, params) {
1040
+ const metadata = params.metadata;
1041
+ switch (typeof this._endpoints.wsEndpoint) {
1042
+ case "undefined":
1043
+ return !!this._getPublicKey(params) ? `wss://rooms.pluv.io/api/room/${room}` : `/api/pluv/room/${room}`;
1044
+ case "string":
1045
+ return this._endpoints.wsEndpoint;
1046
+ default:
1047
+ return this._endpoints.wsEndpoint({ metadata, room });
1048
+ }
1049
+ }
1050
+ _handleExit(message) {
1051
+ const { connectionId } = message;
1052
+ if (!connectionId) return;
1053
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1054
+ const clientId = this._usersManager.getClientId(connectionId);
1055
+ const deleted = this._usersManager.deleteConnection(connectionId);
1056
+ const others = this._usersManager.getOthers();
1057
+ this._stateNotifier.subjects.others.next(others);
1058
+ if (!deleted) {
1059
+ console.warn("Could not identify exited connection");
1060
+ return;
1061
+ }
1062
+ const { data: user, remaining } = deleted;
1063
+ this._usersNotifier.others.next({
1064
+ others,
1065
+ event: { kind: "leave", user }
1066
+ });
1067
+ if (!remaining && !!clientId) this._usersNotifier.delete(clientId);
1068
+ }
1069
+ _handlePresenceUpdatedMessage(message) {
1070
+ var _a;
1071
+ const { connectionId } = message;
1072
+ if (!connectionId) return;
1073
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1074
+ const data = message.data;
1075
+ const myself = (_a = this._usersManager.myself) != null ? _a : null;
1076
+ if ((myself == null ? void 0 : myself.connectionId) === connectionId) return;
1077
+ const updated = this._usersManager.patchPresence(connectionId, data.presence);
1078
+ const myClientId = !!myself ? this._usersManager.getClientId(myself) : null;
1079
+ const clientId = this._usersManager.getClientId(connectionId);
1080
+ if (!!clientId && myClientId === clientId) {
1081
+ this._stateNotifier.subjects["my-presence"].next(updated);
1082
+ this._stateNotifier.subjects.myself.next(this._usersManager.myself);
1083
+ return;
1084
+ }
1085
+ if (!!clientId) {
1086
+ const other2 = this._usersManager.getOther(connectionId);
1087
+ const others2 = this._usersManager.getOthers();
1088
+ this._usersNotifier.other(clientId).next(other2);
1089
+ this._stateNotifier.subjects.others.next(others2);
1090
+ if (!!other2) {
1091
+ this._usersNotifier.others.next({
1092
+ others: others2,
1093
+ event: { kind: "update", user: other2 }
1094
+ });
1095
+ }
1096
+ return;
1097
+ }
1098
+ const added = this._usersManager.addConnection({
1099
+ connectionId,
1100
+ presence: data.presence,
1101
+ user: message.user
1102
+ });
1103
+ const other = this._usersManager.getOther(connectionId);
1104
+ const others = this._usersManager.getOthers();
1105
+ this._usersNotifier.other(added.clientId).next(other);
1106
+ this._stateNotifier.subjects.others.next(others);
1107
+ this._usersNotifier.others.next({
1108
+ others,
1109
+ event: { kind: "update", user: added.data }
1110
+ });
1111
+ }
1112
+ _handleReceiveOthers(message) {
1113
+ if (!message.connectionId) return;
1114
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1115
+ const data = message.data;
1116
+ Object.keys(data.others).forEach((connectionId) => {
1117
+ const { presence, user } = data.others[connectionId];
1118
+ const result = this._usersManager.addConnection({
1119
+ connectionId,
1120
+ presence,
1121
+ user
1122
+ });
1123
+ if (!!presence) this._usersManager.patchPresence(connectionId, presence);
1124
+ if (result.isMyself) return;
1125
+ const clientId = result.clientId;
1126
+ const other = this._usersManager.getOther(connectionId);
1127
+ this._usersNotifier.other(clientId).next(other);
1128
+ });
1129
+ const others = this._usersManager.getOthers();
1130
+ this._stateNotifier.subjects.others.next(others);
1131
+ this._usersNotifier.others.next({
1132
+ others,
1133
+ event: { kind: "sync", users: others }
1134
+ });
1135
+ }
1136
+ _handleRegisteredMessage(message) {
1137
+ return __async(this, null, function* () {
1138
+ var _a, _b, _c;
1139
+ const { connectionId } = message;
1140
+ const user = message.user;
1141
+ if (!connectionId) return;
1142
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1143
+ const data = message.data;
1144
+ const state = data.state;
1145
+ this._updateState((oldState) => {
1146
+ oldState.connection.id = connectionId;
1147
+ oldState.authorization.user = user != null ? user : null;
1148
+ return oldState;
1149
+ });
1150
+ const userInfo = {
1151
+ connectionId,
1152
+ presence: (_a = data.presence) != null ? _a : void 0,
1153
+ user
1154
+ };
1155
+ this._usersManager.setMyself(userInfo);
1156
+ const presence = this._usersManager.myPresence;
1157
+ const myself = (_b = this._usersManager.myself) != null ? _b : null;
1158
+ this._stateNotifier.subjects["my-presence"].next(presence);
1159
+ this._stateNotifier.subjects.myself.next(myself);
1160
+ const update = !state ? (_c = this._crdtManager.resolveEncodedState(yield this._storageStore.getUpdates())) != null ? _c : this._crdtManager.getInitialState() : this._crdtManager.getInitialState();
1161
+ this._sendMessage({
1162
+ type: "$initializeSession",
1163
+ data: { presence, update }
1164
+ });
1165
+ });
1166
+ }
1167
+ _handleStorageReceivedMessage(message) {
1168
+ return __async(this, null, function* () {
1169
+ const { connectionId } = message;
1170
+ if (!connectionId) return;
1171
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1172
+ const data = message.data;
1173
+ const changeKind = data.changeKind;
1174
+ const state = data.state;
1175
+ const updates = yield this._storageStore.getUpdates();
1176
+ const origin = ORIGIN_INITIALIZED;
1177
+ const updateStorage = (update) => {
1178
+ return this._crdtManager.initialized ? this._crdtManager.applyUpdate({ update, origin }) : this._crdtManager.initialize({ update, origin });
1179
+ };
1180
+ if (changeKind === "empty") {
1181
+ this._crdtManager.destroy();
1182
+ this._crdtManager.initialize({ origin, update: updates });
1183
+ } else if (changeKind === "initialized") {
1184
+ if (!!updates.length) updateStorage(updates);
1185
+ else {
1186
+ const encodedState2 = updateStorage(state).doc.getEncodedState();
1187
+ this._addToStorageStore(encodedState2);
1188
+ }
1189
+ } else {
1190
+ const encodedState2 = updateStorage(state).doc.getEncodedState();
1191
+ if (!!updates.length) this._crdtManager.applyUpdate({ update: updates, origin });
1192
+ yield this._addToStorageStore(encodedState2);
1193
+ }
1194
+ const encodedState = this._crdtManager.doc.getEncodedState();
1195
+ this._emitSharedTypes();
1196
+ this._observeCrdt();
1197
+ this._updateState((oldState) => {
1198
+ oldState.storage.state = StorageState.Synced;
1199
+ return oldState;
1200
+ });
1201
+ this._stateNotifier.subjects["storage-loaded"].next(true);
1202
+ this._sendMessage({
1203
+ type: "$updateStorage",
1204
+ data: { origin, update: encodedState }
1205
+ });
1206
+ });
1207
+ }
1208
+ _handleStorageUpdatedMessage(message) {
1209
+ const { connectionId } = message;
1210
+ if (!connectionId) return;
1211
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1212
+ const data = message.data;
1213
+ this._crdtManager.doc.applyEncodedState({
1214
+ origin: ORIGIN_STORAGE_UPDATED,
1215
+ update: data.state
1216
+ });
1217
+ const sharedTypes = this._crdtManager.doc.get();
1218
+ const storageRoot = Object.keys(sharedTypes).reduce(
1219
+ (acc, prop) => {
1220
+ const serialized = this._crdtManager.doc.toJson(prop);
1221
+ this._crdtNotifier.subject(prop).next(serialized);
1222
+ return __spreadProps(__spreadValues({}, acc), { [prop]: serialized });
1223
+ },
1224
+ {}
1225
+ );
1226
+ this._crdtNotifier.rootSubject.next(storageRoot);
1227
+ }
1228
+ _handleSyncStateReceived(message) {
1229
+ var _a;
1230
+ const { connectionId } = message;
1231
+ if (!connectionId) return;
1232
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1233
+ if (!this._usersManager.myself) return;
1234
+ const data = message.data;
1235
+ const active = new Set((_a = data == null ? void 0 : data.connectionIds) != null ? _a : []);
1236
+ const quitters = this._usersManager.getOthers().filter((other) => !active.has(other.connectionId));
1237
+ quitters.forEach((quitter) => {
1238
+ this._usersManager.deleteConnection(quitter.connectionId);
1239
+ const remaining2 = this._usersManager.getOthers();
1240
+ this._usersNotifier.others.next({
1241
+ others: remaining2,
1242
+ event: { kind: "leave", user: quitter }
1243
+ });
1244
+ });
1245
+ const remaining = this._usersManager.getOthers();
1246
+ this._stateNotifier.subjects.others.next(remaining);
1247
+ }
1248
+ _handleUserJoinedMessage(message) {
1249
+ const { connectionId } = message;
1250
+ if (!connectionId) return;
1251
+ if (!this._state.webSocket) throw new Error("Could not find WebSocket");
1252
+ if (!this._usersManager.myself) return;
1253
+ const data = message.data;
1254
+ const myself = this._usersManager.myself;
1255
+ if (myself.connectionId === connectionId) {
1256
+ this._sendMessage({ type: "$getOthers", data: {} });
1257
+ return;
1258
+ }
1259
+ const added = this._usersManager.addConnection({
1260
+ connectionId,
1261
+ presence: data.presence,
1262
+ user: data.user
1263
+ });
1264
+ const other = this._usersManager.getOther(connectionId);
1265
+ const others = this._usersManager.getOthers();
1266
+ this._usersNotifier.other(added.clientId).next(other);
1267
+ this._stateNotifier.subjects.others.next(others);
1268
+ this._usersNotifier.others.next({
1269
+ others,
1270
+ event: { kind: "enter", user: added.data }
1271
+ });
1272
+ }
1273
+ _heartbeat() {
1274
+ this._clearTimeout(this._timeouts.pong);
1275
+ this._timeouts.pong = setTimeout(
1276
+ this._reconnect.bind(this),
1277
+ PONG_TIMEOUT_MS
1278
+ );
1279
+ this._sendMessage('{"type":"$ping","data":{}}');
1280
+ }
1281
+ _logDebug(...data) {
1282
+ var _a;
1283
+ if (typeof process === "undefined") return;
1284
+ if (((_a = process.env) == null ? void 0 : _a.NODE_ENV) === "production") return;
1285
+ if (this._debug) console.log(...data);
1286
+ }
1287
+ _observeCrdt() {
1288
+ var _a, _b;
1289
+ (_b = (_a = this._subscriptions).observeCrdt) == null ? void 0 : _b.call(_a);
1290
+ const unsubscribe = this._crdtManager.doc.subscribe((event) => {
1291
+ var _a2;
1292
+ const origin = (_a2 = event.origin) != null ? _a2 : null;
1293
+ this._emitSharedTypes();
1294
+ if (origin === ORIGIN_INITIALIZED || origin === ORIGIN_STORAGE_UPDATED) {
1295
+ return;
1296
+ }
1297
+ this._addToStorageStore(event.update);
1298
+ if (!this._state.webSocket) return;
1299
+ if (!this._state.connection.id) return;
1300
+ if (this._state.webSocket.readyState !== WebSocket.OPEN) return;
1301
+ this._sendMessage({
1302
+ type: "$updateStorage",
1303
+ data: { origin, update: event.update }
1304
+ });
1305
+ });
1306
+ this._subscriptions.observeCrdt = unsubscribe;
1307
+ }
1308
+ _onAuthorizationFail(error) {
1309
+ const authError = error instanceof Error ? error : new Error("Authorization failed");
1310
+ this._listeners.onAuthorizationFail(authError);
1311
+ this._updateState((oldState) => {
1312
+ oldState.connection.state = ConnectionState.Unavailable;
1313
+ oldState.storage.state = StorageState.Unavailable;
1314
+ return oldState;
1315
+ });
1316
+ }
1317
+ _onClose(event) {
1318
+ return __async(this, null, function* () {
1319
+ this._listenerManager.subjects.close.next(event);
1320
+ this._logDebug("WebSocket closed");
1321
+ if (!!event.reason) this._logDebug(event.reason);
1322
+ const shouldRetry = [
1323
+ // Going away: Client/server is shutting down or navigating
1324
+ 1001,
1325
+ // Abnormal closure: Usually network error
1326
+ 1006,
1327
+ // Internal error: may be a larger problem, but try reconnecting for now
1328
+ 1011,
1329
+ // Service restart: Server restarted
1330
+ 1012,
1331
+ // Try again later: server overloaded
1332
+ 1013,
1333
+ // Bad gateway
1334
+ 1014
1335
+ ].some((okToRetryCode) => event.code === okToRetryCode);
1336
+ this._updateState((oldState) => {
1337
+ oldState.authorization.token = null;
1338
+ oldState.connection.state = shouldRetry ? ConnectionState.Unavailable : (
1339
+ /**
1340
+ * !HACK
1341
+ * @description Assume these are not recoverable. We're just going to mark this
1342
+ * as Closed to avoid reconnect attempts.
1343
+ * @date April 28, 2025
1344
+ */
1345
+ ConnectionState.Closed
1346
+ );
1347
+ oldState.storage.state = oldState.storage.state === StorageState.Synced ? StorageState.Offline : StorageState.Unavailable;
1348
+ oldState.webSocket = null;
1349
+ return oldState;
1350
+ });
1351
+ if (shouldRetry) {
1352
+ yield this._reconnect();
1353
+ return;
1354
+ }
1355
+ this._closeWs();
1356
+ this._clearTimeout(this._timeouts.reconnect);
1357
+ });
1358
+ }
1359
+ /**
1360
+ * TODO
1361
+ * @description Handle websocket errors in a meaningful way, should they occur
1362
+ * @date August 19, 2022
1363
+ */
1364
+ _onError(event) {
1365
+ this._listenerManager.subjects.error.next(event);
1366
+ }
1367
+ _onMessage(event) {
1368
+ this._listenerManager.subjects.message.next(event);
1369
+ const message = this._parseMessage(event);
1370
+ if (!message) return;
1371
+ const shouldLog = typeof this._debug === "boolean" ? this._debug : this._debug.output.find((value) => value === message.type);
1372
+ if (shouldLog) {
1373
+ this._logDebug("WebSocket event received: ", message.type, message);
1374
+ }
1375
+ this._eventNotifier.subject(message.type).next(message);
1376
+ switch (message.type) {
1377
+ case "$exit": {
1378
+ this._handleExit(message);
1379
+ return;
1380
+ }
1381
+ case "$othersReceived": {
1382
+ this._handleReceiveOthers(message);
1383
+ return;
1384
+ }
1385
+ case "$pong": {
1386
+ this._clearTimeout(this._timeouts.pong);
1387
+ return;
1388
+ }
1389
+ case "$presenceUpdated": {
1390
+ this._handlePresenceUpdatedMessage(message);
1391
+ return;
1392
+ }
1393
+ case "$registered": {
1394
+ this._handleRegisteredMessage(message);
1395
+ return;
1396
+ }
1397
+ case "$storageReceived": {
1398
+ this._handleStorageReceivedMessage(message);
1399
+ return;
1400
+ }
1401
+ case "$storageUpdated": {
1402
+ this._handleStorageUpdatedMessage(message);
1403
+ return;
1404
+ }
1405
+ case "$syncStateReceived": {
1406
+ this._handleSyncStateReceived(message);
1407
+ return;
1408
+ }
1409
+ case "$userJoined": {
1410
+ this._handleUserJoinedMessage(message);
1411
+ return;
1412
+ }
1413
+ default:
1414
+ }
1415
+ }
1416
+ _onOpen(event) {
1417
+ this._listenerManager.subjects.open.next(event);
1418
+ if (this._state.connection.state !== ConnectionState.Connecting) return;
1419
+ this._logDebug("WebSocket connected");
1420
+ this._updateState((oldState) => {
1421
+ oldState.connection.state = ConnectionState.Open;
1422
+ return oldState;
1423
+ });
1424
+ this._clearInterval(this._intervals.heartbeat);
1425
+ this._intervals.heartbeat = setInterval(
1426
+ this._heartbeat.bind(this),
1427
+ HEARTBEAT_INTERVAL_MS
1428
+ );
1429
+ }
1430
+ _onNavigatorOffline() {
1431
+ return __async(this, null, function* () {
1432
+ if (this._state.connection.state === ConnectionState.Closed) return;
1433
+ this._updateState((oldState) => {
1434
+ oldState.connection.state = ConnectionState.Unavailable;
1435
+ oldState.storage.state = oldState.storage.state === StorageState.Synced ? StorageState.Offline : StorageState.Unavailable;
1436
+ return oldState;
1437
+ });
1438
+ });
1439
+ }
1440
+ _onNavigatorOnline() {
1441
+ return __async(this, null, function* () {
1442
+ if (this._state.connection.state !== ConnectionState.Unavailable) return;
1443
+ yield this._reconnect();
1444
+ });
1445
+ }
1446
+ _onVisibilityChange() {
1447
+ return __async(this, null, function* () {
1448
+ if (typeof document === "undefined") return;
1449
+ if (document.visibilityState !== "visible") return;
1450
+ switch (this._state.connection.state) {
1451
+ case ConnectionState.Open: {
1452
+ this._clearInterval(this._intervals.heartbeat);
1453
+ setInterval(this._heartbeat.bind(this), HEARTBEAT_INTERVAL_MS);
1454
+ return;
1455
+ }
1456
+ case ConnectionState.Unavailable: {
1457
+ yield this._reconnect();
1458
+ return;
1459
+ }
1460
+ default:
1461
+ }
1462
+ });
1463
+ }
1464
+ _onWindowFocus() {
1465
+ return __async(this, null, function* () {
1466
+ return yield this._onVisibilityChange();
1467
+ });
1468
+ }
1469
+ _parseMessage(message) {
1470
+ if (typeof message.data !== "string") return null;
1471
+ try {
1472
+ const config = JSON.parse(message.data);
1473
+ if (typeof config !== "object") return null;
1474
+ if (typeof config.type !== "string") return null;
1475
+ if (typeof config.data !== "object") return null;
1476
+ return config;
1477
+ } catch (e) {
1478
+ return null;
1479
+ }
1480
+ }
1481
+ _pollReconnect() {
1482
+ this._clearTimeout(this._timeouts.reconnect);
1483
+ const timeoutMs = typeof this._reconnectTimeoutMs === "number" ? this._reconnectTimeoutMs : this._reconnectTimeoutMs({ attempts: this._state.connection.attempts });
1484
+ const clampedMs = Math.max(
1485
+ Math.min(MIN_RECONNECT_TIMEOUT_MS, timeoutMs),
1486
+ MAX_RECONNECT_TIMEOUT_MS
1487
+ );
1488
+ this._timeouts.reconnect = setTimeout(
1489
+ this._reconnect.bind(this),
1490
+ clampedMs
1491
+ );
1492
+ }
1493
+ _reconnect() {
1494
+ return __async(this, null, function* () {
1495
+ this._closeWs();
1496
+ if (this._state.connection.state === ConnectionState.Closed) return;
1497
+ const metadata = this._lastMetadata;
1498
+ const params = typeof metadata === "undefined" ? [] : [{ metadata }];
1499
+ yield this.connect(...params);
1500
+ });
1501
+ }
1502
+ _sendMessage(data) {
1503
+ const webSocket = this._state.webSocket;
1504
+ if ((webSocket == null ? void 0 : webSocket.readyState) !== WebSocket.OPEN) return;
1505
+ const dataType = (() => {
1506
+ var _a, _b, _c;
1507
+ if (typeof data === "object") return (_a = data.type) != null ? _a : null;
1508
+ if (typeof data !== "string") return null;
1509
+ try {
1510
+ return (_c = (_b = JSON.parse(data)) == null ? void 0 : _b.type) != null ? _c : null;
1511
+ } catch (e) {
1512
+ return null;
1513
+ }
1514
+ })();
1515
+ const shouldLog = typeof this._debug === "boolean" ? this._debug : !dataType ? false : this._debug.input.some((value) => value === data.type);
1516
+ if (shouldLog) this._logDebug("WebSocket event sent: ", data.type, data);
1517
+ const message = typeof data === "string" ? data : JSON.stringify(data);
1518
+ webSocket.send(message);
1519
+ }
1520
+ _setMetadata(metadata) {
1521
+ const parsed = this.metadata ? this.metadata.parse(metadata) : metadata;
1522
+ this._lastMetadata = parsed;
1523
+ return parsed;
1524
+ }
1525
+ _updateState(updater) {
1526
+ let authorization;
1527
+ try {
1528
+ authorization = JSON.parse(JSON.stringify(this._state.authorization));
1529
+ } catch (e) {
1530
+ throw new Error("User is not JSON serializable");
1531
+ }
1532
+ const oldState = __spreadProps(__spreadValues({}, this._state), {
1533
+ authorization,
1534
+ connection: JSON.parse(JSON.stringify(this._state.connection)),
1535
+ storage: JSON.parse(JSON.stringify(this._state.storage)),
1536
+ webSocket: this._state.webSocket
1537
+ });
1538
+ const newState = updater(oldState);
1539
+ this._state = newState;
1540
+ this._logDebug("WebSocket new state: ", newState);
1541
+ this._stateNotifier.subjects.connection.next(newState);
1542
+ return newState;
1543
+ }
1544
+ };
1545
+
1546
+ // src/PluvClient.ts
1547
+ var PluvClient = class {
1548
+ constructor(options) {
1549
+ this._publicKey = null;
1550
+ this._rooms = /* @__PURE__ */ new Map();
1551
+ this.createRoom = (room, options = {}) => {
1552
+ var _a, _b;
1553
+ const oldRoom = this.getRoom(room);
1554
+ if (oldRoom) return oldRoom;
1555
+ const newRoom = new PluvRoom(room, {
1556
+ addons: options.addons,
1557
+ authEndpoint: this._authEndpoint,
1558
+ debug: options.debug,
1559
+ initialPresence: options.initialPresence,
1560
+ initialStorage: (_a = options.initialStorage) != null ? _a : this._initialStorage,
1561
+ limits: this._limits,
1562
+ metadata: this.metadata,
1563
+ onAuthorizationFail: options.onAuthorizationFail,
1564
+ presence: this._presence,
1565
+ publicKey: (_b = this._publicKey) != null ? _b : void 0,
1566
+ reconnectTimeoutMs: options.reconnectTimeoutMs,
1567
+ router: options.router,
1568
+ wsEndpoint: this._wsEndpoint
1569
+ });
1570
+ this._rooms.set(room, newRoom);
1571
+ this._logDebug(`New room was created: ${room}`);
1572
+ return newRoom;
1573
+ };
1574
+ this.enter = (room, ...args) => __async(this, null, function* () {
1575
+ const toEnter = typeof room === "string" ? this.getRoom(room) : room;
1576
+ if (!toEnter) throw new Error(`Could not find room: ${room}.`);
1577
+ this._rooms.set(toEnter.id, toEnter);
1578
+ yield toEnter.connect(...args);
1579
+ this._logDebug(`Entered room: ${room}`);
1580
+ return toEnter;
1581
+ });
1582
+ this.getRoom = (room) => {
1583
+ const found = this._rooms.get(room);
1584
+ return found != null ? found : null;
1585
+ };
1586
+ this.getRooms = () => {
1587
+ return Array.from(this._rooms.values());
1588
+ };
1589
+ this.leave = (room) => __async(this, null, function* () {
1590
+ const toLeave = typeof room === "string" ? this.getRoom(room) : room;
1591
+ if (!toLeave) return;
1592
+ yield toLeave.disconnect();
1593
+ this._rooms.delete(toLeave.id);
1594
+ this._logDebug(`Left and deleted room: ${room}`);
1595
+ });
1596
+ const {
1597
+ authEndpoint,
1598
+ debug = false,
1599
+ initialStorage,
1600
+ limits,
1601
+ metadata,
1602
+ presence,
1603
+ publicKey,
1604
+ wsEndpoint
1605
+ } = options;
1606
+ this.metadata = metadata;
1607
+ this._authEndpoint = authEndpoint;
1608
+ this._debug = debug;
1609
+ this._initialStorage = initialStorage;
1610
+ this._limits = __spreadValues({
1611
+ presenceMaxSize: MAX_PRESENCE_SIZE_BYTES
1612
+ }, limits);
1613
+ this._presence = presence;
1614
+ this._wsEndpoint = wsEndpoint;
1615
+ if (!!publicKey) this._publicKey = publicKey;
1616
+ }
1617
+ get _defs() {
1618
+ return {
1619
+ initialStorage: this._initialStorage
1620
+ };
1621
+ }
1622
+ get procedure() {
1623
+ return new PluvProcedure();
1624
+ }
1625
+ router(events) {
1626
+ const invalidName = Object.keys(events).find((name) => name.includes("$"));
1627
+ if (typeof invalidName === "string") {
1628
+ throw new Error(`Invalid event name. Event names must not contain $: "${invalidName}"`);
1629
+ }
1630
+ return new PluvRouter(events);
1631
+ }
1632
+ _logDebug(...data) {
1633
+ var _a;
1634
+ if (typeof process === "undefined") return;
1635
+ if (((_a = process.env) == null ? void 0 : _a.NODE_ENV) === "production") return;
1636
+ if (this._debug) console.log(...data);
1637
+ }
1638
+ };
1639
+
1640
+ // src/createClient.ts
1641
+ var createClient = (options) => {
1642
+ return new PluvClient(options);
1643
+ };
1644
+
1645
+ // src/infer.ts
1646
+ var infer = (callback) => callback;
1647
+
1648
+ // src/MockedRoom.ts
1649
+ import { ConnectionState as ConnectionState2, StorageState as StorageState2 } from "@pluv/types";
1650
+ var MockedRoom = class {
1651
+ constructor(room, options) {
1652
+ /**
1653
+ * @deprecated To be removed in v3. Use `getStorageLoaded` instead.
1654
+ */
1655
+ this.storageLoaded = true;
1656
+ this._crdtNotifier = new CrdtNotifier();
1657
+ this._eventNotifier = new EventNotifier();
1658
+ this._usersNotifier = new UsersNotifier();
1659
+ this._state = {
1660
+ authorization: {
1661
+ token: null,
1662
+ user: null
1663
+ },
1664
+ connection: {
1665
+ attempts: 0,
1666
+ id: null,
1667
+ state: ConnectionState2.Untouched
1668
+ },
1669
+ storage: {
1670
+ state: StorageState2.Unavailable
1671
+ },
1672
+ webSocket: null
1673
+ };
1674
+ this._stateNotifier = new StateNotifier();
1675
+ this._subscriptions = {
1676
+ observeCrdt: null
1677
+ };
1678
+ this.broadcast = new Proxy(
1679
+ (event, data) => __async(this, null, function* () {
1680
+ if (!this._state.webSocket) return;
1681
+ if (this._state.connection.state !== ConnectionState2.Open) return;
1682
+ const type = event.toString();
1683
+ const procedure = this._router._defs.events[type];
1684
+ if (!(procedure == null ? void 0 : procedure.config.broadcast)) {
1685
+ this._simulateEvent(type, data);
1686
+ return;
1687
+ }
1688
+ const myself = this._usersManager.myself;
1689
+ if (!myself) return;
1690
+ const parsed = procedure.config.input ? procedure.config.input.parse(data) : data;
1691
+ const context = {
1692
+ doc: this._crdtManager.doc,
1693
+ others: this._usersManager.getOthers(),
1694
+ room: this.id,
1695
+ user: myself
1696
+ };
1697
+ const output = yield procedure.config.broadcast(parsed, context);
1698
+ Object.entries(output).forEach(([_type, _data]) => {
1699
+ this._simulateEvent(_type, _data);
1700
+ });
1701
+ }),
1702
+ {
1703
+ get(fn, prop) {
1704
+ return (data) => __async(null, null, function* () {
1705
+ return yield fn(prop, data);
1706
+ });
1707
+ }
1708
+ }
1709
+ );
1710
+ this.canRedo = () => {
1711
+ return !!this._crdtManager.doc.canRedo();
1712
+ };
1713
+ this.canUndo = () => {
1714
+ return !!this._crdtManager.doc.canUndo();
1715
+ };
1716
+ this.event = new Proxy(
1717
+ (event, callback) => this._eventNotifier.subscribe(event, callback),
1718
+ {
1719
+ get(fn, prop) {
1720
+ return (callback) => fn(prop, callback);
1721
+ }
1722
+ }
1723
+ );
1724
+ this.getConnection = () => {
1725
+ return Object.freeze(JSON.parse(JSON.stringify(this._state.connection)));
1726
+ };
1727
+ this.getMyPresence = () => {
1728
+ return this._usersManager.myPresence;
1729
+ };
1730
+ this.getMyself = () => {
1731
+ return this._usersManager.myself;
1732
+ };
1733
+ this.getOther = (connectionId) => {
1734
+ return this._usersManager.getOther(connectionId);
1735
+ };
1736
+ this.getOthers = () => {
1737
+ return this._usersManager.getOthers();
1738
+ };
1739
+ this.getStorage = (type) => {
1740
+ const sharedType = this._crdtManager.get(type);
1741
+ if (typeof sharedType === "undefined") return null;
1742
+ return sharedType;
1743
+ };
1744
+ this.other = (connectionId, callback) => {
1745
+ const clientId = this._usersManager.getClientId(connectionId);
1746
+ if (!clientId) return () => void 0;
1747
+ return this._usersNotifier.subscribeOther(clientId, callback);
1748
+ };
1749
+ this.redo = () => {
1750
+ this._crdtManager.doc.redo();
1751
+ };
1752
+ this.storage = new Proxy(
1753
+ (key, callback) => this._crdtNotifier.subscribe(key, callback),
1754
+ {
1755
+ get: (fn, prop) => {
1756
+ if (!!prop) {
1757
+ return (callback) => {
1758
+ return this._crdtNotifier.subcribeRoot(callback);
1759
+ };
1760
+ }
1761
+ return (callback) => {
1762
+ return fn(prop, callback);
1763
+ };
1764
+ }
1765
+ }
1766
+ );
1767
+ this.storageRoot = (fn) => {
1768
+ return this._crdtNotifier.subcribeRoot(fn);
1769
+ };
1770
+ this.subscribe = new Proxy(
1771
+ (name, callback) => {
1772
+ return this._stateNotifier.subscribe(name, callback);
1773
+ },
1774
+ {
1775
+ get: (fn, prop) => {
1776
+ if (prop === "connection") {
1777
+ return (callback) => {
1778
+ return fn("connection", callback);
1779
+ };
1780
+ }
1781
+ if (prop === "myPresence") {
1782
+ return (callback) => {
1783
+ return fn("my-presence", callback);
1784
+ };
1785
+ }
1786
+ if (prop === "myself") {
1787
+ return (callback) => {
1788
+ return fn("myself", callback);
1789
+ };
1790
+ }
1791
+ if (prop === "others") {
1792
+ return (callback) => {
1793
+ return this._usersNotifier.subscribeOthers(callback);
1794
+ };
1795
+ }
1796
+ if (prop === "storageLoaded") {
1797
+ return (callback) => {
1798
+ return fn("storage-loaded", callback);
1799
+ };
1800
+ }
1801
+ if (prop === "event") return this.event;
1802
+ if (prop === "other") return this.other;
1803
+ if (prop === "storage") return this.storage;
1804
+ }
1805
+ }
1806
+ );
1807
+ this.transact = (fn, origin) => {
1808
+ const _origin = origin != null ? origin : this._state.connection.id;
1809
+ const crdtManager = this._crdtManager;
1810
+ if (typeof _origin !== "string") return;
1811
+ if (!crdtManager) return;
1812
+ crdtManager.doc.transact(() => {
1813
+ const storage = crdtManager.doc.get();
1814
+ fn(storage);
1815
+ }, _origin);
1816
+ };
1817
+ this.undo = () => {
1818
+ this._crdtManager.doc.undo();
1819
+ };
1820
+ this.updateMyPresence = (presence) => {
1821
+ var _a;
1822
+ const newPresence = typeof presence === "function" ? presence(this.getMyPresence()) : presence;
1823
+ this._usersManager.updateMyPresence(newPresence);
1824
+ const myPresence = this._usersManager.myPresence;
1825
+ const myself = (_a = this._usersManager.myself) != null ? _a : null;
1826
+ this._stateNotifier.subjects["my-presence"].next(myPresence);
1827
+ if (!!myself) this._stateNotifier.subjects["myself"].next(myself);
1828
+ };
1829
+ const { events, initialPresence, initialStorage, limits, presence, router } = options;
1830
+ this.id = room;
1831
+ this._events = events;
1832
+ this._limits = __spreadValues({
1833
+ presenceMaxSize: MAX_PRESENCE_SIZE_BYTES
1834
+ }, limits);
1835
+ this._router = router != null ? router : new PluvRouter({});
1836
+ this._usersManager = new UsersManager({
1837
+ initialPresence,
1838
+ limits: this._limits,
1839
+ presence
1840
+ });
1841
+ this._crdtManager = new CrdtManager({
1842
+ initialStorage
1843
+ });
1844
+ this._observeCrdt();
1845
+ }
1846
+ addEventListener(kind, handler) {
1847
+ return () => void 0;
1848
+ }
1849
+ getDoc() {
1850
+ return this._crdtManager.doc;
1851
+ }
1852
+ getStorageJson(type) {
1853
+ if (this._state.connection.id === null) return null;
1854
+ if (typeof type === "undefined") return this._crdtManager.doc.toJson();
1855
+ return this._crdtManager.doc.toJson(type);
1856
+ }
1857
+ getStorageLoaded() {
1858
+ return true;
1859
+ }
1860
+ _observeCrdt() {
1861
+ var _a, _b;
1862
+ (_b = (_a = this._subscriptions).observeCrdt) == null ? void 0 : _b.call(_a);
1863
+ if (!this._crdtManager) return;
1864
+ const unsubscribe = this._crdtManager.doc.subscribe((event) => {
1865
+ var _a2;
1866
+ const origin = (_a2 = event.origin) != null ? _a2 : null;
1867
+ if (!this._crdtManager) return;
1868
+ if (origin === "$storageUpdated") return;
1869
+ const sharedTypes = this._crdtManager.doc.get();
1870
+ const storageRoot = Object.keys(sharedTypes).reduce(
1871
+ (acc, prop) => {
1872
+ if (!this._crdtManager) return acc;
1873
+ const serialized = this._crdtManager.doc.toJson(prop);
1874
+ this._crdtNotifier.subject(prop).next(serialized);
1875
+ return __spreadProps(__spreadValues({}, acc), { [prop]: serialized });
1876
+ },
1877
+ {}
1878
+ );
1879
+ this._crdtNotifier.rootSubject.next(storageRoot);
1880
+ });
1881
+ this._subscriptions.observeCrdt = unsubscribe;
1882
+ }
1883
+ _simulateEvent(event, data) {
1884
+ if (!this._events) return;
1885
+ const type = event.toString();
1886
+ const resolver = this._events[type];
1887
+ if (!resolver) return;
1888
+ const result = resolver(data);
1889
+ Object.keys(result).forEach((type2) => {
1890
+ const _type = type2.toString();
1891
+ const data2 = result[_type];
1892
+ if (!data2) return;
1893
+ this._eventNotifier.subject(_type).next(data2);
1894
+ });
1895
+ }
1896
+ };
1897
+
1898
+ // src/register.ts
1899
+ var register = (params) => {
1900
+ const { authEndpoint, publicKey } = params;
1901
+ const wsEndpoint = ({ room }) => `wss://connect.pluv.io/api/room?room=${room}`;
1902
+ return {
1903
+ authEndpoint,
1904
+ publicKey,
1905
+ wsEndpoint
1906
+ };
1907
+ };
1908
+ export {
1909
+ AbstractStorageStore,
1910
+ ConnectionState3 as ConnectionState,
1911
+ MockedRoom,
1912
+ PluvClient,
1913
+ PluvRoom,
1914
+ createClient,
1915
+ infer,
1916
+ register
1917
+ };