@liveblocks/client 0.18.0-beta0 → 0.18.0-beta3

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/index.js CHANGED
@@ -1,2262 +1,1585 @@
1
- "use strict";
2
- function _arrayLikeToArray(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _arrayWithHoles(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function _arrayWithoutHoles(arr) {
11
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
12
- }
13
- function _assertThisInitialized(self) {
14
- if (self === void 0) {
15
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ var _chunkUV2F4F4Rjs = require('./chunk-UV2F4F4R.js');
29
+
30
+ // src/EventSource.ts
31
+ function makeEventSource() {
32
+ const _onetimeObservers = /* @__PURE__ */ new Set();
33
+ const _observers = /* @__PURE__ */ new Set();
34
+ function subscribe(callback) {
35
+ _observers.add(callback);
36
+ return () => _observers.delete(callback);
37
+ }
38
+ function subscribeOnce(callback) {
39
+ _onetimeObservers.add(callback);
40
+ return () => _onetimeObservers.delete(callback);
41
+ }
42
+ function notify(event) {
43
+ _onetimeObservers.forEach((callback) => callback(event));
44
+ _onetimeObservers.clear();
45
+ _observers.forEach((callback) => callback(event));
46
+ }
47
+ function clear() {
48
+ _onetimeObservers.clear();
49
+ _observers.clear();
50
+ }
51
+ return {
52
+ notify,
53
+ subscribe,
54
+ subscribeOnce,
55
+ clear,
56
+ observable: {
57
+ subscribe,
58
+ subscribeOnce
16
59
  }
17
- return self;
60
+ };
18
61
  }
19
- function _classCallCheck(instance, Constructor) {
20
- if (!(instance instanceof Constructor)) {
21
- throw new TypeError("Cannot call a class as a function");
62
+
63
+ // src/ImmutableRef.ts
64
+ function merge(target, patch) {
65
+ let updated = false;
66
+ const newValue = _chunkUV2F4F4Rjs.__spreadValues.call(void 0, {}, target);
67
+ Object.keys(patch).forEach((k) => {
68
+ const key = k;
69
+ const val = patch[key];
70
+ if (newValue[key] !== val) {
71
+ if (val === void 0) {
72
+ delete newValue[key];
73
+ } else {
74
+ newValue[key] = val;
75
+ }
76
+ updated = true;
22
77
  }
78
+ });
79
+ return updated ? newValue : target;
23
80
  }
24
- function isNativeReflectConstruct() {
25
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
26
- if (Reflect.construct.sham) return false;
27
- if (typeof Proxy === "function") return true;
28
- try {
29
- Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
30
- return true;
31
- } catch (e) {
32
- return false;
81
+ var ImmutableRef = class {
82
+ constructor() {
83
+ this._ev = makeEventSource();
84
+ }
85
+ get didInvalidate() {
86
+ return this._ev.observable;
87
+ }
88
+ invalidate() {
89
+ if (this._cache !== void 0) {
90
+ this._cache = void 0;
91
+ this._ev.notify();
33
92
  }
34
- }
35
- function _construct(Parent, args, Class) {
36
- if (isNativeReflectConstruct()) {
37
- _construct = Reflect.construct;
38
- } else {
39
- _construct = function _construct(Parent, args, Class) {
40
- var a = [
41
- null
42
- ];
43
- a.push.apply(a, args);
44
- var Constructor = Function.bind.apply(Parent, a);
45
- var instance = new Constructor();
46
- if (Class) _setPrototypeOf(instance, Class.prototype);
47
- return instance;
48
- };
93
+ }
94
+ get current() {
95
+ var _a;
96
+ return (_a = this._cache) != null ? _a : this._cache = this._toImmutable();
97
+ }
98
+ };
99
+
100
+ // src/MeRef.ts
101
+ var MeRef = class extends ImmutableRef {
102
+ constructor(initialPresence) {
103
+ super();
104
+ this._me = _chunkUV2F4F4Rjs.freeze.call(void 0, _chunkUV2F4F4Rjs.compactObject.call(void 0, initialPresence));
105
+ }
106
+ _toImmutable() {
107
+ return this._me;
108
+ }
109
+ patch(patch) {
110
+ const oldMe = this._me;
111
+ const newMe = merge(oldMe, patch);
112
+ if (oldMe !== newMe) {
113
+ this._me = _chunkUV2F4F4Rjs.freeze.call(void 0, newMe);
114
+ this.invalidate();
49
115
  }
50
- return _construct.apply(null, arguments);
116
+ }
117
+ };
118
+
119
+ // src/OthersRef.ts
120
+ function makeUser(conn, presence) {
121
+ return _chunkUV2F4F4Rjs.freeze.call(void 0, _chunkUV2F4F4Rjs.compactObject.call(void 0, _chunkUV2F4F4Rjs.__spreadProps.call(void 0, _chunkUV2F4F4Rjs.__spreadValues.call(void 0, {}, conn), { presence })));
51
122
  }
52
- function _defineProperties(target, props) {
53
- for(var i = 0; i < props.length; i++){
54
- var descriptor = props[i];
55
- descriptor.enumerable = descriptor.enumerable || false;
56
- descriptor.configurable = true;
57
- if ("value" in descriptor) descriptor.writable = true;
58
- Object.defineProperty(target, descriptor.key, descriptor);
123
+ var OthersRef = class extends ImmutableRef {
124
+ constructor() {
125
+ super();
126
+ this._connections = {};
127
+ this._presences = {};
128
+ this._users = {};
129
+ }
130
+ _toImmutable() {
131
+ const users = _chunkUV2F4F4Rjs.compact.call(void 0,
132
+ Object.keys(this._presences).map(
133
+ (connectionId) => this.getUser(Number(connectionId))
134
+ )
135
+ );
136
+ return _chunkUV2F4F4Rjs.asArrayWithLegacyMethods.call(void 0, users);
137
+ }
138
+ clearOthers() {
139
+ this._connections = {};
140
+ this._presences = {};
141
+ this._users = {};
142
+ this.invalidate();
143
+ }
144
+ _getUser(connectionId) {
145
+ const conn = this._connections[connectionId];
146
+ const presence = this._presences[connectionId];
147
+ if (conn !== void 0 && presence !== void 0) {
148
+ return makeUser(conn, presence);
59
149
  }
60
- }
61
- function _createClass(Constructor, protoProps, staticProps) {
62
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
63
- if (staticProps) _defineProperties(Constructor, staticProps);
64
- return Constructor;
65
- }
66
- function _defineProperty(obj, key, value) {
67
- if (key in obj) {
68
- Object.defineProperty(obj, key, {
69
- value: value,
70
- enumerable: true,
71
- configurable: true,
72
- writable: true
73
- });
74
- } else {
75
- obj[key] = value;
150
+ return void 0;
151
+ }
152
+ getUser(connectionId) {
153
+ const cachedUser = this._users[connectionId];
154
+ if (cachedUser) {
155
+ return cachedUser;
76
156
  }
77
- return obj;
78
- }
79
- function _getPrototypeOf(o) {
80
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
81
- return o.__proto__ || Object.getPrototypeOf(o);
82
- };
83
- return _getPrototypeOf(o);
84
- }
85
- function _inherits(subClass, superClass) {
86
- if (typeof superClass !== "function" && superClass !== null) {
87
- throw new TypeError("Super expression must either be null or a function");
88
- }
89
- subClass.prototype = Object.create(superClass && superClass.prototype, {
90
- constructor: {
91
- value: subClass,
92
- writable: true,
93
- configurable: true
94
- }
95
- });
96
- if (superClass) _setPrototypeOf(subClass, superClass);
97
- }
98
- function _instanceof(left, right) {
99
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
100
- return !!right[Symbol.hasInstance](left);
101
- } else {
102
- return left instanceof right;
157
+ const computedUser = this._getUser(connectionId);
158
+ if (computedUser) {
159
+ this._users[connectionId] = computedUser;
160
+ return computedUser;
103
161
  }
104
- }
105
- function _isNativeFunction(fn) {
106
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
107
- }
108
- function _iterableToArray(iter) {
109
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
110
- }
111
- function _iterableToArrayLimit(arr, i) {
112
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
113
- if (_i == null) return;
114
- var _arr = [];
115
- var _n = true;
116
- var _d = false;
117
- var _s, _e;
118
- try {
119
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
120
- _arr.push(_s.value);
121
- if (i && _arr.length === i) break;
122
- }
123
- } catch (err) {
124
- _d = true;
125
- _e = err;
126
- } finally{
127
- try {
128
- if (!_n && _i["return"] != null) _i["return"]();
129
- } finally{
130
- if (_d) throw _e;
131
- }
162
+ return void 0;
163
+ }
164
+ _invalidateUser(connectionId) {
165
+ if (this._users[connectionId] !== void 0) {
166
+ delete this._users[connectionId];
132
167
  }
133
- return _arr;
134
- }
135
- function _nonIterableRest() {
136
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
137
- }
138
- function _nonIterableSpread() {
139
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
140
- }
141
- function _objectSpread(target) {
142
- for(var i = 1; i < arguments.length; i++){
143
- var source = arguments[i] != null ? arguments[i] : {};
144
- var ownKeys = Object.keys(source);
145
- if (typeof Object.getOwnPropertySymbols === "function") {
146
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
147
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
148
- }));
149
- }
150
- ownKeys.forEach(function(key) {
151
- _defineProperty(target, key, source[key]);
152
- });
168
+ this.invalidate();
169
+ }
170
+ setConnection(connectionId, metaUserId, metaUserInfo) {
171
+ this._connections[connectionId] = _chunkUV2F4F4Rjs.freeze.call(void 0, {
172
+ connectionId,
173
+ id: metaUserId,
174
+ info: metaUserInfo
175
+ });
176
+ if (this._presences[connectionId] !== void 0) {
177
+ this._invalidateUser(connectionId);
153
178
  }
154
- return target;
155
- }
156
- function ownKeys(object, enumerableOnly) {
157
- var keys = Object.keys(object);
158
- if (Object.getOwnPropertySymbols) {
159
- var symbols = Object.getOwnPropertySymbols(object);
160
- if (enumerableOnly) {
161
- symbols = symbols.filter(function(sym) {
162
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
163
- });
164
- }
165
- keys.push.apply(keys, symbols);
179
+ }
180
+ removeConnection(connectionId) {
181
+ delete this._connections[connectionId];
182
+ delete this._presences[connectionId];
183
+ this._invalidateUser(connectionId);
184
+ }
185
+ setOther(connectionId, presence) {
186
+ this._presences[connectionId] = _chunkUV2F4F4Rjs.freeze.call(void 0, _chunkUV2F4F4Rjs.compactObject.call(void 0, presence));
187
+ if (this._connections[connectionId] !== void 0) {
188
+ this._invalidateUser(connectionId);
166
189
  }
167
- return keys;
168
- }
169
- function _objectSpreadProps(target, source) {
170
- source = source != null ? source : {};
171
- if (Object.getOwnPropertyDescriptors) {
172
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
173
- } else {
174
- ownKeys(Object(source)).forEach(function(key) {
175
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
176
- });
190
+ }
191
+ patchOther(connectionId, patch) {
192
+ const oldPresence = this._presences[connectionId];
193
+ if (oldPresence === void 0) {
194
+ return;
177
195
  }
178
- return target;
179
- }
180
- function _possibleConstructorReturn(self, call) {
181
- if (call && (_typeof(call) === "object" || typeof call === "function")) {
182
- return call;
196
+ const newPresence = merge(oldPresence, patch);
197
+ if (oldPresence !== newPresence) {
198
+ this._presences[connectionId] = _chunkUV2F4F4Rjs.freeze.call(void 0, newPresence);
199
+ this._invalidateUser(connectionId);
183
200
  }
184
- return _assertThisInitialized(self);
185
- }
186
- function _setPrototypeOf(o, p) {
187
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
188
- o.__proto__ = p;
189
- return o;
190
- };
191
- return _setPrototypeOf(o, p);
192
- }
193
- function _slicedToArray(arr, i) {
194
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
195
- }
196
- function _toConsumableArray(arr) {
197
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
198
- }
199
- var _typeof = function(obj) {
200
- "@swc/helpers - typeof";
201
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
201
+ }
202
202
  };
203
- function _unsupportedIterableToArray(o, minLen) {
204
- if (!o) return;
205
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
206
- var n = Object.prototype.toString.call(o).slice(8, -1);
207
- if (n === "Object" && o.constructor) n = o.constructor.name;
208
- if (n === "Map" || n === "Set") return Array.from(n);
209
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
210
- }
211
- function _wrapNativeSuper(Class) {
212
- var _cache = typeof Map === "function" ? new Map() : undefined;
213
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
214
- if (Class === null || !_isNativeFunction(Class)) return Class;
215
- if (typeof Class !== "function") {
216
- throw new TypeError("Super expression must either be null or a function");
217
- }
218
- if (typeof _cache !== "undefined") {
219
- if (_cache.has(Class)) return _cache.get(Class);
220
- _cache.set(Class, Wrapper);
221
- }
222
- function Wrapper() {
223
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
224
- }
225
- Wrapper.prototype = Object.create(Class.prototype, {
226
- constructor: {
227
- value: Wrapper,
228
- enumerable: false,
229
- writable: true,
230
- configurable: true
231
- }
232
- });
233
- return _setPrototypeOf(Wrapper, Class);
234
- };
235
- return _wrapNativeSuper(Class);
236
- }
237
- function _isNativeReflectConstruct() {
238
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
239
- if (Reflect.construct.sham) return false;
240
- if (typeof Proxy === "function") return true;
241
- try {
242
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
243
- return true;
244
- } catch (e) {
245
- return false;
246
- }
247
- }
248
- function _createSuper(Derived) {
249
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
250
- return function _createSuperInternal() {
251
- var Super = _getPrototypeOf(Derived), result;
252
- if (hasNativeReflectConstruct) {
253
- var NewTarget = _getPrototypeOf(this).constructor;
254
- result = Reflect.construct(Super, arguments, NewTarget);
255
- } else {
256
- result = Super.apply(this, arguments);
257
- }
258
- return _possibleConstructorReturn(this, result);
259
- };
260
- }
261
- Object.defineProperty(exports, "__esModule", {
262
- value: true
263
- });
264
- function _nullishCoalesce(lhs, rhsFn) {
265
- if (lhs != null) {
266
- return lhs;
267
- } else {
268
- return rhsFn();
269
- }
270
- }
271
- function _optionalChain(ops) {
272
- var lastAccessLHS = undefined;
273
- var value = ops[0];
274
- var i = 1;
275
- while(i < ops.length){
276
- var op = ops[i];
277
- var fn = ops[i + 1];
278
- i += 2;
279
- if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
280
- return undefined;
281
- }
282
- if (op === "access" || op === "optionalAccess") {
283
- lastAccessLHS = value;
284
- value = fn(value);
285
- } else if (op === "call" || op === "optionalCall") {
286
- var _value;
287
- value = fn(function() {
288
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
289
- args[_key] = arguments[_key];
290
- }
291
- return (_value = value).call.apply(_value, [
292
- lastAccessLHS
293
- ].concat(_toConsumableArray(args)));
294
- });
295
- lastAccessLHS = undefined;
296
- }
297
- }
298
- return value;
299
- }
300
- var _chunkZR7CHFN6js = require("./chunk-ZR7CHFN6.js");
301
- // src/EventSource.ts
302
- function makeEventSource() {
303
- var subscribe = function subscribe(callback) {
304
- _observers.add(callback);
305
- return function() {
306
- return _observers.delete(callback);
307
- };
308
- };
309
- var subscribeOnce = function subscribeOnce(callback) {
310
- _onetimeObservers.add(callback);
311
- return function() {
312
- return _onetimeObservers.delete(callback);
313
- };
314
- };
315
- var notify = function notify(event) {
316
- _onetimeObservers.forEach(function(callback) {
317
- return callback(event);
318
- });
319
- _onetimeObservers.clear();
320
- _observers.forEach(function(callback) {
321
- return callback(event);
322
- });
323
- };
324
- var clear = function clear() {
325
- _onetimeObservers.clear();
326
- _observers.clear();
327
- };
328
- var _onetimeObservers = /* @__PURE__ */ new Set();
329
- var _observers = /* @__PURE__ */ new Set();
330
- return {
331
- notify: notify,
332
- subscribe: subscribe,
333
- subscribeOnce: subscribeOnce,
334
- clear: clear,
335
- observable: {
336
- subscribe: subscribe,
337
- subscribeOnce: subscribeOnce
338
- }
339
- };
340
- }
341
- // src/ImmutableRef.ts
342
- function merge(target, patch) {
343
- var updated = false;
344
- var newValue = _objectSpread({}, target);
345
- Object.keys(patch).forEach(function(k) {
346
- var key = k;
347
- var val = patch[key];
348
- if (newValue[key] !== val) {
349
- if (val === void 0) {
350
- delete newValue[key];
351
- } else {
352
- newValue[key] = val;
353
- }
354
- updated = true;
355
- }
356
- });
357
- return updated ? newValue : target;
358
- }
359
- var ImmutableRef = /*#__PURE__*/ function() {
360
- function ImmutableRef() {
361
- _classCallCheck(this, ImmutableRef);
362
- this._ev = makeEventSource();
363
- }
364
- _createClass(ImmutableRef, [
365
- {
366
- key: "didInvalidate",
367
- get: function get() {
368
- return this._ev.observable;
369
- }
370
- },
371
- {
372
- key: "invalidate",
373
- value: function invalidate() {
374
- if (this._cache !== void 0) {
375
- this._cache = void 0;
376
- this._ev.notify();
377
- }
378
- }
379
- },
380
- {
381
- key: "current",
382
- get: function get() {
383
- var _this = this;
384
- return _nullishCoalesce(this._cache, function() {
385
- return _this._cache = _this._toImmutable();
386
- });
387
- }
388
- }
389
- ]);
390
- return ImmutableRef;
391
- }();
392
- // src/MeRef.ts
393
- var MeRef = /*#__PURE__*/ function(ImmutableRef) {
394
- _inherits(MeRef, ImmutableRef);
395
- var _super = _createSuper(MeRef);
396
- function MeRef(initialPresence) {
397
- _classCallCheck(this, MeRef);
398
- var _this;
399
- _this = _super.call(this);
400
- _this._me = _chunkZR7CHFN6js.freeze.call(void 0, _chunkZR7CHFN6js.compactObject.call(void 0, initialPresence));
401
- return _this;
402
- }
403
- _createClass(MeRef, [
404
- {
405
- key: "_toImmutable",
406
- value: function _toImmutable() {
407
- return this._me;
408
- }
409
- },
410
- {
411
- key: "patch",
412
- value: function patch(patch1) {
413
- var oldMe = this._me;
414
- var newMe = merge(oldMe, patch1);
415
- if (oldMe !== newMe) {
416
- this._me = _chunkZR7CHFN6js.freeze.call(void 0, newMe);
417
- this.invalidate();
418
- }
419
- }
420
- }
421
- ]);
422
- return MeRef;
423
- }(ImmutableRef);
424
- // src/OthersRef.ts
425
- function makeUser(conn, presence) {
426
- return _chunkZR7CHFN6js.freeze.call(void 0, _chunkZR7CHFN6js.compactObject.call(void 0, _objectSpreadProps(_objectSpread({}, conn), {
427
- presence: presence
428
- })));
429
- }
430
- var OthersRef = /*#__PURE__*/ function(ImmutableRef) {
431
- _inherits(OthersRef, ImmutableRef);
432
- var _super = _createSuper(OthersRef);
433
- function OthersRef() {
434
- _classCallCheck(this, OthersRef);
435
- var _this;
436
- _this = _super.call(this);
437
- _this._connections = {};
438
- _this._presences = {};
439
- _this._users = {};
440
- return _this;
441
- }
442
- _createClass(OthersRef, [
443
- {
444
- key: "_toImmutable",
445
- value: function _toImmutable() {
446
- var _this = this;
447
- var users = _chunkZR7CHFN6js.compact.call(void 0, Object.keys(this._presences).map(function(connectionId) {
448
- return _this.getUser(Number(connectionId));
449
- }));
450
- Object.defineProperty(users, "count", {
451
- value: users.length,
452
- enumerable: false
453
- });
454
- Object.defineProperty(users, "toArray", {
455
- value: function() {
456
- return users;
457
- },
458
- enumerable: false
459
- });
460
- return _chunkZR7CHFN6js.freeze.call(void 0, users);
461
- }
462
- },
463
- {
464
- key: "clearOthers",
465
- value: function clearOthers() {
466
- this._connections = {};
467
- this._presences = {};
468
- this._users = {};
469
- this.invalidate();
470
- }
471
- },
472
- {
473
- key: "_getUser",
474
- value: function _getUser(connectionId) {
475
- var conn = this._connections[connectionId];
476
- var presence = this._presences[connectionId];
477
- if (conn !== void 0 && presence !== void 0) {
478
- return makeUser(conn, presence);
479
- }
480
- return void 0;
481
- }
482
- },
483
- {
484
- key: "getUser",
485
- value: function getUser(connectionId) {
486
- var cachedUser = this._users[connectionId];
487
- if (cachedUser) {
488
- return cachedUser;
489
- }
490
- var computedUser = this._getUser(connectionId);
491
- if (computedUser) {
492
- this._users[connectionId] = computedUser;
493
- return computedUser;
494
- }
495
- return void 0;
496
- }
497
- },
498
- {
499
- key: "_invalidateUser",
500
- value: function _invalidateUser(connectionId) {
501
- if (this._users[connectionId] !== void 0) {
502
- delete this._users[connectionId];
503
- }
504
- this.invalidate();
505
- }
506
- },
507
- {
508
- key: "setConnection",
509
- value: function setConnection(connectionId, metaUserId, metaUserInfo) {
510
- this._connections[connectionId] = _chunkZR7CHFN6js.freeze.call(void 0, {
511
- connectionId: connectionId,
512
- id: metaUserId,
513
- info: metaUserInfo
514
- });
515
- if (this._presences[connectionId] !== void 0) {
516
- this._invalidateUser(connectionId);
517
- }
518
- }
519
- },
520
- {
521
- key: "removeConnection",
522
- value: function removeConnection(connectionId) {
523
- delete this._connections[connectionId];
524
- delete this._presences[connectionId];
525
- this._invalidateUser(connectionId);
526
- }
527
- },
528
- {
529
- key: "setOther",
530
- value: function setOther(connectionId, presence) {
531
- this._presences[connectionId] = _chunkZR7CHFN6js.freeze.call(void 0, _chunkZR7CHFN6js.compactObject.call(void 0, presence));
532
- if (this._connections[connectionId] !== void 0) {
533
- this._invalidateUser(connectionId);
534
- }
535
- }
536
- },
537
- {
538
- key: "patchOther",
539
- value: function patchOther(connectionId, patch) {
540
- var oldPresence = this._presences[connectionId];
541
- if (oldPresence === void 0) {
542
- return;
543
- }
544
- var newPresence = merge(oldPresence, patch);
545
- if (oldPresence !== newPresence) {
546
- this._presences[connectionId] = _chunkZR7CHFN6js.freeze.call(void 0, newPresence);
547
- this._invalidateUser(connectionId);
548
- }
549
- }
550
- }
551
- ]);
552
- return OthersRef;
553
- }(ImmutableRef);
203
+
554
204
  // src/ValueRef.ts
555
- var ValueRef = /*#__PURE__*/ function(ImmutableRef) {
556
- _inherits(ValueRef, ImmutableRef);
557
- var _super = _createSuper(ValueRef);
558
- function ValueRef(initialValue) {
559
- _classCallCheck(this, ValueRef);
560
- var _this;
561
- _this = _super.call(this);
562
- _this._value = _chunkZR7CHFN6js.freeze.call(void 0, _chunkZR7CHFN6js.compactObject.call(void 0, initialValue));
563
- return _this;
564
- }
565
- _createClass(ValueRef, [
566
- {
567
- key: "_toImmutable",
568
- value: function _toImmutable() {
569
- return this._value;
570
- }
571
- },
572
- {
573
- key: "set",
574
- value: function set(newValue) {
575
- this._value = _chunkZR7CHFN6js.freeze.call(void 0, newValue);
576
- this.invalidate();
577
- }
578
- }
579
- ]);
580
- return ValueRef;
581
- }(ImmutableRef);
582
- var DerivedRef = /*#__PURE__*/ function(ImmutableRef) {
583
- _inherits(DerivedRef, ImmutableRef);
584
- var _super = _createSuper(DerivedRef);
585
- function DerivedRef(otherRefs, transformFn) {
586
- _classCallCheck(this, DerivedRef);
587
- var _this;
588
- _this = _super.call(this);
589
- _this._refs = otherRefs;
590
- _this._refs.forEach(function(ref) {
591
- ref.didInvalidate.subscribe(function() {
592
- return _this.invalidate();
593
- });
594
- });
595
- _this._transform = transformFn;
596
- return _this;
597
- }
598
- _createClass(DerivedRef, [
599
- {
600
- key: "_toImmutable",
601
- value: function _toImmutable() {
602
- return this._transform(this._refs[0].current, this._refs[1].current);
603
- }
604
- }
605
- ]);
606
- return DerivedRef;
607
- }(ImmutableRef);
205
+ var ValueRef = class extends ImmutableRef {
206
+ constructor(initialValue) {
207
+ super();
208
+ this._value = _chunkUV2F4F4Rjs.freeze.call(void 0, _chunkUV2F4F4Rjs.compactObject.call(void 0, initialValue));
209
+ }
210
+ _toImmutable() {
211
+ return this._value;
212
+ }
213
+ set(newValue) {
214
+ this._value = _chunkUV2F4F4Rjs.freeze.call(void 0, newValue);
215
+ this.invalidate();
216
+ }
217
+ };
218
+ var DerivedRef = class extends ImmutableRef {
219
+ constructor(otherRefs, transformFn) {
220
+ super();
221
+ this._refs = otherRefs;
222
+ this._refs.forEach((ref) => {
223
+ ref.didInvalidate.subscribe(() => this.invalidate());
224
+ });
225
+ this._transform = transformFn;
226
+ }
227
+ _toImmutable() {
228
+ return this._transform(this._refs[0].current, this._refs[1].current);
229
+ }
230
+ };
231
+
608
232
  // src/room.ts
609
- var BACKOFF_RETRY_DELAYS = [
610
- 250,
611
- 500,
612
- 1e3,
613
- 2e3,
614
- 4e3,
615
- 8e3,
616
- 1e4
617
- ];
618
- var BACKOFF_RETRY_DELAYS_SLOW = [
619
- 2e3,
620
- 3e4,
621
- 6e4,
622
- 3e5
623
- ];
233
+ var BACKOFF_RETRY_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
234
+ var BACKOFF_RETRY_DELAYS_SLOW = [2e3, 3e4, 6e4, 3e5];
624
235
  var HEARTBEAT_INTERVAL = 3e4;
625
236
  var PONG_TIMEOUT = 2e3;
626
237
  function makeIdFactory(connectionId) {
627
- var count = 0;
628
- return function() {
629
- return "".concat(connectionId, ":").concat(count++);
630
- };
238
+ let count = 0;
239
+ return () => `${connectionId}:${count++}`;
631
240
  }
632
- function log() {
633
- for(var _len = arguments.length, _params = new Array(_len), _key = 0; _key < _len; _key++){
634
- _params[_key] = arguments[_key];
635
- }
636
- return;
241
+ function log(..._params) {
242
+ return;
637
243
  }
638
244
  function isConnectionSelfAware(connection) {
639
- return connection.state === "open" || connection.state === "connecting";
245
+ return connection.state === "open" || connection.state === "connecting";
640
246
  }
641
247
  function makeStateMachine(state, config, mockedEffects) {
642
- var createOrUpdateRootFromMessage = function createOrUpdateRootFromMessage(message) {
643
- if (message.items.length === 0) {
644
- throw new Error("Internal error: cannot load storage without items");
645
- }
646
- if (state.root) {
647
- updateRoot(message.items);
648
- } else {
649
- state.root = load(message.items);
650
- }
651
- for(var key in state.defaultStorageRoot){
652
- if (state.root.get(key) == null) {
653
- state.root.set(key, state.defaultStorageRoot[key]);
654
- }
655
- }
656
- };
657
- var buildRootAndParentToChildren = function buildRootAndParentToChildren(items) {
658
- var parentToChildren = /* @__PURE__ */ new Map();
659
- var root = null;
660
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
661
- try {
662
- for(var _iterator = items[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
663
- var _value = _slicedToArray(_step.value, 2), id = _value[0], crdt = _value[1];
664
- if (_chunkZR7CHFN6js.isRootCrdt.call(void 0, crdt)) {
665
- root = [
666
- id,
667
- crdt
668
- ];
669
- } else {
670
- var tuple = [
671
- id,
672
- crdt
673
- ];
674
- var children = parentToChildren.get(crdt.parentId);
675
- if (children != null) {
676
- children.push(tuple);
677
- } else {
678
- parentToChildren.set(crdt.parentId, [
679
- tuple
680
- ]);
681
- }
682
- }
683
- }
684
- } catch (err) {
685
- _didIteratorError = true;
686
- _iteratorError = err;
687
- } finally{
688
- try {
689
- if (!_iteratorNormalCompletion && _iterator.return != null) {
690
- _iterator.return();
691
- }
692
- } finally{
693
- if (_didIteratorError) {
694
- throw _iteratorError;
695
- }
696
- }
697
- }
698
- if (root == null) {
699
- throw new Error("Root can't be null");
700
- }
701
- return [
702
- root,
703
- parentToChildren
704
- ];
705
- };
706
- var updateRoot = function updateRoot(items) {
707
- if (!state.root) {
708
- return;
709
- }
710
- var currentItems = /* @__PURE__ */ new Map();
711
- state.nodes.forEach(function(node, id) {
712
- currentItems.set(id, node._serialize());
713
- });
714
- var ops = _chunkZR7CHFN6js.getTreesDiffOperations.call(void 0, currentItems, new Map(items));
715
- var result = apply(ops, false);
716
- notify(result.updates);
717
- };
718
- var load = function load(items) {
719
- var ref = _slicedToArray(buildRootAndParentToChildren(items), 2), root = ref[0], parentToChildren = ref[1];
720
- return _chunkZR7CHFN6js.LiveObject._deserialize(root, parentToChildren, pool);
721
- };
722
- var addToUndoStack = function addToUndoStack(historyItem) {
723
- if (state.undoStack.length >= 50) {
724
- state.undoStack.shift();
725
- }
726
- if (state.isHistoryPaused) {
727
- var _pausedHistory;
728
- (_pausedHistory = state.pausedHistory).unshift.apply(_pausedHistory, _toConsumableArray(historyItem));
729
- } else {
730
- state.undoStack.push(historyItem);
731
- onHistoryChange();
732
- }
733
- };
734
- var notify = function notify(param) {
735
- var _storageUpdates = param.storageUpdates, storageUpdates = _storageUpdates === void 0 ? /* @__PURE__ */ new Map() : _storageUpdates, _presence = param.presence, presence = _presence === void 0 ? false : _presence, tmp = param.others, otherEvents = tmp === void 0 ? [] : tmp;
736
- if (otherEvents.length > 0) {
737
- var others = state.others.current;
738
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
739
- try {
740
- for(var _iterator = otherEvents[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
741
- var event = _step.value;
742
- eventHub.others.notify({
743
- others: others,
744
- event: event
745
- });
746
- }
747
- } catch (err) {
748
- _didIteratorError = true;
749
- _iteratorError = err;
750
- } finally{
751
- try {
752
- if (!_iteratorNormalCompletion && _iterator.return != null) {
753
- _iterator.return();
754
- }
755
- } finally{
756
- if (_didIteratorError) {
757
- throw _iteratorError;
758
- }
759
- }
760
- }
761
- }
762
- if (presence) {
763
- eventHub.me.notify(state.me.current);
764
- }
765
- if (storageUpdates.size > 0) {
766
- var updates = Array.from(storageUpdates.values());
767
- eventHub.storage.notify(updates);
768
- }
769
- };
770
- var getConnectionId = function getConnectionId() {
771
- var conn = state.connection.current;
772
- if (isConnectionSelfAware(conn)) {
773
- return conn.id;
774
- } else if (state.lastConnectionId !== null) {
775
- return state.lastConnectionId;
776
- }
777
- throw new Error("Internal. Tried to get connection id but connection was never open");
778
- };
779
- var apply = function apply(item, isLocal) {
780
- var result = {
781
- reverse: [],
782
- updates: {
783
- storageUpdates: /* @__PURE__ */ new Map(),
784
- presence: false
785
- }
786
- };
787
- var createdNodeIds = /* @__PURE__ */ new Set();
788
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
789
- try {
790
- for(var _iterator = item[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
791
- var op = _step.value;
792
- if (op.type === "presence") {
793
- var reverse = {
794
- type: "presence",
795
- data: {}
796
- };
797
- for(var key in op.data){
798
- reverse.data[key] = state.me.current[key];
799
- }
800
- state.me.patch(op.data);
801
- if (state.buffer.me == null) {
802
- state.buffer.me = {
803
- type: "partial",
804
- data: op.data
805
- };
806
- } else {
807
- for(var key1 in op.data){
808
- state.buffer.me.data[key1] = op.data[key1];
809
- }
810
- }
811
- result.reverse.unshift(reverse);
812
- result.updates.presence = true;
813
- } else {
814
- var source = void 0;
815
- if (!op.opId) {
816
- op.opId = pool.generateOpId();
817
- }
818
- if (isLocal) {
819
- source = 0 /* UNDOREDO_RECONNECT */ ;
820
- } else {
821
- var deleted = state.offlineOperations.delete(_chunkZR7CHFN6js.nn.call(void 0, op.opId));
822
- source = deleted ? 2 /* ACK */ : 1 /* REMOTE */ ;
823
- }
824
- var applyOpResult = applyOp(op, source);
825
- if (applyOpResult.modified) {
826
- var parentId = applyOpResult.modified.node.parent.type === "HasParent" ? _chunkZR7CHFN6js.nn.call(void 0, applyOpResult.modified.node.parent.node._id, "Expected parent node to have an ID") : void 0;
827
- if (!parentId || !createdNodeIds.has(parentId)) {
828
- var _reverse;
829
- result.updates.storageUpdates.set(_chunkZR7CHFN6js.nn.call(void 0, applyOpResult.modified.node._id), _chunkZR7CHFN6js.mergeStorageUpdates.call(void 0, result.updates.storageUpdates.get(_chunkZR7CHFN6js.nn.call(void 0, applyOpResult.modified.node._id)), applyOpResult.modified));
830
- (_reverse = result.reverse).unshift.apply(_reverse, _toConsumableArray(applyOpResult.reverse));
831
- }
832
- if (op.type === 2 /* CREATE_LIST */ || op.type === 7 /* CREATE_MAP */ || op.type === 4 /* CREATE_OBJECT */ ) {
833
- createdNodeIds.add(_chunkZR7CHFN6js.nn.call(void 0, applyOpResult.modified.node._id));
834
- }
835
- }
836
- }
837
- }
838
- } catch (err) {
839
- _didIteratorError = true;
840
- _iteratorError = err;
841
- } finally{
842
- try {
843
- if (!_iteratorNormalCompletion && _iterator.return != null) {
844
- _iterator.return();
845
- }
846
- } finally{
847
- if (_didIteratorError) {
848
- throw _iteratorError;
849
- }
850
- }
851
- }
852
- return result;
853
- };
854
- var applyOp = function applyOp(op, source) {
855
- switch(op.type){
856
- case 6 /* DELETE_OBJECT_KEY */ :
857
- case 3 /* UPDATE_OBJECT */ :
858
- case 5 /* DELETE_CRDT */ :
859
- {
860
- var node = state.nodes.get(op.id);
861
- if (node == null) {
862
- return {
863
- modified: false
864
- };
865
- }
866
- return node._apply(op, source === 0 /* UNDOREDO_RECONNECT */ );
867
- }
868
- case 1 /* SET_PARENT_KEY */ :
869
- {
870
- var node1 = state.nodes.get(op.id);
871
- if (node1 == null) {
872
- return {
873
- modified: false
874
- };
875
- }
876
- if (node1.parent.type === "HasParent" && _chunkZR7CHFN6js.isLiveList.call(void 0, node1.parent.node)) {
877
- return node1.parent.node._setChildKey(op.parentKey, node1, source);
878
- }
879
- return {
880
- modified: false
881
- };
882
- }
883
- case 4 /* CREATE_OBJECT */ :
884
- case 2 /* CREATE_LIST */ :
885
- case 7 /* CREATE_MAP */ :
886
- case 8 /* CREATE_REGISTER */ :
887
- {
888
- if (op.parentId === void 0) {
889
- return {
890
- modified: false
891
- };
892
- }
893
- var parentNode = state.nodes.get(op.parentId);
894
- if (parentNode == null) {
895
- return {
896
- modified: false
897
- };
898
- }
899
- return parentNode._attachChild(op, source);
900
- }
901
- }
902
- };
903
- var subscribeToLiveStructureDeeply = function subscribeToLiveStructureDeeply(node, callback) {
904
- return eventHub.storage.subscribe(function(updates) {
905
- var relatedUpdates = updates.filter(function(update) {
906
- return _chunkZR7CHFN6js.isSameNodeOrChildOf.call(void 0, update.node, node);
907
- });
908
- if (relatedUpdates.length > 0) {
909
- callback(relatedUpdates);
910
- }
911
- });
912
- };
913
- var subscribeToLiveStructureShallowly = function subscribeToLiveStructureShallowly(node, callback) {
914
- return eventHub.storage.subscribe(function(updates) {
915
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
916
- try {
917
- for(var _iterator = updates[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
918
- var update = _step.value;
919
- if (update.node._id === node._id) {
920
- callback(update.node);
921
- }
922
- }
923
- } catch (err) {
924
- _didIteratorError = true;
925
- _iteratorError = err;
926
- } finally{
927
- try {
928
- if (!_iteratorNormalCompletion && _iterator.return != null) {
929
- _iterator.return();
930
- }
931
- } finally{
932
- if (_didIteratorError) {
933
- throw _iteratorError;
934
- }
935
- }
936
- }
937
- });
938
- };
939
- var subscribe = function subscribe(first, second, options) {
940
- if (typeof first === "string" && _chunkZR7CHFN6js.isRoomEventName.call(void 0, first)) {
941
- if (typeof second !== "function") {
942
- throw new Error("Second argument must be a callback function");
943
- }
944
- var callback = second;
945
- switch(first){
946
- case "event":
947
- return eventHub.customEvent.subscribe(callback);
948
- case "my-presence":
949
- return eventHub.me.subscribe(callback);
950
- case "others":
951
- {
952
- var cb = callback;
953
- return eventHub.others.subscribe(function(param) {
954
- var others = param.others, event = param.event;
955
- return cb(others, event);
956
- });
957
- }
958
- case "error":
959
- return eventHub.error.subscribe(callback);
960
- case "connection":
961
- return eventHub.connection.subscribe(callback);
962
- case "storage":
963
- return eventHub.storage.subscribe(callback);
964
- case "history":
965
- return eventHub.history.subscribe(callback);
966
- default:
967
- return _chunkZR7CHFN6js.assertNever.call(void 0, first, "Unknown event");
968
- }
969
- }
970
- if (second === void 0 || typeof first === "function") {
971
- if (typeof first === "function") {
972
- var storageCallback = first;
973
- return eventHub.storage.subscribe(storageCallback);
974
- } else {
975
- throw new Error("Please specify a listener callback");
976
- }
977
- }
978
- if (_chunkZR7CHFN6js.isLiveNode.call(void 0, first)) {
979
- var node = first;
980
- if (_optionalChain([
981
- options,
982
- "optionalAccess",
983
- function(_) {
984
- return _.isDeep;
985
- }
986
- ])) {
987
- var storageCallback1 = second;
988
- return subscribeToLiveStructureDeeply(node, storageCallback1);
989
- } else {
990
- var nodeCallback = second;
991
- return subscribeToLiveStructureShallowly(node, nodeCallback);
992
- }
993
- }
994
- throw new Error('"'.concat(first, '" is not a valid event name'));
995
- };
996
- var getConnectionState = function getConnectionState() {
997
- return state.connection.current.state;
998
- };
999
- var connect = function connect() {
1000
- if (state.connection.current.state !== "closed" && state.connection.current.state !== "unavailable") {
1001
- return null;
1002
- }
1003
- var auth = prepareAuthEndpoint(config.authentication, _nullishCoalesce(_optionalChain([
1004
- config,
1005
- "access",
1006
- function(_2) {
1007
- return _2.polyfills;
1008
- },
1009
- "optionalAccess",
1010
- function(_3) {
1011
- return _3.fetch;
1012
- }
1013
- ]), function() {
1014
- return config.fetchPolyfill;
1015
- }));
1016
- var createWebSocket = prepareCreateWebSocket(config.liveblocksServer, _nullishCoalesce(_optionalChain([
1017
- config,
1018
- "access",
1019
- function(_4) {
1020
- return _4.polyfills;
1021
- },
1022
- "optionalAccess",
1023
- function(_5) {
1024
- return _5.WebSocket;
1025
- }
1026
- ]), function() {
1027
- return config.WebSocketPolyfill;
1028
- }));
1029
- updateConnection({
1030
- state: "authenticating"
1031
- });
1032
- effects.authenticate(auth, createWebSocket);
1033
- };
1034
- var updatePresence = function updatePresence(patch, options) {
1035
- var oldValues = {};
1036
- if (state.buffer.me == null) {
1037
- state.buffer.me = {
1038
- type: "partial",
1039
- data: {}
1040
- };
1041
- }
1042
- for(var key in patch){
1043
- var overrideValue = patch[key];
1044
- if (overrideValue === void 0) {
1045
- continue;
1046
- }
1047
- state.buffer.me.data[key] = overrideValue;
1048
- oldValues[key] = state.me.current[key];
1049
- }
1050
- state.me.patch(patch);
1051
- if (state.isBatching) {
1052
- if (_optionalChain([
1053
- options,
1054
- "optionalAccess",
1055
- function(_6) {
1056
- return _6.addToHistory;
1057
- }
1058
- ])) {
1059
- state.batch.reverseOps.push({
1060
- type: "presence",
1061
- data: oldValues
1062
- });
1063
- }
1064
- state.batch.updates.presence = true;
1065
- } else {
1066
- tryFlushing();
1067
- if (_optionalChain([
1068
- options,
1069
- "optionalAccess",
1070
- function(_7) {
1071
- return _7.addToHistory;
1072
- }
1073
- ])) {
1074
- addToUndoStack([
1075
- {
1076
- type: "presence",
1077
- data: oldValues
1078
- }
1079
- ]);
1080
- }
1081
- notify({
1082
- presence: true
1083
- });
1084
- }
1085
- };
1086
- var authenticationSuccess = function authenticationSuccess(token, socket) {
1087
- socket.addEventListener("message", onMessage);
1088
- socket.addEventListener("open", onOpen);
1089
- socket.addEventListener("close", onClose);
1090
- socket.addEventListener("error", onError);
1091
- updateConnection({
1092
- state: "connecting",
1093
- id: token.actor,
1094
- userInfo: token.info,
1095
- userId: token.id
1096
- });
1097
- state.idFactory = makeIdFactory(token.actor);
1098
- state.socket = socket;
1099
- };
1100
- var authenticationFailure = function authenticationFailure(error) {
1101
- if (process.env.NODE_ENV !== "production") {
1102
- console.error("Call to authentication endpoint failed", error);
1103
- }
1104
- state.token = null;
1105
- updateConnection({
1106
- state: "unavailable"
248
+ const pool = {
249
+ roomId: config.roomId,
250
+ getNode: (id) => state.nodes.get(id),
251
+ addNode: (id, node) => void state.nodes.set(id, node),
252
+ deleteNode: (id) => void state.nodes.delete(id),
253
+ generateId: () => `${getConnectionId()}:${state.clock++}`,
254
+ generateOpId: () => `${getConnectionId()}:${state.opClock++}`,
255
+ dispatch(ops, reverse, storageUpdates) {
256
+ const activeBatch = state.activeBatch;
257
+ if (activeBatch) {
258
+ activeBatch.ops.push(...ops);
259
+ storageUpdates.forEach((value, key) => {
260
+ activeBatch.updates.storageUpdates.set(
261
+ key,
262
+ _chunkUV2F4F4Rjs.mergeStorageUpdates.call(void 0,
263
+ activeBatch.updates.storageUpdates.get(key),
264
+ value
265
+ )
266
+ );
1107
267
  });
1108
- state.numberOfRetry++;
1109
- state.timeoutHandles.reconnect = effects.scheduleReconnect(getRetryDelay());
1110
- };
1111
- var onVisibilityChange = function onVisibilityChange(visibilityState) {
1112
- if (visibilityState === "visible" && state.connection.current.state === "open") {
1113
- log("Heartbeat after visibility change");
1114
- heartbeat();
1115
- }
1116
- };
1117
- var onUpdatePresenceMessage = function onUpdatePresenceMessage(message) {
1118
- if (message.targetActor !== void 0) {
1119
- var oldUser = state.others.getUser(message.actor);
1120
- state.others.setOther(message.actor, message.data);
1121
- var newUser = state.others.getUser(message.actor);
1122
- if (oldUser === void 0 && newUser !== void 0) {
1123
- return {
1124
- type: "enter",
1125
- user: newUser
1126
- };
1127
- }
1128
- } else {
1129
- state.others.patchOther(message.actor, message.data), message;
1130
- }
1131
- var user = state.others.getUser(message.actor);
1132
- if (user) {
1133
- return {
1134
- type: "update",
1135
- updates: message.data,
1136
- user: user
1137
- };
1138
- } else {
1139
- return void 0;
1140
- }
1141
- };
1142
- var onUserLeftMessage = function onUserLeftMessage(message) {
1143
- var user = state.others.getUser(message.actor);
1144
- if (user) {
1145
- state.others.removeConnection(message.actor);
1146
- return {
1147
- type: "leave",
1148
- user: user
1149
- };
1150
- }
1151
- return null;
1152
- };
1153
- var onRoomStateMessage = function onRoomStateMessage(message) {
1154
- for(var key in message.users){
1155
- var user = message.users[key];
1156
- var connectionId = Number(key);
1157
- state.others.setConnection(connectionId, user.id, user.info);
1158
- }
1159
- return {
1160
- type: "reset"
1161
- };
1162
- };
1163
- var onNavigatorOnline = function onNavigatorOnline() {
1164
- if (state.connection.current.state === "unavailable") {
1165
- log("Try to reconnect after connectivity change");
1166
- reconnect();
1167
- }
1168
- };
1169
- var onHistoryChange = function onHistoryChange() {
1170
- eventHub.history.notify({
1171
- canUndo: canUndo(),
1172
- canRedo: canRedo()
1173
- });
1174
- };
1175
- var onUserJoinedMessage = function onUserJoinedMessage(message) {
1176
- state.others.setConnection(message.actor, message.id, message.info);
1177
- state.buffer.messages.push({
1178
- type: 100 /* UPDATE_PRESENCE */ ,
1179
- data: state.me.current,
1180
- targetActor: message.actor
1181
- });
1182
- tryFlushing();
1183
- var user = state.others.getUser(message.actor);
1184
- return user ? {
1185
- type: "enter",
1186
- user: user
1187
- } : void 0;
1188
- };
1189
- var parseServerMessage = function parseServerMessage(data) {
1190
- if (!_chunkZR7CHFN6js.isJsonObject.call(void 0, data)) {
1191
- return null;
1192
- }
1193
- return data;
1194
- };
1195
- var parseServerMessages = function parseServerMessages(text) {
1196
- var data = _chunkZR7CHFN6js.tryParseJson.call(void 0, text);
1197
- if (data === void 0) {
1198
- return null;
1199
- } else if (_chunkZR7CHFN6js.isJsonArray.call(void 0, data)) {
1200
- return _chunkZR7CHFN6js.compact.call(void 0, data.map(function(item) {
1201
- return parseServerMessage(item);
1202
- }));
1203
- } else {
1204
- return _chunkZR7CHFN6js.compact.call(void 0, [
1205
- parseServerMessage(data)
1206
- ]);
1207
- }
1208
- };
1209
- var onMessage = function onMessage(event) {
1210
- if (event.data === "pong") {
1211
- clearTimeout(state.timeoutHandles.pongTimeout);
1212
- return;
1213
- }
1214
- var messages = parseServerMessages(event.data);
1215
- if (messages === null || messages.length === 0) {
268
+ activeBatch.reverseOps.push(...reverse);
269
+ } else {
270
+ addToUndoStack(reverse);
271
+ state.redoStack = [];
272
+ dispatchOps(ops);
273
+ notify({ storageUpdates });
274
+ }
275
+ }
276
+ };
277
+ const eventHub = {
278
+ customEvent: makeEventSource(),
279
+ me: makeEventSource(),
280
+ others: makeEventSource(),
281
+ error: makeEventSource(),
282
+ connection: makeEventSource(),
283
+ storage: makeEventSource(),
284
+ history: makeEventSource(),
285
+ storageDidLoad: makeEventSource()
286
+ };
287
+ const effects = mockedEffects || {
288
+ authenticate(auth, createWebSocket) {
289
+ const rawToken = state.token;
290
+ const parsedToken = rawToken !== null && _chunkUV2F4F4Rjs.parseRoomAuthToken.call(void 0, rawToken);
291
+ if (parsedToken && !_chunkUV2F4F4Rjs.isTokenExpired.call(void 0, parsedToken)) {
292
+ const socket = createWebSocket(rawToken);
293
+ authenticationSuccess(parsedToken, socket);
294
+ } else {
295
+ return auth(config.roomId).then(({ token }) => {
296
+ if (state.connection.current.state !== "authenticating") {
1216
297
  return;
298
+ }
299
+ const parsedToken2 = _chunkUV2F4F4Rjs.parseRoomAuthToken.call(void 0, token);
300
+ const socket = createWebSocket(token);
301
+ authenticationSuccess(parsedToken2, socket);
302
+ state.token = token;
303
+ }).catch(
304
+ (er) => authenticationFailure(
305
+ er instanceof Error ? er : new Error(String(er))
306
+ )
307
+ );
308
+ }
309
+ },
310
+ send(messageOrMessages) {
311
+ if (state.socket === null) {
312
+ throw new Error("Can't send message if socket is null");
313
+ }
314
+ state.socket.send(JSON.stringify(messageOrMessages));
315
+ },
316
+ delayFlush(delay) {
317
+ return setTimeout(tryFlushing, delay);
318
+ },
319
+ startHeartbeatInterval() {
320
+ return setInterval(heartbeat, HEARTBEAT_INTERVAL);
321
+ },
322
+ schedulePongTimeout() {
323
+ return setTimeout(pongTimeout, PONG_TIMEOUT);
324
+ },
325
+ scheduleReconnect(delay) {
326
+ return setTimeout(connect, delay);
327
+ }
328
+ };
329
+ const self = new DerivedRef(
330
+ [state.connection, state.me],
331
+ (conn, me) => isConnectionSelfAware(conn) ? {
332
+ connectionId: conn.id,
333
+ id: conn.userId,
334
+ info: conn.userInfo,
335
+ presence: me
336
+ } : null
337
+ );
338
+ function createOrUpdateRootFromMessage(message) {
339
+ if (message.items.length === 0) {
340
+ throw new Error("Internal error: cannot load storage without items");
341
+ }
342
+ if (state.root) {
343
+ updateRoot(message.items);
344
+ } else {
345
+ state.root = load(message.items);
346
+ }
347
+ for (const key in state.initialStorage) {
348
+ if (state.root.get(key) === void 0) {
349
+ state.root.set(key, state.initialStorage[key]);
350
+ }
351
+ }
352
+ }
353
+ function buildRootAndParentToChildren(items) {
354
+ const parentToChildren = /* @__PURE__ */ new Map();
355
+ let root = null;
356
+ for (const [id, crdt] of items) {
357
+ if (_chunkUV2F4F4Rjs.isRootCrdt.call(void 0, crdt)) {
358
+ root = [id, crdt];
359
+ } else {
360
+ const tuple = [id, crdt];
361
+ const children = parentToChildren.get(crdt.parentId);
362
+ if (children !== void 0) {
363
+ children.push(tuple);
364
+ } else {
365
+ parentToChildren.set(crdt.parentId, [tuple]);
1217
366
  }
1218
- var updates = {
1219
- storageUpdates: /* @__PURE__ */ new Map(),
1220
- others: []
367
+ }
368
+ }
369
+ if (root === null) {
370
+ throw new Error("Root can't be null");
371
+ }
372
+ return [root, parentToChildren];
373
+ }
374
+ function updateRoot(items) {
375
+ if (!state.root) {
376
+ return;
377
+ }
378
+ const currentItems = /* @__PURE__ */ new Map();
379
+ state.nodes.forEach((node, id) => {
380
+ currentItems.set(id, node._serialize());
381
+ });
382
+ const ops = _chunkUV2F4F4Rjs.getTreesDiffOperations.call(void 0, currentItems, new Map(items));
383
+ const result = apply(ops, false);
384
+ notify(result.updates);
385
+ }
386
+ function load(items) {
387
+ const [root, parentToChildren] = buildRootAndParentToChildren(items);
388
+ return _chunkUV2F4F4Rjs.LiveObject._deserialize(root, parentToChildren, pool);
389
+ }
390
+ function _addToRealUndoStack(historyOps) {
391
+ if (state.undoStack.length >= 50) {
392
+ state.undoStack.shift();
393
+ }
394
+ state.undoStack.push(historyOps);
395
+ onHistoryChange();
396
+ }
397
+ function addToUndoStack(historyOps) {
398
+ if (state.pausedHistory !== null) {
399
+ state.pausedHistory.unshift(...historyOps);
400
+ } else {
401
+ _addToRealUndoStack(historyOps);
402
+ }
403
+ }
404
+ function notify({
405
+ storageUpdates = /* @__PURE__ */ new Map(),
406
+ presence = false,
407
+ others: otherEvents = []
408
+ }) {
409
+ if (otherEvents.length > 0) {
410
+ const others = state.others.current;
411
+ for (const event of otherEvents) {
412
+ eventHub.others.notify({ others, event });
413
+ }
414
+ }
415
+ if (presence) {
416
+ eventHub.me.notify(state.me.current);
417
+ }
418
+ if (storageUpdates.size > 0) {
419
+ const updates = Array.from(storageUpdates.values());
420
+ eventHub.storage.notify(updates);
421
+ }
422
+ }
423
+ function getConnectionId() {
424
+ const conn = state.connection.current;
425
+ if (isConnectionSelfAware(conn)) {
426
+ return conn.id;
427
+ } else if (state.lastConnectionId !== null) {
428
+ return state.lastConnectionId;
429
+ }
430
+ throw new Error(
431
+ "Internal. Tried to get connection id but connection was never open"
432
+ );
433
+ }
434
+ function apply(ops, isLocal) {
435
+ const result = {
436
+ reverse: [],
437
+ updates: {
438
+ storageUpdates: /* @__PURE__ */ new Map(),
439
+ presence: false
440
+ }
441
+ };
442
+ const createdNodeIds = /* @__PURE__ */ new Set();
443
+ for (const op of ops) {
444
+ if (op.type === "presence") {
445
+ const reverse = {
446
+ type: "presence",
447
+ data: {}
1221
448
  };
1222
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1223
- try {
1224
- for(var _iterator = messages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1225
- var message = _step.value;
1226
- switch(message.type){
1227
- case 101 /* USER_JOINED */ :
1228
- {
1229
- var userJoinedUpdate = onUserJoinedMessage(message);
1230
- if (userJoinedUpdate) {
1231
- updates.others.push(userJoinedUpdate);
1232
- }
1233
- break;
1234
- }
1235
- case 100 /* UPDATE_PRESENCE */ :
1236
- {
1237
- var othersPresenceUpdate = onUpdatePresenceMessage(message);
1238
- if (othersPresenceUpdate) {
1239
- updates.others.push(othersPresenceUpdate);
1240
- }
1241
- break;
1242
- }
1243
- case 103 /* BROADCASTED_EVENT */ :
1244
- {
1245
- eventHub.customEvent.notify({
1246
- connectionId: message.actor,
1247
- event: message.event
1248
- });
1249
- break;
1250
- }
1251
- case 102 /* USER_LEFT */ :
1252
- {
1253
- var event2 = onUserLeftMessage(message);
1254
- if (event2) {
1255
- updates.others.push(event2);
1256
- }
1257
- break;
1258
- }
1259
- case 104 /* ROOM_STATE */ :
1260
- {
1261
- updates.others.push(onRoomStateMessage(message));
1262
- break;
1263
- }
1264
- case 200 /* INITIAL_STORAGE_STATE */ :
1265
- {
1266
- var offlineOps = new Map(state.offlineOperations);
1267
- createOrUpdateRootFromMessage(message);
1268
- applyAndSendOfflineOps(offlineOps);
1269
- _optionalChain([
1270
- _getInitialStateResolver,
1271
- "optionalCall",
1272
- function(_8) {
1273
- return _8();
1274
- }
1275
- ]);
1276
- eventHub.storageDidLoad.notify();
1277
- break;
1278
- }
1279
- case 201 /* UPDATE_STORAGE */ :
1280
- {
1281
- var applyResult = apply(message.ops, false);
1282
- applyResult.updates.storageUpdates.forEach(function(value, key) {
1283
- updates.storageUpdates.set(key, _chunkZR7CHFN6js.mergeStorageUpdates.call(void 0, updates.storageUpdates.get(key), value));
1284
- });
1285
- break;
1286
- }
1287
- }
1288
- }
1289
- } catch (err) {
1290
- _didIteratorError = true;
1291
- _iteratorError = err;
1292
- } finally{
1293
- try {
1294
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1295
- _iterator.return();
1296
- }
1297
- } finally{
1298
- if (_didIteratorError) {
1299
- throw _iteratorError;
1300
- }
1301
- }
449
+ for (const key in op.data) {
450
+ reverse.data[key] = state.me.current[key];
1302
451
  }
1303
- notify(updates);
1304
- };
1305
- var onClose = function onClose(event) {
1306
- state.socket = null;
1307
- clearTimeout(state.timeoutHandles.pongTimeout);
1308
- clearInterval(state.intervalHandles.heartbeat);
1309
- if (state.timeoutHandles.flush) {
1310
- clearTimeout(state.timeoutHandles.flush);
1311
- }
1312
- clearTimeout(state.timeoutHandles.reconnect);
1313
- state.others.clearOthers();
1314
- notify({
1315
- others: [
1316
- {
1317
- type: "reset"
1318
- }
1319
- ]
1320
- });
1321
- if (event.code >= 4e3 && event.code <= 4100) {
1322
- updateConnection({
1323
- state: "failed"
1324
- });
1325
- var error = new LiveblocksError(event.reason, event.code);
1326
- eventHub.error.notify(error);
1327
- var delay = getRetryDelay(true);
1328
- state.numberOfRetry++;
1329
- if (process.env.NODE_ENV !== "production") {
1330
- console.error("Connection to Liveblocks websocket server closed. Reason: ".concat(error.message, " (code: ").concat(error.code, "). Retrying in ").concat(delay, "ms."));
1331
- }
1332
- updateConnection({
1333
- state: "unavailable"
1334
- });
1335
- state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
1336
- } else if (event.code === 4999 /* CLOSE_WITHOUT_RETRY */ ) {
1337
- updateConnection({
1338
- state: "closed"
1339
- });
452
+ state.me.patch(op.data);
453
+ if (state.buffer.me === null) {
454
+ state.buffer.me = { type: "partial", data: op.data };
1340
455
  } else {
1341
- var delay1 = getRetryDelay();
1342
- state.numberOfRetry++;
1343
- if (process.env.NODE_ENV !== "production") {
1344
- console.warn("Connection to Liveblocks websocket server closed (code: ".concat(event.code, "). Retrying in ").concat(delay1, "ms."));
1345
- }
1346
- updateConnection({
1347
- state: "unavailable"
1348
- });
1349
- state.timeoutHandles.reconnect = effects.scheduleReconnect(delay1);
1350
- }
1351
- };
1352
- var updateConnection = function updateConnection(connection) {
1353
- state.connection.set(connection);
1354
- eventHub.connection.notify(connection.state);
1355
- };
1356
- var getRetryDelay = function getRetryDelay() {
1357
- var slow = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
1358
- if (slow) {
1359
- return BACKOFF_RETRY_DELAYS_SLOW[state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS_SLOW.length - 1];
1360
- }
1361
- return BACKOFF_RETRY_DELAYS[state.numberOfRetry < BACKOFF_RETRY_DELAYS.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS.length - 1];
1362
- };
1363
- var onError = function onError() {};
1364
- var onOpen = function onOpen() {
1365
- clearInterval(state.intervalHandles.heartbeat);
1366
- state.intervalHandles.heartbeat = effects.startHeartbeatInterval();
1367
- if (state.connection.current.state === "connecting") {
1368
- updateConnection(_objectSpreadProps(_objectSpread({}, state.connection.current), {
1369
- state: "open"
1370
- }));
1371
- state.numberOfRetry = 0;
1372
- if (state.lastConnectionId !== void 0) {
1373
- state.buffer.me = {
1374
- type: "full",
1375
- data: state.me.current
1376
- };
1377
- tryFlushing();
1378
- }
1379
- state.lastConnectionId = state.connection.current.id;
1380
- if (state.root) {
1381
- state.buffer.messages.push({
1382
- type: 200 /* FETCH_STORAGE */
1383
- });
1384
- }
1385
- tryFlushing();
1386
- } else {}
1387
- };
1388
- var heartbeat = function heartbeat() {
1389
- if (state.socket == null) {
1390
- return;
1391
- }
1392
- clearTimeout(state.timeoutHandles.pongTimeout);
1393
- state.timeoutHandles.pongTimeout = effects.schedulePongTimeout();
1394
- if (state.socket.readyState === state.socket.OPEN) {
1395
- state.socket.send("ping");
1396
- }
1397
- };
1398
- var pongTimeout = function pongTimeout() {
1399
- log("Pong timeout. Trying to reconnect.");
1400
- reconnect();
1401
- };
1402
- var reconnect = function reconnect() {
1403
- if (state.socket) {
1404
- state.socket.removeEventListener("open", onOpen);
1405
- state.socket.removeEventListener("message", onMessage);
1406
- state.socket.removeEventListener("close", onClose);
1407
- state.socket.removeEventListener("error", onError);
1408
- state.socket.close();
1409
- state.socket = null;
1410
- }
1411
- updateConnection({
1412
- state: "unavailable"
1413
- });
1414
- clearTimeout(state.timeoutHandles.pongTimeout);
1415
- if (state.timeoutHandles.flush) {
1416
- clearTimeout(state.timeoutHandles.flush);
1417
- }
1418
- clearTimeout(state.timeoutHandles.reconnect);
1419
- clearInterval(state.intervalHandles.heartbeat);
1420
- connect();
1421
- };
1422
- var applyAndSendOfflineOps = function applyAndSendOfflineOps(offlineOps) {
1423
- if (offlineOps.size === 0) {
1424
- return;
1425
- }
1426
- var messages = [];
1427
- var ops = Array.from(offlineOps.values());
1428
- var result = apply(ops, true);
1429
- messages.push({
1430
- type: 201 /* UPDATE_STORAGE */ ,
1431
- ops: ops
1432
- });
1433
- notify(result.updates);
1434
- effects.send(messages);
1435
- };
1436
- var tryFlushing = function tryFlushing() {
1437
- var storageOps = state.buffer.storageOperations;
1438
- if (storageOps.length > 0) {
1439
- storageOps.forEach(function(op) {
1440
- state.offlineOperations.set(_chunkZR7CHFN6js.nn.call(void 0, op.opId), op);
1441
- });
1442
- }
1443
- if (state.socket == null || state.socket.readyState !== state.socket.OPEN) {
1444
- state.buffer.storageOperations = [];
1445
- return;
1446
- }
1447
- var now = Date.now();
1448
- var elapsedTime = now - state.lastFlushTime;
1449
- if (elapsedTime > config.throttleDelay) {
1450
- var messages = flushDataToMessages(state);
1451
- if (messages.length === 0) {
1452
- return;
1453
- }
1454
- effects.send(messages);
1455
- state.buffer = {
1456
- messages: [],
1457
- storageOperations: [],
1458
- me: null
1459
- };
1460
- state.lastFlushTime = now;
456
+ for (const key in op.data) {
457
+ state.buffer.me.data[key] = op.data[key];
458
+ }
459
+ }
460
+ result.reverse.unshift(reverse);
461
+ result.updates.presence = true;
462
+ } else {
463
+ let source;
464
+ if (!op.opId) {
465
+ op.opId = pool.generateOpId();
466
+ }
467
+ if (isLocal) {
468
+ source = 0 /* UNDOREDO_RECONNECT */;
1461
469
  } else {
1462
- if (state.timeoutHandles.flush != null) {
1463
- clearTimeout(state.timeoutHandles.flush);
1464
- }
1465
- state.timeoutHandles.flush = effects.delayFlush(config.throttleDelay - (now - state.lastFlushTime));
1466
- }
1467
- };
1468
- var flushDataToMessages = function flushDataToMessages(state2) {
1469
- var messages = [];
1470
- if (state2.buffer.me) {
1471
- messages.push(state2.buffer.me.type === "full" ? {
1472
- type: 100 /* UPDATE_PRESENCE */ ,
1473
- targetActor: -1,
1474
- data: state2.buffer.me.data
1475
- } : {
1476
- type: 100 /* UPDATE_PRESENCE */ ,
1477
- data: state2.buffer.me.data
1478
- });
1479
- }
1480
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1481
- try {
1482
- for(var _iterator = state2.buffer.messages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1483
- var event = _step.value;
1484
- messages.push(event);
1485
- }
1486
- } catch (err) {
1487
- _didIteratorError = true;
1488
- _iteratorError = err;
1489
- } finally{
1490
- try {
1491
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1492
- _iterator.return();
1493
- }
1494
- } finally{
1495
- if (_didIteratorError) {
1496
- throw _iteratorError;
1497
- }
1498
- }
1499
- }
1500
- if (state2.buffer.storageOperations.length > 0) {
1501
- messages.push({
1502
- type: 201 /* UPDATE_STORAGE */ ,
1503
- ops: state2.buffer.storageOperations
1504
- });
1505
- }
1506
- return messages;
1507
- };
1508
- var disconnect = function disconnect() {
1509
- if (state.socket) {
1510
- state.socket.removeEventListener("open", onOpen);
1511
- state.socket.removeEventListener("message", onMessage);
1512
- state.socket.removeEventListener("close", onClose);
1513
- state.socket.removeEventListener("error", onError);
1514
- state.socket.close();
1515
- state.socket = null;
1516
- }
1517
- updateConnection({
1518
- state: "closed"
1519
- });
1520
- if (state.timeoutHandles.flush) {
1521
- clearTimeout(state.timeoutHandles.flush);
1522
- }
1523
- clearTimeout(state.timeoutHandles.reconnect);
1524
- clearTimeout(state.timeoutHandles.pongTimeout);
1525
- clearInterval(state.intervalHandles.heartbeat);
1526
- state.others.clearOthers();
1527
- notify({
1528
- others: [
1529
- {
1530
- type: "reset"
1531
- }
1532
- ]
1533
- });
1534
- Object.values(eventHub).forEach(function(eventSource) {
1535
- return eventSource.clear();
470
+ const deleted = state.offlineOperations.delete(_chunkUV2F4F4Rjs.nn.call(void 0, op.opId));
471
+ source = deleted ? 2 /* ACK */ : 1 /* REMOTE */;
472
+ }
473
+ const applyOpResult = applyOp(op, source);
474
+ if (applyOpResult.modified) {
475
+ const parentId = applyOpResult.modified.node.parent.type === "HasParent" ? _chunkUV2F4F4Rjs.nn.call(void 0,
476
+ applyOpResult.modified.node.parent.node._id,
477
+ "Expected parent node to have an ID"
478
+ ) : void 0;
479
+ if (!parentId || !createdNodeIds.has(parentId)) {
480
+ result.updates.storageUpdates.set(
481
+ _chunkUV2F4F4Rjs.nn.call(void 0, applyOpResult.modified.node._id),
482
+ _chunkUV2F4F4Rjs.mergeStorageUpdates.call(void 0,
483
+ result.updates.storageUpdates.get(
484
+ _chunkUV2F4F4Rjs.nn.call(void 0, applyOpResult.modified.node._id)
485
+ ),
486
+ applyOpResult.modified
487
+ )
488
+ );
489
+ result.reverse.unshift(...applyOpResult.reverse);
490
+ }
491
+ if (op.type === 2 /* CREATE_LIST */ || op.type === 7 /* CREATE_MAP */ || op.type === 4 /* CREATE_OBJECT */) {
492
+ createdNodeIds.add(_chunkUV2F4F4Rjs.nn.call(void 0, applyOpResult.modified.node._id));
493
+ }
494
+ }
495
+ }
496
+ }
497
+ return result;
498
+ }
499
+ function applyOp(op, source) {
500
+ switch (op.type) {
501
+ case 6 /* DELETE_OBJECT_KEY */:
502
+ case 3 /* UPDATE_OBJECT */:
503
+ case 5 /* DELETE_CRDT */: {
504
+ const node = state.nodes.get(op.id);
505
+ if (node === void 0) {
506
+ return { modified: false };
507
+ }
508
+ return node._apply(op, source === 0 /* UNDOREDO_RECONNECT */);
509
+ }
510
+ case 1 /* SET_PARENT_KEY */: {
511
+ const node = state.nodes.get(op.id);
512
+ if (node === void 0) {
513
+ return { modified: false };
514
+ }
515
+ if (node.parent.type === "HasParent" && _chunkUV2F4F4Rjs.isLiveList.call(void 0, node.parent.node)) {
516
+ return node.parent.node._setChildKey(op.parentKey, node, source);
517
+ }
518
+ return { modified: false };
519
+ }
520
+ case 4 /* CREATE_OBJECT */:
521
+ case 2 /* CREATE_LIST */:
522
+ case 7 /* CREATE_MAP */:
523
+ case 8 /* CREATE_REGISTER */: {
524
+ if (op.parentId === void 0) {
525
+ return { modified: false };
526
+ }
527
+ const parentNode = state.nodes.get(op.parentId);
528
+ if (parentNode === void 0) {
529
+ return { modified: false };
530
+ }
531
+ return parentNode._attachChild(op, source);
532
+ }
533
+ }
534
+ }
535
+ function subscribeToLiveStructureDeeply(node, callback) {
536
+ return eventHub.storage.subscribe((updates) => {
537
+ const relatedUpdates = updates.filter(
538
+ (update) => _chunkUV2F4F4Rjs.isSameNodeOrChildOf.call(void 0, update.node, node)
539
+ );
540
+ if (relatedUpdates.length > 0) {
541
+ callback(relatedUpdates);
542
+ }
543
+ });
544
+ }
545
+ function subscribeToLiveStructureShallowly(node, callback) {
546
+ return eventHub.storage.subscribe((updates) => {
547
+ for (const update of updates) {
548
+ if (update.node._id === node._id) {
549
+ callback(update.node);
550
+ }
551
+ }
552
+ });
553
+ }
554
+ function subscribe(first, second, options) {
555
+ if (typeof first === "string" && _chunkUV2F4F4Rjs.isRoomEventName.call(void 0, first)) {
556
+ if (typeof second !== "function") {
557
+ throw new Error("Second argument must be a callback function");
558
+ }
559
+ const callback = second;
560
+ switch (first) {
561
+ case "event":
562
+ return eventHub.customEvent.subscribe(
563
+ callback
564
+ );
565
+ case "my-presence":
566
+ return eventHub.me.subscribe(callback);
567
+ case "others": {
568
+ const cb = callback;
569
+ return eventHub.others.subscribe(
570
+ ({ others, event }) => cb(others, event)
571
+ );
572
+ }
573
+ case "error":
574
+ return eventHub.error.subscribe(callback);
575
+ case "connection":
576
+ return eventHub.connection.subscribe(
577
+ callback
578
+ );
579
+ case "storage":
580
+ return eventHub.storage.subscribe(
581
+ callback
582
+ );
583
+ case "history":
584
+ return eventHub.history.subscribe(callback);
585
+ default:
586
+ return _chunkUV2F4F4Rjs.assertNever.call(void 0, first, "Unknown event");
587
+ }
588
+ }
589
+ if (second === void 0 || typeof first === "function") {
590
+ if (typeof first === "function") {
591
+ const storageCallback = first;
592
+ return eventHub.storage.subscribe(storageCallback);
593
+ } else {
594
+ throw new Error("Please specify a listener callback");
595
+ }
596
+ }
597
+ if (_chunkUV2F4F4Rjs.isLiveNode.call(void 0, first)) {
598
+ const node = first;
599
+ if (options == null ? void 0 : options.isDeep) {
600
+ const storageCallback = second;
601
+ return subscribeToLiveStructureDeeply(node, storageCallback);
602
+ } else {
603
+ const nodeCallback = second;
604
+ return subscribeToLiveStructureShallowly(node, nodeCallback);
605
+ }
606
+ }
607
+ throw new Error(`"${first}" is not a valid event name`);
608
+ }
609
+ function getConnectionState() {
610
+ return state.connection.current.state;
611
+ }
612
+ function connect() {
613
+ var _a, _b, _c, _d;
614
+ if (state.connection.current.state !== "closed" && state.connection.current.state !== "unavailable") {
615
+ return null;
616
+ }
617
+ const auth = prepareAuthEndpoint(
618
+ config.authentication,
619
+ (_b = (_a = config.polyfills) == null ? void 0 : _a.fetch) != null ? _b : config.fetchPolyfill
620
+ );
621
+ const createWebSocket = prepareCreateWebSocket(
622
+ config.liveblocksServer,
623
+ (_d = (_c = config.polyfills) == null ? void 0 : _c.WebSocket) != null ? _d : config.WebSocketPolyfill
624
+ );
625
+ updateConnection({ state: "authenticating" });
626
+ effects.authenticate(auth, createWebSocket);
627
+ }
628
+ function updatePresence(patch, options) {
629
+ const oldValues = {};
630
+ if (state.buffer.me === null) {
631
+ state.buffer.me = {
632
+ type: "partial",
633
+ data: {}
634
+ };
635
+ }
636
+ for (const key in patch) {
637
+ const overrideValue = patch[key];
638
+ if (overrideValue === void 0) {
639
+ continue;
640
+ }
641
+ state.buffer.me.data[key] = overrideValue;
642
+ oldValues[key] = state.me.current[key];
643
+ }
644
+ state.me.patch(patch);
645
+ if (state.activeBatch) {
646
+ if (options == null ? void 0 : options.addToHistory) {
647
+ state.activeBatch.reverseOps.push({
648
+ type: "presence",
649
+ data: oldValues
1536
650
  });
1537
- };
1538
- var getPresence = function getPresence() {
1539
- return state.me.current;
1540
- };
1541
- var getOthers = function getOthers() {
1542
- return state.others.current;
1543
- };
1544
- var broadcastEvent = function broadcastEvent(event) {
1545
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
1546
- shouldQueueEventIfNotReady: false
651
+ }
652
+ state.activeBatch.updates.presence = true;
653
+ } else {
654
+ tryFlushing();
655
+ if (options == null ? void 0 : options.addToHistory) {
656
+ addToUndoStack([{ type: "presence", data: oldValues }]);
657
+ }
658
+ notify({ presence: true });
659
+ }
660
+ }
661
+ function authenticationSuccess(token, socket) {
662
+ socket.addEventListener("message", onMessage);
663
+ socket.addEventListener("open", onOpen);
664
+ socket.addEventListener("close", onClose);
665
+ socket.addEventListener("error", onError);
666
+ updateConnection({
667
+ state: "connecting",
668
+ id: token.actor,
669
+ userInfo: token.info,
670
+ userId: token.id
671
+ });
672
+ state.idFactory = makeIdFactory(token.actor);
673
+ state.socket = socket;
674
+ }
675
+ function authenticationFailure(error) {
676
+ if (process.env.NODE_ENV !== "production") {
677
+ console.error("Call to authentication endpoint failed", error);
678
+ }
679
+ state.token = null;
680
+ updateConnection({ state: "unavailable" });
681
+ state.numberOfRetry++;
682
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(getRetryDelay());
683
+ }
684
+ function onVisibilityChange(visibilityState) {
685
+ if (visibilityState === "visible" && state.connection.current.state === "open") {
686
+ log("Heartbeat after visibility change");
687
+ heartbeat();
688
+ }
689
+ }
690
+ function onUpdatePresenceMessage(message) {
691
+ if (message.targetActor !== void 0) {
692
+ const oldUser = state.others.getUser(message.actor);
693
+ state.others.setOther(message.actor, message.data);
694
+ const newUser = state.others.getUser(message.actor);
695
+ if (oldUser === void 0 && newUser !== void 0) {
696
+ return { type: "enter", user: newUser };
697
+ }
698
+ } else {
699
+ state.others.patchOther(message.actor, message.data), message;
700
+ }
701
+ const user = state.others.getUser(message.actor);
702
+ if (user) {
703
+ return {
704
+ type: "update",
705
+ updates: message.data,
706
+ user
707
+ };
708
+ } else {
709
+ return void 0;
710
+ }
711
+ }
712
+ function onUserLeftMessage(message) {
713
+ const user = state.others.getUser(message.actor);
714
+ if (user) {
715
+ state.others.removeConnection(message.actor);
716
+ return { type: "leave", user };
717
+ }
718
+ return null;
719
+ }
720
+ function onRoomStateMessage(message) {
721
+ for (const key in message.users) {
722
+ const user = message.users[key];
723
+ const connectionId = Number(key);
724
+ state.others.setConnection(connectionId, user.id, user.info);
725
+ }
726
+ return { type: "reset" };
727
+ }
728
+ function onNavigatorOnline() {
729
+ if (state.connection.current.state === "unavailable") {
730
+ log("Try to reconnect after connectivity change");
731
+ reconnect();
732
+ }
733
+ }
734
+ function onHistoryChange() {
735
+ eventHub.history.notify({ canUndo: canUndo(), canRedo: canRedo() });
736
+ }
737
+ function onUserJoinedMessage(message) {
738
+ state.others.setConnection(message.actor, message.id, message.info);
739
+ state.buffer.messages.push({
740
+ type: 100 /* UPDATE_PRESENCE */,
741
+ data: state.me.current,
742
+ targetActor: message.actor
743
+ });
744
+ tryFlushing();
745
+ const user = state.others.getUser(message.actor);
746
+ return user ? { type: "enter", user } : void 0;
747
+ }
748
+ function parseServerMessage(data) {
749
+ if (!_chunkUV2F4F4Rjs.isJsonObject.call(void 0, data)) {
750
+ return null;
751
+ }
752
+ return data;
753
+ }
754
+ function parseServerMessages(text) {
755
+ const data = _chunkUV2F4F4Rjs.tryParseJson.call(void 0, text);
756
+ if (data === void 0) {
757
+ return null;
758
+ } else if (_chunkUV2F4F4Rjs.isJsonArray.call(void 0, data)) {
759
+ return _chunkUV2F4F4Rjs.compact.call(void 0, data.map((item) => parseServerMessage(item)));
760
+ } else {
761
+ return _chunkUV2F4F4Rjs.compact.call(void 0, [parseServerMessage(data)]);
762
+ }
763
+ }
764
+ function onMessage(event) {
765
+ if (event.data === "pong") {
766
+ clearTimeout(state.timeoutHandles.pongTimeout);
767
+ return;
768
+ }
769
+ const messages = parseServerMessages(event.data);
770
+ if (messages === null || messages.length === 0) {
771
+ return;
772
+ }
773
+ const updates = {
774
+ storageUpdates: /* @__PURE__ */ new Map(),
775
+ others: []
776
+ };
777
+ for (const message of messages) {
778
+ switch (message.type) {
779
+ case 101 /* USER_JOINED */: {
780
+ const userJoinedUpdate = onUserJoinedMessage(message);
781
+ if (userJoinedUpdate) {
782
+ updates.others.push(userJoinedUpdate);
783
+ }
784
+ break;
785
+ }
786
+ case 100 /* UPDATE_PRESENCE */: {
787
+ const othersPresenceUpdate = onUpdatePresenceMessage(message);
788
+ if (othersPresenceUpdate) {
789
+ updates.others.push(othersPresenceUpdate);
790
+ }
791
+ break;
792
+ }
793
+ case 103 /* BROADCASTED_EVENT */: {
794
+ eventHub.customEvent.notify({
795
+ connectionId: message.actor,
796
+ event: message.event
797
+ });
798
+ break;
799
+ }
800
+ case 102 /* USER_LEFT */: {
801
+ const event2 = onUserLeftMessage(message);
802
+ if (event2) {
803
+ updates.others.push(event2);
804
+ }
805
+ break;
806
+ }
807
+ case 104 /* ROOM_STATE */: {
808
+ updates.others.push(onRoomStateMessage(message));
809
+ break;
810
+ }
811
+ case 200 /* INITIAL_STORAGE_STATE */: {
812
+ const offlineOps = new Map(state.offlineOperations);
813
+ createOrUpdateRootFromMessage(message);
814
+ applyAndSendOfflineOps(offlineOps);
815
+ _getInitialStateResolver == null ? void 0 : _getInitialStateResolver();
816
+ eventHub.storageDidLoad.notify();
817
+ break;
818
+ }
819
+ case 201 /* UPDATE_STORAGE */: {
820
+ const applyResult = apply(message.ops, false);
821
+ applyResult.updates.storageUpdates.forEach((value, key) => {
822
+ updates.storageUpdates.set(
823
+ key,
824
+ _chunkUV2F4F4Rjs.mergeStorageUpdates.call(void 0,
825
+ updates.storageUpdates.get(key),
826
+ value
827
+ )
828
+ );
829
+ });
830
+ break;
831
+ }
832
+ }
833
+ }
834
+ notify(updates);
835
+ }
836
+ function onClose(event) {
837
+ state.socket = null;
838
+ clearTimeout(state.timeoutHandles.pongTimeout);
839
+ clearInterval(state.intervalHandles.heartbeat);
840
+ if (state.timeoutHandles.flush) {
841
+ clearTimeout(state.timeoutHandles.flush);
842
+ }
843
+ clearTimeout(state.timeoutHandles.reconnect);
844
+ state.others.clearOthers();
845
+ notify({ others: [{ type: "reset" }] });
846
+ if (event.code >= 4e3 && event.code <= 4100) {
847
+ updateConnection({ state: "failed" });
848
+ const error = new LiveblocksError(event.reason, event.code);
849
+ eventHub.error.notify(error);
850
+ const delay = getRetryDelay(true);
851
+ state.numberOfRetry++;
852
+ if (process.env.NODE_ENV !== "production") {
853
+ console.error(
854
+ `Connection to Liveblocks websocket server closed. Reason: ${error.message} (code: ${error.code}). Retrying in ${delay}ms.`
855
+ );
856
+ }
857
+ updateConnection({ state: "unavailable" });
858
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
859
+ } else if (event.code === 4999 /* CLOSE_WITHOUT_RETRY */) {
860
+ updateConnection({ state: "closed" });
861
+ } else {
862
+ const delay = getRetryDelay();
863
+ state.numberOfRetry++;
864
+ if (process.env.NODE_ENV !== "production") {
865
+ console.warn(
866
+ `Connection to Liveblocks websocket server closed (code: ${event.code}). Retrying in ${delay}ms.`
867
+ );
868
+ }
869
+ updateConnection({ state: "unavailable" });
870
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
871
+ }
872
+ }
873
+ function updateConnection(connection) {
874
+ state.connection.set(connection);
875
+ eventHub.connection.notify(connection.state);
876
+ }
877
+ function getRetryDelay(slow = false) {
878
+ if (slow) {
879
+ return BACKOFF_RETRY_DELAYS_SLOW[state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS_SLOW.length - 1];
880
+ }
881
+ return BACKOFF_RETRY_DELAYS[state.numberOfRetry < BACKOFF_RETRY_DELAYS.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS.length - 1];
882
+ }
883
+ function onError() {
884
+ }
885
+ function onOpen() {
886
+ clearInterval(state.intervalHandles.heartbeat);
887
+ state.intervalHandles.heartbeat = effects.startHeartbeatInterval();
888
+ if (state.connection.current.state === "connecting") {
889
+ updateConnection(_chunkUV2F4F4Rjs.__spreadProps.call(void 0, _chunkUV2F4F4Rjs.__spreadValues.call(void 0, {}, state.connection.current), { state: "open" }));
890
+ state.numberOfRetry = 0;
891
+ if (state.lastConnectionId !== void 0) {
892
+ state.buffer.me = {
893
+ type: "full",
894
+ data: state.me.current
1547
895
  };
1548
- if (state.socket == null && options.shouldQueueEventIfNotReady == false) {
1549
- return;
1550
- }
1551
- state.buffer.messages.push({
1552
- type: 103 /* BROADCAST_EVENT */ ,
1553
- event: event
1554
- });
1555
896
  tryFlushing();
1556
- };
1557
- var dispatchOps = function dispatchOps(ops) {
1558
- var _storageOperations;
1559
- (_storageOperations = state.buffer.storageOperations).push.apply(_storageOperations, _toConsumableArray(ops));
1560
- tryFlushing();
1561
- };
1562
- var startLoadingStorage = function startLoadingStorage() {
1563
- if (_getInitialStatePromise == null) {
1564
- state.buffer.messages.push({
1565
- type: 200 /* FETCH_STORAGE */
1566
- });
1567
- tryFlushing();
1568
- _getInitialStatePromise = new Promise(function(resolve) {
1569
- return _getInitialStateResolver = resolve;
1570
- });
1571
- }
1572
- return _getInitialStatePromise;
1573
- };
1574
- var getStorageSnapshot = function getStorageSnapshot() {
1575
- var root = state.root;
1576
- if (root !== void 0) {
1577
- return root;
1578
- } else {
1579
- startLoadingStorage();
1580
- return null;
1581
- }
1582
- };
1583
- var getStorage = function getStorage() {
1584
- if (state.root) {
1585
- return Promise.resolve({
1586
- root: state.root
1587
- });
1588
- }
1589
- return startLoadingStorage().then(function() {
1590
- return {
1591
- root: _chunkZR7CHFN6js.nn.call(void 0, state.root)
1592
- };
897
+ }
898
+ state.lastConnectionId = state.connection.current.id;
899
+ if (state.root) {
900
+ state.buffer.messages.push({ type: 200 /* FETCH_STORAGE */ });
901
+ }
902
+ tryFlushing();
903
+ } else {
904
+ }
905
+ }
906
+ function heartbeat() {
907
+ if (state.socket === null) {
908
+ return;
909
+ }
910
+ clearTimeout(state.timeoutHandles.pongTimeout);
911
+ state.timeoutHandles.pongTimeout = effects.schedulePongTimeout();
912
+ if (state.socket.readyState === state.socket.OPEN) {
913
+ state.socket.send("ping");
914
+ }
915
+ }
916
+ function pongTimeout() {
917
+ log("Pong timeout. Trying to reconnect.");
918
+ reconnect();
919
+ }
920
+ function reconnect() {
921
+ if (state.socket) {
922
+ state.socket.removeEventListener("open", onOpen);
923
+ state.socket.removeEventListener("message", onMessage);
924
+ state.socket.removeEventListener("close", onClose);
925
+ state.socket.removeEventListener("error", onError);
926
+ state.socket.close();
927
+ state.socket = null;
928
+ }
929
+ updateConnection({ state: "unavailable" });
930
+ clearTimeout(state.timeoutHandles.pongTimeout);
931
+ if (state.timeoutHandles.flush) {
932
+ clearTimeout(state.timeoutHandles.flush);
933
+ }
934
+ clearTimeout(state.timeoutHandles.reconnect);
935
+ clearInterval(state.intervalHandles.heartbeat);
936
+ connect();
937
+ }
938
+ function applyAndSendOfflineOps(offlineOps) {
939
+ if (offlineOps.size === 0) {
940
+ return;
941
+ }
942
+ const messages = [];
943
+ const ops = Array.from(offlineOps.values());
944
+ const result = apply(ops, true);
945
+ messages.push({
946
+ type: 201 /* UPDATE_STORAGE */,
947
+ ops
948
+ });
949
+ notify(result.updates);
950
+ effects.send(messages);
951
+ }
952
+ function tryFlushing() {
953
+ const storageOps = state.buffer.storageOperations;
954
+ if (storageOps.length > 0) {
955
+ storageOps.forEach((op) => {
956
+ state.offlineOperations.set(_chunkUV2F4F4Rjs.nn.call(void 0, op.opId), op);
957
+ });
958
+ }
959
+ if (state.socket === null || state.socket.readyState !== state.socket.OPEN) {
960
+ state.buffer.storageOperations = [];
961
+ return;
962
+ }
963
+ const now = Date.now();
964
+ const elapsedTime = now - state.lastFlushTime;
965
+ if (elapsedTime > config.throttleDelay) {
966
+ const messages = flushDataToMessages(state);
967
+ if (messages.length === 0) {
968
+ return;
969
+ }
970
+ effects.send(messages);
971
+ state.buffer = {
972
+ messages: [],
973
+ storageOperations: [],
974
+ me: null
975
+ };
976
+ state.lastFlushTime = now;
977
+ } else {
978
+ if (state.timeoutHandles.flush !== null) {
979
+ clearTimeout(state.timeoutHandles.flush);
980
+ }
981
+ state.timeoutHandles.flush = effects.delayFlush(
982
+ config.throttleDelay - (now - state.lastFlushTime)
983
+ );
984
+ }
985
+ }
986
+ function flushDataToMessages(state2) {
987
+ const messages = [];
988
+ if (state2.buffer.me) {
989
+ messages.push(
990
+ state2.buffer.me.type === "full" ? {
991
+ type: 100 /* UPDATE_PRESENCE */,
992
+ targetActor: -1,
993
+ data: state2.buffer.me.data
994
+ } : {
995
+ type: 100 /* UPDATE_PRESENCE */,
996
+ data: state2.buffer.me.data
997
+ }
998
+ );
999
+ }
1000
+ for (const event of state2.buffer.messages) {
1001
+ messages.push(event);
1002
+ }
1003
+ if (state2.buffer.storageOperations.length > 0) {
1004
+ messages.push({
1005
+ type: 201 /* UPDATE_STORAGE */,
1006
+ ops: state2.buffer.storageOperations
1007
+ });
1008
+ }
1009
+ return messages;
1010
+ }
1011
+ function disconnect() {
1012
+ if (state.socket) {
1013
+ state.socket.removeEventListener("open", onOpen);
1014
+ state.socket.removeEventListener("message", onMessage);
1015
+ state.socket.removeEventListener("close", onClose);
1016
+ state.socket.removeEventListener("error", onError);
1017
+ state.socket.close();
1018
+ state.socket = null;
1019
+ }
1020
+ updateConnection({ state: "closed" });
1021
+ if (state.timeoutHandles.flush) {
1022
+ clearTimeout(state.timeoutHandles.flush);
1023
+ }
1024
+ clearTimeout(state.timeoutHandles.reconnect);
1025
+ clearTimeout(state.timeoutHandles.pongTimeout);
1026
+ clearInterval(state.intervalHandles.heartbeat);
1027
+ state.others.clearOthers();
1028
+ notify({ others: [{ type: "reset" }] });
1029
+ Object.values(eventHub).forEach((eventSource) => eventSource.clear());
1030
+ }
1031
+ function getPresence() {
1032
+ return state.me.current;
1033
+ }
1034
+ function getOthers() {
1035
+ return state.others.current;
1036
+ }
1037
+ function broadcastEvent(event, options = {
1038
+ shouldQueueEventIfNotReady: false
1039
+ }) {
1040
+ if (state.socket === null && !options.shouldQueueEventIfNotReady) {
1041
+ return;
1042
+ }
1043
+ state.buffer.messages.push({
1044
+ type: 103 /* BROADCAST_EVENT */,
1045
+ event
1046
+ });
1047
+ tryFlushing();
1048
+ }
1049
+ function dispatchOps(ops) {
1050
+ state.buffer.storageOperations.push(...ops);
1051
+ tryFlushing();
1052
+ }
1053
+ let _getInitialStatePromise = null;
1054
+ let _getInitialStateResolver = null;
1055
+ function startLoadingStorage() {
1056
+ if (_getInitialStatePromise === null) {
1057
+ state.buffer.messages.push({ type: 200 /* FETCH_STORAGE */ });
1058
+ tryFlushing();
1059
+ _getInitialStatePromise = new Promise(
1060
+ (resolve) => _getInitialStateResolver = resolve
1061
+ );
1062
+ }
1063
+ return _getInitialStatePromise;
1064
+ }
1065
+ function getStorageSnapshot() {
1066
+ const root = state.root;
1067
+ if (root !== void 0) {
1068
+ return root;
1069
+ } else {
1070
+ startLoadingStorage();
1071
+ return null;
1072
+ }
1073
+ }
1074
+ function getStorage() {
1075
+ return _chunkUV2F4F4Rjs.__async.call(void 0, this, null, function* () {
1076
+ if (state.root) {
1077
+ return Promise.resolve({
1078
+ root: state.root
1593
1079
  });
1594
- };
1595
- var undo = function undo() {
1596
- if (state.isBatching) {
1597
- throw new Error("undo is not allowed during a batch");
1598
- }
1599
- var historyItem = state.undoStack.pop();
1600
- if (historyItem == null) {
1601
- return;
1602
- }
1603
- state.isHistoryPaused = false;
1604
- var result = apply(historyItem, true);
1605
- notify(result.updates);
1606
- state.redoStack.push(result.reverse);
1607
- onHistoryChange();
1608
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1609
- try {
1610
- for(var _iterator = historyItem[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1611
- var op = _step.value;
1612
- if (op.type !== "presence") {
1613
- state.buffer.storageOperations.push(op);
1614
- }
1615
- }
1616
- } catch (err) {
1617
- _didIteratorError = true;
1618
- _iteratorError = err;
1619
- } finally{
1620
- try {
1621
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1622
- _iterator.return();
1623
- }
1624
- } finally{
1625
- if (_didIteratorError) {
1626
- throw _iteratorError;
1627
- }
1628
- }
1629
- }
1630
- tryFlushing();
1631
- };
1632
- var canUndo = function canUndo() {
1633
- return state.undoStack.length > 0;
1634
- };
1635
- var redo = function redo() {
1636
- if (state.isBatching) {
1637
- throw new Error("redo is not allowed during a batch");
1638
- }
1639
- var historyItem = state.redoStack.pop();
1640
- if (historyItem == null) {
1641
- return;
1642
- }
1643
- state.isHistoryPaused = false;
1644
- var result = apply(historyItem, true);
1645
- notify(result.updates);
1646
- state.undoStack.push(result.reverse);
1647
- onHistoryChange();
1648
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1649
- try {
1650
- for(var _iterator = historyItem[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1651
- var op = _step.value;
1652
- if (op.type !== "presence") {
1653
- state.buffer.storageOperations.push(op);
1654
- }
1655
- }
1656
- } catch (err) {
1657
- _didIteratorError = true;
1658
- _iteratorError = err;
1659
- } finally{
1660
- try {
1661
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1662
- _iterator.return();
1663
- }
1664
- } finally{
1665
- if (_didIteratorError) {
1666
- throw _iteratorError;
1667
- }
1668
- }
1669
- }
1670
- tryFlushing();
1671
- };
1672
- var canRedo = function canRedo() {
1673
- return state.redoStack.length > 0;
1674
- };
1675
- var batch = function batch(callback) {
1676
- if (state.isBatching) {
1677
- throw new Error("batch should not be called during a batch");
1678
- }
1679
- state.isBatching = true;
1680
- try {
1681
- callback();
1682
- } finally{
1683
- state.isBatching = false;
1684
- if (state.batch.reverseOps.length > 0) {
1685
- addToUndoStack(state.batch.reverseOps);
1686
- }
1687
- if (state.batch.ops.length > 0) {
1688
- state.redoStack = [];
1689
- }
1690
- if (state.batch.ops.length > 0) {
1691
- dispatchOps(state.batch.ops);
1692
- }
1693
- notify(state.batch.updates);
1694
- state.batch = {
1695
- ops: [],
1696
- reverseOps: [],
1697
- updates: {
1698
- others: [],
1699
- storageUpdates: /* @__PURE__ */ new Map(),
1700
- presence: false
1701
- }
1702
- };
1703
- tryFlushing();
1704
- }
1705
- };
1706
- var pauseHistory = function pauseHistory() {
1707
- state.pausedHistory = [];
1708
- state.isHistoryPaused = true;
1709
- };
1710
- var resumeHistory = function resumeHistory() {
1711
- state.isHistoryPaused = false;
1712
- if (state.pausedHistory.length > 0) {
1713
- addToUndoStack(state.pausedHistory);
1714
- }
1715
- state.pausedHistory = [];
1716
- };
1717
- var simulateSocketClose = function simulateSocketClose() {
1718
- if (state.socket) {
1719
- state.socket = null;
1720
- }
1721
- };
1722
- var simulateSendCloseEvent = function simulateSendCloseEvent(event) {
1723
- onClose(event);
1724
- };
1725
- var pool = {
1726
- roomId: config.roomId,
1727
- getNode: function(id) {
1728
- return state.nodes.get(id);
1729
- },
1730
- addNode: function(id, node) {
1731
- return void state.nodes.set(id, node);
1732
- },
1733
- deleteNode: function(id) {
1734
- return void state.nodes.delete(id);
1735
- },
1736
- generateId: function() {
1737
- return "".concat(getConnectionId(), ":").concat(state.clock++);
1738
- },
1739
- generateOpId: function() {
1740
- return "".concat(getConnectionId(), ":").concat(state.opClock++);
1741
- },
1742
- dispatch: function dispatch(ops, reverse, storageUpdates) {
1743
- if (state.isBatching) {
1744
- var _ops, _reverseOps;
1745
- (_ops = state.batch.ops).push.apply(_ops, _toConsumableArray(ops));
1746
- storageUpdates.forEach(function(value, key) {
1747
- state.batch.updates.storageUpdates.set(key, _chunkZR7CHFN6js.mergeStorageUpdates.call(void 0, state.batch.updates.storageUpdates.get(key), value));
1748
- });
1749
- (_reverseOps = state.batch.reverseOps).push.apply(_reverseOps, _toConsumableArray(reverse));
1750
- } else {
1751
- addToUndoStack(reverse);
1752
- state.redoStack = [];
1753
- dispatchOps(ops);
1754
- notify({
1755
- storageUpdates: storageUpdates
1756
- });
1757
- }
1758
- }
1759
- };
1760
- var eventHub = {
1761
- customEvent: makeEventSource(),
1762
- me: makeEventSource(),
1763
- others: makeEventSource(),
1764
- error: makeEventSource(),
1765
- connection: makeEventSource(),
1766
- storage: makeEventSource(),
1767
- history: makeEventSource(),
1768
- storageDidLoad: makeEventSource()
1769
- };
1770
- var effects = mockedEffects || {
1771
- authenticate: function authenticate(auth, createWebSocket) {
1772
- var rawToken = state.token;
1773
- var parsedToken = rawToken !== null && _chunkZR7CHFN6js.parseRoomAuthToken.call(void 0, rawToken);
1774
- if (parsedToken && !_chunkZR7CHFN6js.isTokenExpired.call(void 0, parsedToken)) {
1775
- var socket = createWebSocket(rawToken);
1776
- authenticationSuccess(parsedToken, socket);
1777
- } else {
1778
- return auth(config.roomId).then(function(param) {
1779
- var token = param.token;
1780
- if (state.connection.current.state !== "authenticating") {
1781
- return;
1782
- }
1783
- var parsedToken2 = _chunkZR7CHFN6js.parseRoomAuthToken.call(void 0, token);
1784
- var socket = createWebSocket(token);
1785
- authenticationSuccess(parsedToken2, socket);
1786
- state.token = token;
1787
- }).catch(function(er) {
1788
- return authenticationFailure(_instanceof(er, Error) ? er : new Error(String(er)));
1789
- });
1790
- }
1791
- },
1792
- send: function send(messageOrMessages) {
1793
- if (state.socket == null) {
1794
- throw new Error("Can't send message if socket is null");
1795
- }
1796
- state.socket.send(JSON.stringify(messageOrMessages));
1797
- },
1798
- delayFlush: function delayFlush(delay) {
1799
- return setTimeout(tryFlushing, delay);
1800
- },
1801
- startHeartbeatInterval: function startHeartbeatInterval() {
1802
- return setInterval(heartbeat, HEARTBEAT_INTERVAL);
1803
- },
1804
- schedulePongTimeout: function schedulePongTimeout() {
1805
- return setTimeout(pongTimeout, PONG_TIMEOUT);
1806
- },
1807
- scheduleReconnect: function scheduleReconnect(delay) {
1808
- return setTimeout(connect, delay);
1809
- }
1810
- };
1811
- var self = new DerivedRef([
1812
- state.connection,
1813
- state.me
1814
- ], function(conn, me) {
1815
- return isConnectionSelfAware(conn) ? {
1816
- connectionId: conn.id,
1817
- id: conn.userId,
1818
- info: conn.userInfo,
1819
- presence: me
1820
- } : null;
1080
+ }
1081
+ yield startLoadingStorage();
1082
+ return {
1083
+ root: _chunkUV2F4F4Rjs.nn.call(void 0, state.root)
1084
+ };
1821
1085
  });
1822
- var _getInitialStatePromise = null;
1823
- var _getInitialStateResolver = null;
1824
- return {
1825
- onClose: onClose,
1826
- onMessage: onMessage,
1827
- authenticationSuccess: authenticationSuccess,
1828
- heartbeat: heartbeat,
1829
- onNavigatorOnline: onNavigatorOnline,
1830
- simulateSocketClose: simulateSocketClose,
1831
- simulateSendCloseEvent: simulateSendCloseEvent,
1832
- onVisibilityChange: onVisibilityChange,
1833
- getUndoStack: function() {
1834
- return state.undoStack;
1835
- },
1836
- getItemsCount: function() {
1837
- return state.nodes.size;
1838
- },
1839
- connect: connect,
1840
- disconnect: disconnect,
1841
- subscribe: subscribe,
1842
- updatePresence: updatePresence,
1843
- broadcastEvent: broadcastEvent,
1844
- batch: batch,
1845
- undo: undo,
1846
- redo: redo,
1847
- canUndo: canUndo,
1848
- canRedo: canRedo,
1849
- pauseHistory: pauseHistory,
1850
- resumeHistory: resumeHistory,
1851
- getStorage: getStorage,
1852
- getStorageSnapshot: getStorageSnapshot,
1853
- events: {
1854
- customEvent: eventHub.customEvent.observable,
1855
- others: eventHub.others.observable,
1856
- me: eventHub.me.observable,
1857
- error: eventHub.error.observable,
1858
- connection: eventHub.connection.observable,
1859
- storage: eventHub.storage.observable,
1860
- history: eventHub.history.observable,
1861
- storageDidLoad: eventHub.storageDidLoad.observable
1862
- },
1863
- getConnectionState: getConnectionState,
1864
- isSelfAware: function() {
1865
- return isConnectionSelfAware(state.connection.current);
1866
- },
1867
- getSelf: function() {
1868
- return self.current;
1869
- },
1870
- getPresence: getPresence,
1871
- getOthers: getOthers
1086
+ }
1087
+ function undo() {
1088
+ if (state.activeBatch) {
1089
+ throw new Error("undo is not allowed during a batch");
1090
+ }
1091
+ const historyOps = state.undoStack.pop();
1092
+ if (historyOps === void 0) {
1093
+ return;
1094
+ }
1095
+ state.pausedHistory = null;
1096
+ const result = apply(historyOps, true);
1097
+ notify(result.updates);
1098
+ state.redoStack.push(result.reverse);
1099
+ onHistoryChange();
1100
+ for (const op of historyOps) {
1101
+ if (op.type !== "presence") {
1102
+ state.buffer.storageOperations.push(op);
1103
+ }
1104
+ }
1105
+ tryFlushing();
1106
+ }
1107
+ function canUndo() {
1108
+ return state.undoStack.length > 0;
1109
+ }
1110
+ function redo() {
1111
+ if (state.activeBatch) {
1112
+ throw new Error("redo is not allowed during a batch");
1113
+ }
1114
+ const historyOps = state.redoStack.pop();
1115
+ if (historyOps === void 0) {
1116
+ return;
1117
+ }
1118
+ state.pausedHistory = null;
1119
+ const result = apply(historyOps, true);
1120
+ notify(result.updates);
1121
+ state.undoStack.push(result.reverse);
1122
+ onHistoryChange();
1123
+ for (const op of historyOps) {
1124
+ if (op.type !== "presence") {
1125
+ state.buffer.storageOperations.push(op);
1126
+ }
1127
+ }
1128
+ tryFlushing();
1129
+ }
1130
+ function canRedo() {
1131
+ return state.redoStack.length > 0;
1132
+ }
1133
+ function batch(callback) {
1134
+ if (state.activeBatch) {
1135
+ return callback();
1136
+ }
1137
+ state.activeBatch = {
1138
+ ops: [],
1139
+ updates: {
1140
+ storageUpdates: /* @__PURE__ */ new Map(),
1141
+ presence: false,
1142
+ others: []
1143
+ },
1144
+ reverseOps: []
1872
1145
  };
1146
+ try {
1147
+ return callback();
1148
+ } finally {
1149
+ const currentBatch = state.activeBatch;
1150
+ state.activeBatch = null;
1151
+ if (currentBatch.reverseOps.length > 0) {
1152
+ addToUndoStack(currentBatch.reverseOps);
1153
+ }
1154
+ if (currentBatch.ops.length > 0) {
1155
+ state.redoStack = [];
1156
+ }
1157
+ if (currentBatch.ops.length > 0) {
1158
+ dispatchOps(currentBatch.ops);
1159
+ }
1160
+ notify(currentBatch.updates);
1161
+ tryFlushing();
1162
+ }
1163
+ }
1164
+ function pauseHistory() {
1165
+ state.pausedHistory = [];
1166
+ }
1167
+ function resumeHistory() {
1168
+ const historyOps = state.pausedHistory;
1169
+ state.pausedHistory = null;
1170
+ if (historyOps !== null && historyOps.length > 0) {
1171
+ _addToRealUndoStack(historyOps);
1172
+ }
1173
+ }
1174
+ function simulateSocketClose() {
1175
+ if (state.socket) {
1176
+ state.socket = null;
1177
+ }
1178
+ }
1179
+ function simulateSendCloseEvent(event) {
1180
+ onClose(event);
1181
+ }
1182
+ return {
1183
+ onClose,
1184
+ onMessage,
1185
+ authenticationSuccess,
1186
+ heartbeat,
1187
+ onNavigatorOnline,
1188
+ simulateSocketClose,
1189
+ simulateSendCloseEvent,
1190
+ onVisibilityChange,
1191
+ getUndoStack: () => state.undoStack,
1192
+ getItemsCount: () => state.nodes.size,
1193
+ connect,
1194
+ disconnect,
1195
+ subscribe,
1196
+ updatePresence,
1197
+ broadcastEvent,
1198
+ batch,
1199
+ undo,
1200
+ redo,
1201
+ canUndo,
1202
+ canRedo,
1203
+ pauseHistory,
1204
+ resumeHistory,
1205
+ getStorage,
1206
+ getStorageSnapshot,
1207
+ events: {
1208
+ customEvent: eventHub.customEvent.observable,
1209
+ others: eventHub.others.observable,
1210
+ me: eventHub.me.observable,
1211
+ error: eventHub.error.observable,
1212
+ connection: eventHub.connection.observable,
1213
+ storage: eventHub.storage.observable,
1214
+ history: eventHub.history.observable,
1215
+ storageDidLoad: eventHub.storageDidLoad.observable
1216
+ },
1217
+ getConnectionState,
1218
+ isSelfAware: () => isConnectionSelfAware(state.connection.current),
1219
+ getSelf: () => self.current,
1220
+ getPresence,
1221
+ getOthers
1222
+ };
1873
1223
  }
1874
1224
  function defaultState(initialPresence, initialStorage) {
1875
- var others = new OthersRef();
1876
- var connection = new ValueRef({
1877
- state: "closed"
1878
- });
1879
- return {
1880
- token: null,
1881
- lastConnectionId: null,
1882
- socket: null,
1883
- numberOfRetry: 0,
1884
- lastFlushTime: 0,
1885
- timeoutHandles: {
1886
- flush: null,
1887
- reconnect: 0,
1888
- pongTimeout: 0
1889
- },
1890
- buffer: {
1891
- me: {
1892
- type: "full",
1893
- data: initialPresence
1894
- },
1895
- messages: [],
1896
- storageOperations: []
1897
- },
1898
- intervalHandles: {
1899
- heartbeat: 0
1900
- },
1901
- connection: connection,
1902
- me: new MeRef(initialPresence),
1903
- others: others,
1904
- defaultStorageRoot: initialStorage,
1905
- idFactory: null,
1906
- clock: 0,
1907
- opClock: 0,
1908
- nodes: /* @__PURE__ */ new Map(),
1909
- root: void 0,
1910
- undoStack: [],
1911
- redoStack: [],
1912
- isHistoryPaused: false,
1913
- pausedHistory: [],
1914
- isBatching: false,
1915
- batch: {
1916
- ops: [],
1917
- updates: {
1918
- storageUpdates: /* @__PURE__ */ new Map(),
1919
- presence: false,
1920
- others: []
1921
- },
1922
- reverseOps: []
1923
- },
1924
- offlineOperations: /* @__PURE__ */ new Map()
1925
- };
1225
+ const others = new OthersRef();
1226
+ const connection = new ValueRef({ state: "closed" });
1227
+ return {
1228
+ token: null,
1229
+ lastConnectionId: null,
1230
+ socket: null,
1231
+ numberOfRetry: 0,
1232
+ lastFlushTime: 0,
1233
+ timeoutHandles: {
1234
+ flush: null,
1235
+ reconnect: 0,
1236
+ pongTimeout: 0
1237
+ },
1238
+ buffer: {
1239
+ me: {
1240
+ type: "full",
1241
+ data: initialPresence
1242
+ },
1243
+ messages: [],
1244
+ storageOperations: []
1245
+ },
1246
+ intervalHandles: {
1247
+ heartbeat: 0
1248
+ },
1249
+ connection,
1250
+ me: new MeRef(initialPresence),
1251
+ others,
1252
+ initialStorage,
1253
+ idFactory: null,
1254
+ clock: 0,
1255
+ opClock: 0,
1256
+ nodes: /* @__PURE__ */ new Map(),
1257
+ root: void 0,
1258
+ undoStack: [],
1259
+ redoStack: [],
1260
+ pausedHistory: null,
1261
+ activeBatch: null,
1262
+ offlineOperations: /* @__PURE__ */ new Map()
1263
+ };
1926
1264
  }
1927
1265
  function createRoom(options, config) {
1928
- var initialPresence = options.initialPresence, initialStorage = options.initialStorage;
1929
- var state = defaultState(typeof initialPresence === "function" ? initialPresence(config.roomId) : initialPresence, typeof initialStorage === "function" ? initialStorage(config.roomId) : initialStorage);
1930
- var machine = makeStateMachine(state, config);
1931
- var room = {
1932
- id: config.roomId,
1933
- getConnectionState: machine.getConnectionState,
1934
- isSelfAware: machine.isSelfAware,
1935
- getSelf: machine.getSelf,
1936
- subscribe: machine.subscribe,
1937
- getPresence: machine.getPresence,
1938
- updatePresence: machine.updatePresence,
1939
- getOthers: machine.getOthers,
1940
- broadcastEvent: machine.broadcastEvent,
1941
- getStorage: machine.getStorage,
1942
- getStorageSnapshot: machine.getStorageSnapshot,
1943
- events: machine.events,
1944
- batch: machine.batch,
1945
- history: {
1946
- undo: machine.undo,
1947
- redo: machine.redo,
1948
- canUndo: machine.canUndo,
1949
- canRedo: machine.canRedo,
1950
- pause: machine.pauseHistory,
1951
- resume: machine.resumeHistory
1952
- },
1953
- __INTERNAL_DO_NOT_USE: {
1954
- simulateCloseWebsocket: machine.simulateSocketClose,
1955
- simulateSendCloseEvent: machine.simulateSendCloseEvent
1956
- }
1957
- };
1958
- return {
1959
- connect: machine.connect,
1960
- disconnect: machine.disconnect,
1961
- onNavigatorOnline: machine.onNavigatorOnline,
1962
- onVisibilityChange: machine.onVisibilityChange,
1963
- room: room
1964
- };
1266
+ const { initialPresence, initialStorage } = options;
1267
+ const state = defaultState(
1268
+ typeof initialPresence === "function" ? initialPresence(config.roomId) : initialPresence,
1269
+ typeof initialStorage === "function" ? initialStorage(config.roomId) : initialStorage
1270
+ );
1271
+ const machine = makeStateMachine(
1272
+ state,
1273
+ config
1274
+ );
1275
+ const room = {
1276
+ id: config.roomId,
1277
+ getConnectionState: machine.getConnectionState,
1278
+ isSelfAware: machine.isSelfAware,
1279
+ getSelf: machine.getSelf,
1280
+ subscribe: machine.subscribe,
1281
+ getPresence: machine.getPresence,
1282
+ updatePresence: machine.updatePresence,
1283
+ getOthers: machine.getOthers,
1284
+ broadcastEvent: machine.broadcastEvent,
1285
+ getStorage: machine.getStorage,
1286
+ getStorageSnapshot: machine.getStorageSnapshot,
1287
+ events: machine.events,
1288
+ batch: machine.batch,
1289
+ history: {
1290
+ undo: machine.undo,
1291
+ redo: machine.redo,
1292
+ canUndo: machine.canUndo,
1293
+ canRedo: machine.canRedo,
1294
+ pause: machine.pauseHistory,
1295
+ resume: machine.resumeHistory
1296
+ },
1297
+ __INTERNAL_DO_NOT_USE: {
1298
+ simulateCloseWebsocket: machine.simulateSocketClose,
1299
+ simulateSendCloseEvent: machine.simulateSendCloseEvent
1300
+ }
1301
+ };
1302
+ return {
1303
+ connect: machine.connect,
1304
+ disconnect: machine.disconnect,
1305
+ onNavigatorOnline: machine.onNavigatorOnline,
1306
+ onVisibilityChange: machine.onVisibilityChange,
1307
+ room
1308
+ };
1965
1309
  }
1966
- var LiveblocksError = /*#__PURE__*/ function(Error1) {
1967
- _inherits(LiveblocksError, Error1);
1968
- var _super = _createSuper(LiveblocksError);
1969
- function LiveblocksError(message, code) {
1970
- _classCallCheck(this, LiveblocksError);
1971
- var _this;
1972
- _this = _super.call(this, message);
1973
- _this.code = code;
1974
- return _this;
1975
- }
1976
- return LiveblocksError;
1977
- }(_wrapNativeSuper(Error));
1310
+ var LiveblocksError = class extends Error {
1311
+ constructor(message, code) {
1312
+ super(message);
1313
+ this.code = code;
1314
+ }
1315
+ };
1978
1316
  function prepareCreateWebSocket(liveblocksServer, WebSocketPolyfill) {
1979
- if (typeof window === "undefined" && WebSocketPolyfill == null) {
1980
- throw new Error("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");
1981
- }
1982
- var ws = WebSocketPolyfill || WebSocket;
1983
- return function(token) {
1984
- return new ws("".concat(liveblocksServer, "/?token=").concat(token, "&version=").concat(true ? "0.18.0-beta0" : "dev"));
1985
- };
1317
+ if (typeof window === "undefined" && WebSocketPolyfill === void 0) {
1318
+ throw new Error(
1319
+ "To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill."
1320
+ );
1321
+ }
1322
+ const ws = WebSocketPolyfill || WebSocket;
1323
+ return (token) => {
1324
+ return new ws(
1325
+ `${liveblocksServer}/?token=${token}&version=${true ? "0.18.0-beta3" : "dev"}`
1326
+ );
1327
+ };
1986
1328
  }
1987
1329
  function prepareAuthEndpoint(authentication, fetchPolyfill) {
1988
- if (authentication.type === "public") {
1989
- if (typeof window === "undefined" && fetchPolyfill == null) {
1990
- throw new Error("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");
1991
- }
1992
- return function(room) {
1993
- return fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1994
- room: room,
1995
- publicApiKey: authentication.publicApiKey
1996
- });
1997
- };
1330
+ if (authentication.type === "public") {
1331
+ if (typeof window === "undefined" && fetchPolyfill === void 0) {
1332
+ throw new Error(
1333
+ "To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill."
1334
+ );
1998
1335
  }
1999
- if (authentication.type === "private") {
2000
- if (typeof window === "undefined" && fetchPolyfill == null) {
2001
- throw new Error("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");
2002
- }
2003
- return function(room) {
2004
- return fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
2005
- room: room
2006
- });
2007
- };
2008
- }
2009
- if (authentication.type === "custom") {
2010
- var authWithResponseValidation = function(room) {
2011
- return authentication.callback(room).then(function(response) {
2012
- if (!response || !response.token) {
2013
- throw new Error('Authentication error. We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }');
2014
- }
2015
- return response;
2016
- });
2017
- };
2018
- return authWithResponseValidation;
1336
+ return (room) => fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1337
+ room,
1338
+ publicApiKey: authentication.publicApiKey
1339
+ });
1340
+ }
1341
+ if (authentication.type === "private") {
1342
+ if (typeof window === "undefined" && fetchPolyfill === void 0) {
1343
+ throw new Error(
1344
+ "To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill."
1345
+ );
2019
1346
  }
2020
- throw new Error("Internal error. Unexpected authentication type");
1347
+ return (room) => fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1348
+ room
1349
+ });
1350
+ }
1351
+ if (authentication.type === "custom") {
1352
+ return (room) => _chunkUV2F4F4Rjs.__async.call(void 0, this, null, function* () {
1353
+ const response = yield authentication.callback(room);
1354
+ if (!response || !response.token) {
1355
+ throw new Error(
1356
+ 'Authentication error. We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }'
1357
+ );
1358
+ }
1359
+ return response;
1360
+ });
1361
+ }
1362
+ throw new Error("Internal error. Unexpected authentication type");
2021
1363
  }
2022
1364
  function fetchAuthEndpoint(fetch2, endpoint, body) {
2023
- return fetch2(endpoint, {
2024
- method: "POST",
2025
- headers: {
2026
- "Content-Type": "application/json"
2027
- },
2028
- body: JSON.stringify(body)
2029
- }).then(function(res) {
2030
- if (!res.ok) {
2031
- throw new AuthenticationError("Expected a status 200 but got ".concat(res.status, ' when doing a POST request on "').concat(endpoint, '"'));
2032
- }
2033
- return res.json().catch(function(er) {
2034
- throw new AuthenticationError('Expected a JSON response when doing a POST request on "'.concat(endpoint, '". ').concat(er));
2035
- });
2036
- }).then(function(data) {
2037
- if (!_chunkZR7CHFN6js.isPlainObject.call(void 0, data) || typeof data.token !== "string") {
2038
- throw new AuthenticationError('Expected a JSON response of the form `{ token: "..." }` when doing a POST request on "'.concat(endpoint, '", but got ').concat(JSON.stringify(data)));
2039
- }
2040
- var token = data.token;
2041
- return {
2042
- token: token
2043
- };
1365
+ return _chunkUV2F4F4Rjs.__async.call(void 0, this, null, function* () {
1366
+ const res = yield fetch2(endpoint, {
1367
+ method: "POST",
1368
+ headers: {
1369
+ "Content-Type": "application/json"
1370
+ },
1371
+ body: JSON.stringify(body)
2044
1372
  });
1373
+ if (!res.ok) {
1374
+ throw new AuthenticationError(
1375
+ `Expected a status 200 but got ${res.status} when doing a POST request on "${endpoint}"`
1376
+ );
1377
+ }
1378
+ let data;
1379
+ try {
1380
+ data = yield res.json();
1381
+ } catch (er) {
1382
+ throw new AuthenticationError(
1383
+ `Expected a JSON response when doing a POST request on "${endpoint}". ${er}`
1384
+ );
1385
+ }
1386
+ if (!_chunkUV2F4F4Rjs.isPlainObject.call(void 0, data) || typeof data.token !== "string") {
1387
+ throw new AuthenticationError(
1388
+ `Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${endpoint}", but got ${JSON.stringify(
1389
+ data
1390
+ )}`
1391
+ );
1392
+ }
1393
+ const { token } = data;
1394
+ return { token };
1395
+ });
2045
1396
  }
2046
- var AuthenticationError = /*#__PURE__*/ function(Error1) {
2047
- _inherits(AuthenticationError, Error1);
2048
- var _super = _createSuper(AuthenticationError);
2049
- function AuthenticationError(message) {
2050
- _classCallCheck(this, AuthenticationError);
2051
- return _super.call(this, message);
2052
- }
2053
- return AuthenticationError;
2054
- }(_wrapNativeSuper(Error));
1397
+ var AuthenticationError = class extends Error {
1398
+ constructor(message) {
1399
+ super(message);
1400
+ }
1401
+ };
1402
+
2055
1403
  // src/client.ts
2056
1404
  function createClient(options) {
2057
- var getRoom = function getRoom(roomId) {
2058
- var internalRoom = rooms.get(roomId);
2059
- return internalRoom ? internalRoom.room : null;
2060
- };
2061
- var enter = function enter(roomId, options2) {
2062
- var internalRoom = rooms.get(roomId);
2063
- if (internalRoom) {
2064
- return internalRoom.room;
2065
- }
2066
- _chunkZR7CHFN6js.deprecateIf.call(void 0, options2.initialPresence == null, "Please provide an initial presence value for the current user when entering the room.");
2067
- internalRoom = createRoom({
2068
- initialPresence: _nullishCoalesce(options2.initialPresence, function() {
2069
- return {};
2070
- }),
2071
- initialStorage: options2.initialStorage
2072
- }, {
2073
- roomId: roomId,
2074
- throttleDelay: throttleDelay,
2075
- polyfills: clientOptions.polyfills,
2076
- WebSocketPolyfill: clientOptions.WebSocketPolyfill,
2077
- fetchPolyfill: clientOptions.fetchPolyfill,
2078
- liveblocksServer: _optionalChain([
2079
- clientOptions,
2080
- "optionalAccess",
2081
- function(_9) {
2082
- return _9.liveblocksServer;
2083
- }
2084
- ]) || "wss://api.liveblocks.io/v6",
2085
- authentication: prepareAuthentication(clientOptions, roomId)
2086
- });
2087
- rooms.set(roomId, internalRoom);
2088
- if (!options2.DO_NOT_USE_withoutConnecting) {
2089
- if (typeof atob == "undefined") {
2090
- if (_optionalChain([
2091
- clientOptions,
2092
- "access",
2093
- function(_10) {
2094
- return _10.polyfills;
2095
- },
2096
- "optionalAccess",
2097
- function(_11) {
2098
- return _11.atob;
2099
- }
2100
- ]) == void 0) {
2101
- throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");
2102
- }
2103
- global.atob = clientOptions.polyfills.atob;
2104
- }
2105
- internalRoom.connect();
2106
- }
2107
- return internalRoom.room;
2108
- };
2109
- var leave = function leave(roomId) {
2110
- var room = rooms.get(roomId);
2111
- if (room) {
2112
- room.disconnect();
2113
- rooms.delete(roomId);
2114
- }
2115
- };
2116
- var clientOptions = options;
2117
- var throttleDelay = getThrottleDelayFromOptions(options);
2118
- var rooms = /* @__PURE__ */ new Map();
2119
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2120
- window.addEventListener("online", function() {
2121
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2122
- try {
2123
- for(var _iterator = rooms[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2124
- var _value = _slicedToArray(_step.value, 2), room = _value[1];
2125
- room.onNavigatorOnline();
2126
- }
2127
- } catch (err) {
2128
- _didIteratorError = true;
2129
- _iteratorError = err;
2130
- } finally{
2131
- try {
2132
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2133
- _iterator.return();
2134
- }
2135
- } finally{
2136
- if (_didIteratorError) {
2137
- throw _iteratorError;
2138
- }
2139
- }
2140
- }
2141
- });
1405
+ const clientOptions = options;
1406
+ const throttleDelay = getThrottleDelayFromOptions(options);
1407
+ const rooms = /* @__PURE__ */ new Map();
1408
+ function getRoom(roomId) {
1409
+ const internalRoom = rooms.get(roomId);
1410
+ return internalRoom ? internalRoom.room : null;
1411
+ }
1412
+ function enter(roomId, options2) {
1413
+ var _a, _b;
1414
+ let internalRoom = rooms.get(roomId);
1415
+ if (internalRoom) {
1416
+ return internalRoom.room;
2142
1417
  }
2143
- if (typeof document !== "undefined") {
2144
- document.addEventListener("visibilitychange", function() {
2145
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2146
- try {
2147
- for(var _iterator = rooms[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2148
- var _value = _slicedToArray(_step.value, 2), room = _value[1];
2149
- room.onVisibilityChange(document.visibilityState);
2150
- }
2151
- } catch (err) {
2152
- _didIteratorError = true;
2153
- _iteratorError = err;
2154
- } finally{
2155
- try {
2156
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2157
- _iterator.return();
2158
- }
2159
- } finally{
2160
- if (_didIteratorError) {
2161
- throw _iteratorError;
2162
- }
2163
- }
2164
- }
2165
- });
1418
+ _chunkUV2F4F4Rjs.deprecateIf.call(void 0,
1419
+ options2.initialPresence === null || options2.initialPresence === void 0,
1420
+ "Please provide an initial presence value for the current user when entering the room."
1421
+ );
1422
+ internalRoom = createRoom(
1423
+ {
1424
+ initialPresence: (_a = options2.initialPresence) != null ? _a : {},
1425
+ initialStorage: options2.initialStorage
1426
+ },
1427
+ {
1428
+ roomId,
1429
+ throttleDelay,
1430
+ polyfills: clientOptions.polyfills,
1431
+ WebSocketPolyfill: clientOptions.WebSocketPolyfill,
1432
+ fetchPolyfill: clientOptions.fetchPolyfill,
1433
+ liveblocksServer: (clientOptions == null ? void 0 : clientOptions.liveblocksServer) || "wss://api.liveblocks.io/v6",
1434
+ authentication: prepareAuthentication(clientOptions, roomId)
1435
+ }
1436
+ );
1437
+ rooms.set(
1438
+ roomId,
1439
+ internalRoom
1440
+ );
1441
+ if (!options2.DO_NOT_USE_withoutConnecting) {
1442
+ if (typeof atob === "undefined") {
1443
+ if (((_b = clientOptions.polyfills) == null ? void 0 : _b.atob) === void 0) {
1444
+ throw new Error(
1445
+ "You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill"
1446
+ );
1447
+ }
1448
+ global.atob = clientOptions.polyfills.atob;
1449
+ }
1450
+ internalRoom.connect();
2166
1451
  }
2167
- return {
2168
- getRoom: getRoom,
2169
- enter: enter,
2170
- leave: leave
2171
- };
1452
+ return internalRoom.room;
1453
+ }
1454
+ function leave(roomId) {
1455
+ const room = rooms.get(roomId);
1456
+ if (room) {
1457
+ room.disconnect();
1458
+ rooms.delete(roomId);
1459
+ }
1460
+ }
1461
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1462
+ window.addEventListener("online", () => {
1463
+ for (const [, room] of rooms) {
1464
+ room.onNavigatorOnline();
1465
+ }
1466
+ });
1467
+ }
1468
+ if (typeof document !== "undefined") {
1469
+ document.addEventListener("visibilitychange", () => {
1470
+ for (const [, room] of rooms) {
1471
+ room.onVisibilityChange(document.visibilityState);
1472
+ }
1473
+ });
1474
+ }
1475
+ return {
1476
+ getRoom,
1477
+ enter,
1478
+ leave
1479
+ };
2172
1480
  }
2173
1481
  function getThrottleDelayFromOptions(options) {
2174
- if (options.throttle === void 0) {
2175
- return 100;
2176
- }
2177
- if (typeof options.throttle !== "number" || options.throttle < 80 || options.throttle > 1e3) {
2178
- throw new Error("throttle should be a number between 80 and 1000.");
2179
- }
2180
- return options.throttle;
1482
+ if (options.throttle === void 0) {
1483
+ return 100;
1484
+ }
1485
+ if (typeof options.throttle !== "number" || options.throttle < 80 || options.throttle > 1e3) {
1486
+ throw new Error("throttle should be a number between 80 and 1000.");
1487
+ }
1488
+ return options.throttle;
2181
1489
  }
2182
1490
  function prepareAuthentication(clientOptions, roomId) {
2183
- var publicApiKey = clientOptions.publicApiKey, authEndpoint = clientOptions.authEndpoint;
2184
- if (authEndpoint !== void 0 && publicApiKey !== void 0) {
2185
- throw new Error("You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");
2186
- }
2187
- if (typeof publicApiKey === "string") {
2188
- if (publicApiKey.startsWith("sk_")) {
2189
- throw new Error("Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");
2190
- } else if (!publicApiKey.startsWith("pk_")) {
2191
- throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");
2192
- }
2193
- return {
2194
- type: "public",
2195
- publicApiKey: publicApiKey,
2196
- url: buildLiveblocksPublicAuthorizeEndpoint(clientOptions, roomId)
2197
- };
2198
- }
2199
- if (typeof authEndpoint === "string") {
2200
- return {
2201
- type: "private",
2202
- url: authEndpoint
2203
- };
2204
- } else if (typeof authEndpoint === "function") {
2205
- return {
2206
- type: "custom",
2207
- callback: authEndpoint
2208
- };
2209
- } else if (authEndpoint !== void 0) {
2210
- throw new Error("authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint");
1491
+ const { publicApiKey, authEndpoint } = clientOptions;
1492
+ if (authEndpoint !== void 0 && publicApiKey !== void 0) {
1493
+ throw new Error(
1494
+ "You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1495
+ );
1496
+ }
1497
+ if (typeof publicApiKey === "string") {
1498
+ if (publicApiKey.startsWith("sk_")) {
1499
+ throw new Error(
1500
+ "Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey"
1501
+ );
1502
+ } else if (!publicApiKey.startsWith("pk_")) {
1503
+ throw new Error(
1504
+ "Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey"
1505
+ );
2211
1506
  }
2212
- throw new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");
1507
+ return {
1508
+ type: "public",
1509
+ publicApiKey,
1510
+ url: buildLiveblocksPublicAuthorizeEndpoint(clientOptions, roomId)
1511
+ };
1512
+ }
1513
+ if (typeof authEndpoint === "string") {
1514
+ return {
1515
+ type: "private",
1516
+ url: authEndpoint
1517
+ };
1518
+ } else if (typeof authEndpoint === "function") {
1519
+ return {
1520
+ type: "custom",
1521
+ callback: authEndpoint
1522
+ };
1523
+ } else if (authEndpoint !== void 0) {
1524
+ throw new Error(
1525
+ "authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"
1526
+ );
1527
+ }
1528
+ throw new Error(
1529
+ "Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1530
+ );
2213
1531
  }
2214
1532
  function buildLiveblocksPublicAuthorizeEndpoint(options, roomId) {
2215
- if (options.publicAuthorizeEndpoint) {
2216
- return options.publicAuthorizeEndpoint.replace("{roomId}", roomId);
2217
- }
2218
- return "https://api.liveblocks.io/v2/rooms/".concat(encodeURIComponent(roomId), "/public/authorize");
1533
+ if (options.publicAuthorizeEndpoint) {
1534
+ return options.publicAuthorizeEndpoint.replace("{roomId}", roomId);
1535
+ }
1536
+ return `https://api.liveblocks.io/v2/rooms/${encodeURIComponent(
1537
+ roomId
1538
+ )}/public/authorize`;
2219
1539
  }
1540
+
2220
1541
  // src/shallow.ts
2221
1542
  function shallowArray(xs, ys) {
2222
- if (xs.length !== ys.length) {
2223
- return false;
2224
- }
2225
- for(var i = 0; i < xs.length; i++){
2226
- if (!Object.is(xs[i], ys[i])) {
2227
- return false;
2228
- }
1543
+ if (xs.length !== ys.length) {
1544
+ return false;
1545
+ }
1546
+ for (let i = 0; i < xs.length; i++) {
1547
+ if (!Object.is(xs[i], ys[i])) {
1548
+ return false;
2229
1549
  }
2230
- return true;
1550
+ }
1551
+ return true;
2231
1552
  }
2232
1553
  function shallowObj(objA, objB) {
2233
- if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null || Object.prototype.toString.call(objA) !== "[object Object]" || Object.prototype.toString.call(objB) !== "[object Object]") {
2234
- return false;
2235
- }
2236
- var keysA = Object.keys(objA);
2237
- if (keysA.length !== Object.keys(objB).length) {
2238
- return false;
2239
- }
2240
- return keysA.every(function(key) {
2241
- return Object.prototype.hasOwnProperty.call(objB, key) && Object.is(objA[key], objB[key]);
2242
- });
1554
+ if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null || Object.prototype.toString.call(objA) !== "[object Object]" || Object.prototype.toString.call(objB) !== "[object Object]") {
1555
+ return false;
1556
+ }
1557
+ const keysA = Object.keys(objA);
1558
+ if (keysA.length !== Object.keys(objB).length) {
1559
+ return false;
1560
+ }
1561
+ return keysA.every(
1562
+ (key) => Object.prototype.hasOwnProperty.call(objB, key) && Object.is(objA[key], objB[key])
1563
+ );
2243
1564
  }
2244
1565
  function shallow(a, b) {
2245
- if (Object.is(a, b)) {
2246
- return true;
2247
- }
2248
- var isArrayA = Array.isArray(a);
2249
- var isArrayB = Array.isArray(b);
2250
- if (isArrayA || isArrayB) {
2251
- if (!isArrayA || !isArrayB) {
2252
- return false;
2253
- }
2254
- return shallowArray(a, b);
1566
+ if (Object.is(a, b)) {
1567
+ return true;
1568
+ }
1569
+ const isArrayA = Array.isArray(a);
1570
+ const isArrayB = Array.isArray(b);
1571
+ if (isArrayA || isArrayB) {
1572
+ if (!isArrayA || !isArrayB) {
1573
+ return false;
2255
1574
  }
2256
- return shallowObj(a, b);
1575
+ return shallowArray(a, b);
1576
+ }
1577
+ return shallowObj(a, b);
2257
1578
  }
2258
- exports.LiveList = _chunkZR7CHFN6js.LiveList;
2259
- exports.LiveMap = _chunkZR7CHFN6js.LiveMap;
2260
- exports.LiveObject = _chunkZR7CHFN6js.LiveObject;
2261
- exports.createClient = createClient;
2262
- exports.shallow = shallow;
1579
+
1580
+
1581
+
1582
+
1583
+
1584
+
1585
+ exports.LiveList = _chunkUV2F4F4Rjs.LiveList; exports.LiveMap = _chunkUV2F4F4Rjs.LiveMap; exports.LiveObject = _chunkUV2F4F4Rjs.LiveObject; exports.createClient = createClient; exports.shallow = shallow;