@liveblocks/client 0.17.11-debug2 → 0.17.11

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.
@@ -1,2314 +0,0 @@
1
- // src/deprecation.ts
2
- var _emittedDeprecationWarnings = /* @__PURE__ */ new Set();
3
- function deprecate(message, key = message) {
4
- if (process.env.NODE_ENV !== "production") {
5
- if (!_emittedDeprecationWarnings.has(key)) {
6
- _emittedDeprecationWarnings.add(key);
7
- console.error(`DEPRECATION WARNING: ${message}`);
8
- }
9
- }
10
- }
11
- function deprecateIf(condition, message, key = message) {
12
- if (process.env.NODE_ENV !== "production") {
13
- if (condition) {
14
- deprecate(message, key);
15
- }
16
- }
17
- }
18
- function throwUsageError(message) {
19
- if (process.env.NODE_ENV !== "production") {
20
- const usageError = new Error(message);
21
- usageError.name = "Usage error";
22
- throw usageError;
23
- }
24
- }
25
- function errorIf(condition, message) {
26
- if (process.env.NODE_ENV !== "production") {
27
- if (condition) {
28
- throwUsageError(message);
29
- }
30
- }
31
- }
32
-
33
- // src/assert.ts
34
- function assertNever(_value, errmsg) {
35
- throw new Error(errmsg);
36
- }
37
- function assert(condition, errmsg) {
38
- if (process.env.NODE_ENV !== "production" && !condition) {
39
- const err = new Error(errmsg);
40
- err.name = "Assertion failure";
41
- throw err;
42
- }
43
- }
44
- function nn(value, errmsg = "Expected value to be non-nullable") {
45
- assert(value != null, errmsg);
46
- return value;
47
- }
48
-
49
- // src/types/ClientMsg.ts
50
- var ClientMsgCode = /* @__PURE__ */ ((ClientMsgCode2) => {
51
- ClientMsgCode2[ClientMsgCode2["UPDATE_PRESENCE"] = 100] = "UPDATE_PRESENCE";
52
- ClientMsgCode2[ClientMsgCode2["BROADCAST_EVENT"] = 103] = "BROADCAST_EVENT";
53
- ClientMsgCode2[ClientMsgCode2["FETCH_STORAGE"] = 200] = "FETCH_STORAGE";
54
- ClientMsgCode2[ClientMsgCode2["UPDATE_STORAGE"] = 201] = "UPDATE_STORAGE";
55
- return ClientMsgCode2;
56
- })(ClientMsgCode || {});
57
-
58
- // src/types/Op.ts
59
- var OpCode = /* @__PURE__ */ ((OpCode2) => {
60
- OpCode2[OpCode2["INIT"] = 0] = "INIT";
61
- OpCode2[OpCode2["SET_PARENT_KEY"] = 1] = "SET_PARENT_KEY";
62
- OpCode2[OpCode2["CREATE_LIST"] = 2] = "CREATE_LIST";
63
- OpCode2[OpCode2["UPDATE_OBJECT"] = 3] = "UPDATE_OBJECT";
64
- OpCode2[OpCode2["CREATE_OBJECT"] = 4] = "CREATE_OBJECT";
65
- OpCode2[OpCode2["DELETE_CRDT"] = 5] = "DELETE_CRDT";
66
- OpCode2[OpCode2["DELETE_OBJECT_KEY"] = 6] = "DELETE_OBJECT_KEY";
67
- OpCode2[OpCode2["CREATE_MAP"] = 7] = "CREATE_MAP";
68
- OpCode2[OpCode2["CREATE_REGISTER"] = 8] = "CREATE_REGISTER";
69
- return OpCode2;
70
- })(OpCode || {});
71
-
72
- // src/types/SerializedCrdt.ts
73
- var CrdtType = /* @__PURE__ */ ((CrdtType2) => {
74
- CrdtType2[CrdtType2["OBJECT"] = 0] = "OBJECT";
75
- CrdtType2[CrdtType2["LIST"] = 1] = "LIST";
76
- CrdtType2[CrdtType2["MAP"] = 2] = "MAP";
77
- CrdtType2[CrdtType2["REGISTER"] = 3] = "REGISTER";
78
- return CrdtType2;
79
- })(CrdtType || {});
80
- function isRootCrdt(crdt) {
81
- return crdt.type === 0 /* OBJECT */ && !isChildCrdt(crdt);
82
- }
83
- function isChildCrdt(crdt) {
84
- return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
85
- }
86
-
87
- // src/types/ServerMsg.ts
88
- var ServerMsgCode = /* @__PURE__ */ ((ServerMsgCode2) => {
89
- ServerMsgCode2[ServerMsgCode2["UPDATE_PRESENCE"] = 100] = "UPDATE_PRESENCE";
90
- ServerMsgCode2[ServerMsgCode2["USER_JOINED"] = 101] = "USER_JOINED";
91
- ServerMsgCode2[ServerMsgCode2["USER_LEFT"] = 102] = "USER_LEFT";
92
- ServerMsgCode2[ServerMsgCode2["BROADCASTED_EVENT"] = 103] = "BROADCASTED_EVENT";
93
- ServerMsgCode2[ServerMsgCode2["ROOM_STATE"] = 104] = "ROOM_STATE";
94
- ServerMsgCode2[ServerMsgCode2["INITIAL_STORAGE_STATE"] = 200] = "INITIAL_STORAGE_STATE";
95
- ServerMsgCode2[ServerMsgCode2["UPDATE_STORAGE"] = 201] = "UPDATE_STORAGE";
96
- return ServerMsgCode2;
97
- })(ServerMsgCode || {});
98
-
99
- // src/types/index.ts
100
- function isRoomEventName(value) {
101
- return value === "my-presence" || value === "others" || value === "event" || value === "error" || value === "connection" || value === "history";
102
- }
103
- var WebsocketCloseCodes = /* @__PURE__ */ ((WebsocketCloseCodes2) => {
104
- WebsocketCloseCodes2[WebsocketCloseCodes2["CLOSE_ABNORMAL"] = 1006] = "CLOSE_ABNORMAL";
105
- WebsocketCloseCodes2[WebsocketCloseCodes2["INVALID_MESSAGE_FORMAT"] = 4e3] = "INVALID_MESSAGE_FORMAT";
106
- WebsocketCloseCodes2[WebsocketCloseCodes2["NOT_ALLOWED"] = 4001] = "NOT_ALLOWED";
107
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_MESSAGES_PER_SECONDS"] = 4002] = "MAX_NUMBER_OF_MESSAGES_PER_SECONDS";
108
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_CONCURRENT_CONNECTIONS"] = 4003] = "MAX_NUMBER_OF_CONCURRENT_CONNECTIONS";
109
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP"] = 4004] = "MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP";
110
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM"] = 4005] = "MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM";
111
- WebsocketCloseCodes2[WebsocketCloseCodes2["CLOSE_WITHOUT_RETRY"] = 4999] = "CLOSE_WITHOUT_RETRY";
112
- return WebsocketCloseCodes2;
113
- })(WebsocketCloseCodes || {});
114
-
115
- // src/position.ts
116
- var min = 32;
117
- var max = 126;
118
- function makePosition(before, after) {
119
- if (before != null && after != null) {
120
- return pos(makePositionFromCodes(posCodes(before), posCodes(after)));
121
- } else if (before != null) {
122
- return getNextPosition(before);
123
- } else if (after != null) {
124
- return getPreviousPosition(after);
125
- }
126
- return pos([min + 1]);
127
- }
128
- function getPreviousPosition(after) {
129
- const result = [];
130
- const afterCodes = posCodes(after);
131
- for (let i = 0; i < afterCodes.length; i++) {
132
- const code = afterCodes[i];
133
- if (code <= min + 1) {
134
- result.push(min);
135
- if (afterCodes.length - 1 === i) {
136
- result.push(max);
137
- break;
138
- }
139
- } else {
140
- result.push(code - 1);
141
- break;
142
- }
143
- }
144
- return pos(result);
145
- }
146
- function getNextPosition(before) {
147
- const result = [];
148
- const beforeCodes = posCodes(before);
149
- for (let i = 0; i < beforeCodes.length; i++) {
150
- const code = beforeCodes[i];
151
- if (code === max) {
152
- result.push(code);
153
- if (beforeCodes.length - 1 === i) {
154
- result.push(min + 1);
155
- break;
156
- }
157
- } else {
158
- result.push(code + 1);
159
- break;
160
- }
161
- }
162
- return pos(result);
163
- }
164
- function makePositionFromCodes(before, after) {
165
- let index = 0;
166
- const result = [];
167
- while (true) {
168
- const beforeDigit = before[index] || min;
169
- const afterDigit = after[index] || max;
170
- if (beforeDigit > afterDigit) {
171
- throw new Error(
172
- `Impossible to generate position between ${before} and ${after}`
173
- );
174
- }
175
- if (beforeDigit === afterDigit) {
176
- result.push(beforeDigit);
177
- index++;
178
- continue;
179
- }
180
- if (afterDigit - beforeDigit === 1) {
181
- result.push(beforeDigit);
182
- result.push(...makePositionFromCodes(before.slice(index + 1), []));
183
- break;
184
- }
185
- const mid = afterDigit + beforeDigit >> 1;
186
- result.push(mid);
187
- break;
188
- }
189
- return result;
190
- }
191
- function posCodes(str) {
192
- const codes = [];
193
- for (let i = 0; i < str.length; i++) {
194
- codes.push(str.charCodeAt(i));
195
- }
196
- return codes;
197
- }
198
- function pos(codes) {
199
- return String.fromCharCode(...codes);
200
- }
201
- function comparePosition(posA, posB) {
202
- const aCodes = posCodes(posA);
203
- const bCodes = posCodes(posB);
204
- const maxLength = Math.max(aCodes.length, bCodes.length);
205
- for (let i = 0; i < maxLength; i++) {
206
- const a = aCodes[i] == null ? min : aCodes[i];
207
- const b = bCodes[i] == null ? min : bCodes[i];
208
- if (a === b) {
209
- continue;
210
- } else {
211
- return a - b;
212
- }
213
- }
214
- throw new Error(
215
- `Impossible to compare similar position "${posA}" and "${posB}"`
216
- );
217
- }
218
-
219
- // src/AbstractCrdt.ts
220
- function crdtAsLiveNode(value) {
221
- return value;
222
- }
223
- function HasParent(node, key) {
224
- return Object.freeze({ type: "HasParent", node, key });
225
- }
226
- var NoParent = Object.freeze({ type: "NoParent" });
227
- function Orphaned(oldKey) {
228
- return Object.freeze({ type: "Orphaned", oldKey });
229
- }
230
- var AbstractCrdt = class {
231
- constructor() {
232
- this._parent = NoParent;
233
- }
234
- _getParentKeyOrThrow() {
235
- switch (this.parent.type) {
236
- case "HasParent":
237
- return this.parent.key;
238
- case "NoParent":
239
- throw new Error("Parent key is missing");
240
- case "Orphaned":
241
- return this.parent.oldKey;
242
- default:
243
- return assertNever(this.parent, "Unknown state");
244
- }
245
- }
246
- get _doc() {
247
- return this.__doc;
248
- }
249
- get roomId() {
250
- return this.__doc ? this.__doc.roomId : null;
251
- }
252
- get _id() {
253
- return this.__id;
254
- }
255
- get parent() {
256
- return this._parent;
257
- }
258
- get _parentNode() {
259
- switch (this.parent.type) {
260
- case "HasParent":
261
- return this.parent.node;
262
- case "NoParent":
263
- return null;
264
- case "Orphaned":
265
- return null;
266
- default:
267
- return assertNever(this.parent, "Unknown state");
268
- }
269
- }
270
- get _parentKey() {
271
- switch (this.parent.type) {
272
- case "HasParent":
273
- return this.parent.key;
274
- case "NoParent":
275
- return null;
276
- case "Orphaned":
277
- return this.parent.oldKey;
278
- default:
279
- return assertNever(this.parent, "Unknown state");
280
- }
281
- }
282
- _apply(op, _isLocal) {
283
- switch (op.type) {
284
- case 5 /* DELETE_CRDT */: {
285
- if (this.parent.type === "HasParent") {
286
- return this.parent.node._detachChild(crdtAsLiveNode(this));
287
- }
288
- return { modified: false };
289
- }
290
- }
291
- return { modified: false };
292
- }
293
- _setParentLink(newParentNode, newParentKey) {
294
- switch (this.parent.type) {
295
- case "HasParent":
296
- if (this.parent.node !== newParentNode) {
297
- throw new Error("Cannot attach parent if it already exist");
298
- } else {
299
- this._parent = HasParent(newParentNode, newParentKey);
300
- return;
301
- }
302
- case "Orphaned":
303
- case "NoParent": {
304
- this._parent = HasParent(newParentNode, newParentKey);
305
- return;
306
- }
307
- default:
308
- return assertNever(this.parent, "Unknown state");
309
- }
310
- }
311
- _attach(id, doc) {
312
- if (this.__id || this.__doc) {
313
- throw new Error("Cannot attach if CRDT is already attached");
314
- }
315
- doc.addItem(id, crdtAsLiveNode(this));
316
- this.__id = id;
317
- this.__doc = doc;
318
- }
319
- _detach() {
320
- if (this.__doc && this.__id) {
321
- this.__doc.deleteItem(this.__id);
322
- }
323
- switch (this.parent.type) {
324
- case "HasParent": {
325
- this._parent = Orphaned(this.parent.key);
326
- break;
327
- }
328
- case "NoParent": {
329
- this._parent = NoParent;
330
- break;
331
- }
332
- case "Orphaned": {
333
- this._parent = Orphaned(this.parent.oldKey);
334
- break;
335
- }
336
- default:
337
- assertNever(this.parent, "Unknown state");
338
- }
339
- this.__doc = void 0;
340
- }
341
- };
342
-
343
- // src/LiveRegister.ts
344
- var LiveRegister = class extends AbstractCrdt {
345
- constructor(data) {
346
- super();
347
- this._data = data;
348
- }
349
- get data() {
350
- return this._data;
351
- }
352
- static _deserialize([id, item], _parentToChildren, doc) {
353
- const register = new LiveRegister(item.data);
354
- register._attach(id, doc);
355
- return register;
356
- }
357
- _serialize(parentId, parentKey, doc) {
358
- if (this._id == null || parentId == null || parentKey == null) {
359
- throw new Error(
360
- "Cannot serialize register if parentId or parentKey is undefined"
361
- );
362
- }
363
- return [
364
- {
365
- type: 8 /* CREATE_REGISTER */,
366
- opId: doc?.generateOpId(),
367
- id: this._id,
368
- parentId,
369
- parentKey,
370
- data: this.data
371
- }
372
- ];
373
- }
374
- _toSerializedCrdt() {
375
- if (this.parent.type !== "HasParent") {
376
- throw new Error("Cannot serialize LiveRegister if parent is missing");
377
- }
378
- return {
379
- type: 3 /* REGISTER */,
380
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
381
- parentKey: this.parent.key,
382
- data: this.data
383
- };
384
- }
385
- _attachChild(_op) {
386
- throw new Error("Method not implemented.");
387
- }
388
- _detachChild(_crdt) {
389
- throw new Error("Method not implemented.");
390
- }
391
- _apply(op, isLocal) {
392
- return super._apply(op, isLocal);
393
- }
394
- };
395
-
396
- // src/LiveMap.ts
397
- var LiveMap = class extends AbstractCrdt {
398
- constructor(entries2) {
399
- super();
400
- errorIf(
401
- entries2 === null,
402
- "Support for calling `new LiveMap(null)` will be removed in @liveblocks/client 0.18. Please call as `new LiveMap()`, or `new LiveMap([])`."
403
- );
404
- this.unacknowledgedSet = /* @__PURE__ */ new Map();
405
- if (entries2) {
406
- const mappedEntries = [];
407
- for (const entry of entries2) {
408
- const value = lsonToLiveNode(entry[1]);
409
- value._setParentLink(this, entry[0]);
410
- mappedEntries.push([entry[0], value]);
411
- }
412
- this._map = new Map(mappedEntries);
413
- } else {
414
- this._map = /* @__PURE__ */ new Map();
415
- }
416
- }
417
- _serialize(parentId, parentKey, doc) {
418
- if (this._id == null) {
419
- throw new Error("Cannot serialize item is not attached");
420
- }
421
- const ops = [];
422
- const op = {
423
- id: this._id,
424
- opId: doc?.generateOpId(),
425
- type: 7 /* CREATE_MAP */,
426
- parentId,
427
- parentKey
428
- };
429
- ops.push(op);
430
- for (const [key, value] of this._map) {
431
- ops.push(...value._serialize(this._id, key, doc));
432
- }
433
- return ops;
434
- }
435
- static _deserialize([id, _item], parentToChildren, doc) {
436
- const map = new LiveMap();
437
- map._attach(id, doc);
438
- const children = parentToChildren.get(id);
439
- if (children == null) {
440
- return map;
441
- }
442
- for (const [id2, crdt] of children) {
443
- const child = deserialize([id2, crdt], parentToChildren, doc);
444
- child._setParentLink(map, crdt.parentKey);
445
- map._map.set(crdt.parentKey, child);
446
- }
447
- return map;
448
- }
449
- _attach(id, doc) {
450
- super._attach(id, doc);
451
- for (const [_key, value] of this._map) {
452
- if (isLiveNode(value)) {
453
- value._attach(doc.generateId(), doc);
454
- }
455
- }
456
- }
457
- _attachChild(op, source) {
458
- if (this._doc == null) {
459
- throw new Error("Can't attach child if doc is not present");
460
- }
461
- const { id, parentKey, opId } = op;
462
- const key = parentKey;
463
- const child = creationOpToLiveNode(op);
464
- if (this._doc.getItem(id) !== void 0) {
465
- return { modified: false };
466
- }
467
- if (source === 2 /* ACK */) {
468
- const lastUpdateOpId = this.unacknowledgedSet.get(key);
469
- if (lastUpdateOpId === opId) {
470
- this.unacknowledgedSet.delete(key);
471
- return { modified: false };
472
- } else if (lastUpdateOpId != null) {
473
- return { modified: false };
474
- }
475
- } else if (source === 1 /* REMOTE */) {
476
- this.unacknowledgedSet.delete(key);
477
- }
478
- const previousValue = this._map.get(key);
479
- let reverse;
480
- if (previousValue) {
481
- const thisId = nn(this._id);
482
- reverse = previousValue._serialize(thisId, key);
483
- previousValue._detach();
484
- } else {
485
- reverse = [{ type: 5 /* DELETE_CRDT */, id }];
486
- }
487
- child._setParentLink(this, key);
488
- child._attach(id, this._doc);
489
- this._map.set(key, child);
490
- return {
491
- modified: {
492
- node: this,
493
- type: "LiveMap",
494
- updates: { [key]: { type: "update" } }
495
- },
496
- reverse
497
- };
498
- }
499
- _detach() {
500
- super._detach();
501
- for (const item of this._map.values()) {
502
- item._detach();
503
- }
504
- }
505
- _detachChild(child) {
506
- const id = nn(this._id);
507
- const parentKey = nn(child._parentKey);
508
- const reverse = child._serialize(id, parentKey, this._doc);
509
- for (const [key, value] of this._map) {
510
- if (value === child) {
511
- this._map.delete(key);
512
- }
513
- }
514
- child._detach();
515
- const storageUpdate = {
516
- node: this,
517
- type: "LiveMap",
518
- updates: { [parentKey]: { type: "delete" } }
519
- };
520
- return { modified: storageUpdate, reverse };
521
- }
522
- _toSerializedCrdt() {
523
- if (this.parent.type !== "HasParent") {
524
- throw new Error("Cannot serialize LiveMap if parent is missing");
525
- }
526
- return {
527
- type: 2 /* MAP */,
528
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
529
- parentKey: this.parent.key
530
- };
531
- }
532
- get(key) {
533
- const value = this._map.get(key);
534
- if (value == void 0) {
535
- return void 0;
536
- }
537
- return liveNodeToLson(value);
538
- }
539
- set(key, value) {
540
- const oldValue = this._map.get(key);
541
- if (oldValue) {
542
- oldValue._detach();
543
- }
544
- const item = lsonToLiveNode(value);
545
- item._setParentLink(this, key);
546
- this._map.set(key, item);
547
- if (this._doc && this._id) {
548
- const id = this._doc.generateId();
549
- item._attach(id, this._doc);
550
- const storageUpdates = /* @__PURE__ */ new Map();
551
- storageUpdates.set(this._id, {
552
- node: this,
553
- type: "LiveMap",
554
- updates: { [key]: { type: "update" } }
555
- });
556
- const ops = item._serialize(this._id, key, this._doc);
557
- this.unacknowledgedSet.set(key, nn(ops[0].opId));
558
- this._doc.dispatch(
559
- item._serialize(this._id, key, this._doc),
560
- oldValue ? oldValue._serialize(this._id, key) : [{ type: 5 /* DELETE_CRDT */, id }],
561
- storageUpdates
562
- );
563
- }
564
- }
565
- get size() {
566
- return this._map.size;
567
- }
568
- has(key) {
569
- return this._map.has(key);
570
- }
571
- delete(key) {
572
- const item = this._map.get(key);
573
- if (item == null) {
574
- return false;
575
- }
576
- item._detach();
577
- this._map.delete(key);
578
- if (this._doc && item._id) {
579
- const thisId = nn(this._id);
580
- const storageUpdates = /* @__PURE__ */ new Map();
581
- storageUpdates.set(thisId, {
582
- node: this,
583
- type: "LiveMap",
584
- updates: { [key]: { type: "delete" } }
585
- });
586
- this._doc.dispatch(
587
- [
588
- {
589
- type: 5 /* DELETE_CRDT */,
590
- id: item._id,
591
- opId: this._doc.generateOpId()
592
- }
593
- ],
594
- item._serialize(thisId, key),
595
- storageUpdates
596
- );
597
- }
598
- return true;
599
- }
600
- entries() {
601
- const innerIterator = this._map.entries();
602
- return {
603
- [Symbol.iterator]() {
604
- return this;
605
- },
606
- next() {
607
- const iteratorValue = innerIterator.next();
608
- if (iteratorValue.done) {
609
- return {
610
- done: true,
611
- value: void 0
612
- };
613
- }
614
- const entry = iteratorValue.value;
615
- const key = entry[0];
616
- const value = liveNodeToLson(iteratorValue.value[1]);
617
- return {
618
- value: [key, value]
619
- };
620
- }
621
- };
622
- }
623
- [Symbol.iterator]() {
624
- return this.entries();
625
- }
626
- keys() {
627
- return this._map.keys();
628
- }
629
- values() {
630
- const innerIterator = this._map.values();
631
- return {
632
- [Symbol.iterator]() {
633
- return this;
634
- },
635
- next() {
636
- const iteratorValue = innerIterator.next();
637
- if (iteratorValue.done) {
638
- return {
639
- done: true,
640
- value: void 0
641
- };
642
- }
643
- const value = liveNodeToLson(iteratorValue.value);
644
- return { value };
645
- }
646
- };
647
- }
648
- forEach(callback) {
649
- for (const entry of this) {
650
- callback(entry[1], entry[0], this);
651
- }
652
- }
653
- };
654
-
655
- // src/LiveObject.ts
656
- var LiveObject = class extends AbstractCrdt {
657
- constructor(obj = {}) {
658
- super();
659
- this._propToLastUpdate = /* @__PURE__ */ new Map();
660
- for (const key in obj) {
661
- const value = obj[key];
662
- if (value === void 0) {
663
- continue;
664
- } else if (isLiveNode(value)) {
665
- value._setParentLink(this, key);
666
- }
667
- }
668
- this._map = new Map(Object.entries(obj));
669
- }
670
- _serialize(parentId, parentKey, doc) {
671
- if (this._id == null) {
672
- throw new Error("Cannot serialize item is not attached");
673
- }
674
- const opId = doc?.generateOpId();
675
- const ops = [];
676
- const op = parentId !== void 0 && parentKey !== void 0 ? {
677
- type: 4 /* CREATE_OBJECT */,
678
- id: this._id,
679
- opId,
680
- parentId,
681
- parentKey,
682
- data: {}
683
- } : { type: 4 /* CREATE_OBJECT */, id: this._id, opId, data: {} };
684
- ops.push(op);
685
- for (const [key, value] of this._map) {
686
- if (isLiveNode(value)) {
687
- ops.push(...value._serialize(this._id, key, doc));
688
- } else {
689
- op.data[key] = value;
690
- }
691
- }
692
- return ops;
693
- }
694
- static _deserialize([id, item], parentToChildren, doc) {
695
- const liveObj = new LiveObject(item.data);
696
- liveObj._attach(id, doc);
697
- return this._deserializeChildren(liveObj, parentToChildren, doc);
698
- }
699
- static _deserializeChildren(liveObj, parentToChildren, doc) {
700
- const children = parentToChildren.get(nn(liveObj._id));
701
- if (children == null) {
702
- return liveObj;
703
- }
704
- for (const [id, crdt] of children) {
705
- const child = deserializeToLson([id, crdt], parentToChildren, doc);
706
- if (isLiveStructure(child)) {
707
- child._setParentLink(liveObj, crdt.parentKey);
708
- }
709
- liveObj._map.set(crdt.parentKey, child);
710
- }
711
- return liveObj;
712
- }
713
- _attach(id, doc) {
714
- super._attach(id, doc);
715
- for (const [_key, value] of this._map) {
716
- if (isLiveNode(value)) {
717
- value._attach(doc.generateId(), doc);
718
- }
719
- }
720
- }
721
- _attachChild(op, source) {
722
- if (this._doc == null) {
723
- throw new Error("Can't attach child if doc is not present");
724
- }
725
- const { id, opId, parentKey: key } = op;
726
- const child = creationOpToLson(op);
727
- if (this._doc.getItem(id) !== void 0) {
728
- if (this._propToLastUpdate.get(key) === opId) {
729
- this._propToLastUpdate.delete(key);
730
- }
731
- return { modified: false };
732
- }
733
- if (source === 0 /* UNDOREDO_RECONNECT */) {
734
- this._propToLastUpdate.set(key, nn(opId));
735
- } else if (this._propToLastUpdate.get(key) === void 0) {
736
- } else if (this._propToLastUpdate.get(key) === opId) {
737
- this._propToLastUpdate.delete(key);
738
- return { modified: false };
739
- } else {
740
- return { modified: false };
741
- }
742
- const thisId = nn(this._id);
743
- const previousValue = this._map.get(key);
744
- let reverse;
745
- if (isLiveNode(previousValue)) {
746
- reverse = previousValue._serialize(thisId, key);
747
- previousValue._detach();
748
- } else if (previousValue === void 0) {
749
- reverse = [{ type: 6 /* DELETE_OBJECT_KEY */, id: thisId, key }];
750
- } else {
751
- reverse = [
752
- {
753
- type: 3 /* UPDATE_OBJECT */,
754
- id: thisId,
755
- data: { [key]: previousValue }
756
- }
757
- ];
758
- }
759
- this._map.set(key, child);
760
- if (isLiveStructure(child)) {
761
- child._setParentLink(this, key);
762
- child._attach(id, this._doc);
763
- }
764
- return {
765
- reverse,
766
- modified: {
767
- node: this,
768
- type: "LiveObject",
769
- updates: { [key]: { type: "update" } }
770
- }
771
- };
772
- }
773
- _detachChild(child) {
774
- if (child) {
775
- const id = nn(this._id);
776
- const parentKey = nn(child._parentKey);
777
- const reverse = child._serialize(id, parentKey, this._doc);
778
- for (const [key, value] of this._map) {
779
- if (value === child) {
780
- this._map.delete(key);
781
- }
782
- }
783
- child._detach();
784
- const storageUpdate = {
785
- node: this,
786
- type: "LiveObject",
787
- updates: {
788
- [parentKey]: { type: "delete" }
789
- }
790
- };
791
- return { modified: storageUpdate, reverse };
792
- }
793
- return { modified: false };
794
- }
795
- _detach() {
796
- super._detach();
797
- for (const value of this._map.values()) {
798
- if (isLiveNode(value)) {
799
- value._detach();
800
- }
801
- }
802
- }
803
- _apply(op, isLocal) {
804
- if (op.type === 3 /* UPDATE_OBJECT */) {
805
- return this._applyUpdate(op, isLocal);
806
- } else if (op.type === 6 /* DELETE_OBJECT_KEY */) {
807
- return this._applyDeleteObjectKey(op);
808
- }
809
- return super._apply(op, isLocal);
810
- }
811
- _toSerializedCrdt() {
812
- const data = {};
813
- for (const [key, value] of this._map) {
814
- if (!isLiveNode(value)) {
815
- data[key] = value;
816
- }
817
- }
818
- if (this.parent.type === "HasParent" && this.parent.node._id) {
819
- return {
820
- type: 0 /* OBJECT */,
821
- parentId: this.parent.node._id,
822
- parentKey: this.parent.key,
823
- data
824
- };
825
- } else {
826
- return {
827
- type: 0 /* OBJECT */,
828
- data
829
- };
830
- }
831
- }
832
- _applyUpdate(op, isLocal) {
833
- let isModified = false;
834
- const id = nn(this._id);
835
- const reverse = [];
836
- const reverseUpdate = {
837
- type: 3 /* UPDATE_OBJECT */,
838
- id,
839
- data: {}
840
- };
841
- reverse.push(reverseUpdate);
842
- for (const key in op.data) {
843
- const oldValue = this._map.get(key);
844
- if (isLiveNode(oldValue)) {
845
- reverse.push(...oldValue._serialize(id, key));
846
- oldValue._detach();
847
- } else if (oldValue !== void 0) {
848
- reverseUpdate.data[key] = oldValue;
849
- } else if (oldValue === void 0) {
850
- reverse.push({ type: 6 /* DELETE_OBJECT_KEY */, id, key });
851
- }
852
- }
853
- const updateDelta = {};
854
- for (const key in op.data) {
855
- const value = op.data[key];
856
- if (value === void 0) {
857
- continue;
858
- }
859
- if (isLocal) {
860
- this._propToLastUpdate.set(key, nn(op.opId));
861
- } else if (this._propToLastUpdate.get(key) == null) {
862
- isModified = true;
863
- } else if (this._propToLastUpdate.get(key) === op.opId) {
864
- this._propToLastUpdate.delete(key);
865
- continue;
866
- } else {
867
- continue;
868
- }
869
- const oldValue = this._map.get(key);
870
- if (isLiveNode(oldValue)) {
871
- oldValue._detach();
872
- }
873
- isModified = true;
874
- updateDelta[key] = { type: "update" };
875
- this._map.set(key, value);
876
- }
877
- if (Object.keys(reverseUpdate.data).length !== 0) {
878
- reverse.unshift(reverseUpdate);
879
- }
880
- return isModified ? {
881
- modified: {
882
- node: this,
883
- type: "LiveObject",
884
- updates: updateDelta
885
- },
886
- reverse
887
- } : { modified: false };
888
- }
889
- _applyDeleteObjectKey(op) {
890
- const key = op.key;
891
- if (this._map.has(key) === false) {
892
- return { modified: false };
893
- }
894
- if (this._propToLastUpdate.get(key) !== void 0) {
895
- return { modified: false };
896
- }
897
- const oldValue = this._map.get(key);
898
- const id = nn(this._id);
899
- let reverse = [];
900
- if (isLiveNode(oldValue)) {
901
- reverse = oldValue._serialize(id, op.key);
902
- oldValue._detach();
903
- } else if (oldValue !== void 0) {
904
- reverse = [
905
- {
906
- type: 3 /* UPDATE_OBJECT */,
907
- id,
908
- data: { [key]: oldValue }
909
- }
910
- ];
911
- }
912
- this._map.delete(key);
913
- return {
914
- modified: {
915
- node: this,
916
- type: "LiveObject",
917
- updates: { [op.key]: { type: "delete" } }
918
- },
919
- reverse
920
- };
921
- }
922
- toObject() {
923
- return fromEntries(this._map);
924
- }
925
- set(key, value) {
926
- this.update({ [key]: value });
927
- }
928
- get(key) {
929
- return this._map.get(key);
930
- }
931
- delete(key) {
932
- const keyAsString = key;
933
- const oldValue = this._map.get(keyAsString);
934
- if (oldValue === void 0) {
935
- return;
936
- }
937
- if (this._doc == null || this._id == null) {
938
- if (isLiveNode(oldValue)) {
939
- oldValue._detach();
940
- }
941
- this._map.delete(keyAsString);
942
- return;
943
- }
944
- let reverse;
945
- if (isLiveNode(oldValue)) {
946
- oldValue._detach();
947
- reverse = oldValue._serialize(this._id, keyAsString);
948
- } else {
949
- reverse = [
950
- {
951
- type: 3 /* UPDATE_OBJECT */,
952
- data: { [keyAsString]: oldValue },
953
- id: this._id
954
- }
955
- ];
956
- }
957
- this._map.delete(keyAsString);
958
- const storageUpdates = /* @__PURE__ */ new Map();
959
- storageUpdates.set(this._id, {
960
- node: this,
961
- type: "LiveObject",
962
- updates: { [key]: { type: "delete" } }
963
- });
964
- this._doc.dispatch(
965
- [
966
- {
967
- type: 6 /* DELETE_OBJECT_KEY */,
968
- key: keyAsString,
969
- id: this._id,
970
- opId: this._doc.generateOpId()
971
- }
972
- ],
973
- reverse,
974
- storageUpdates
975
- );
976
- }
977
- update(overrides) {
978
- if (this._doc == null || this._id == null) {
979
- for (const key in overrides) {
980
- const newValue = overrides[key];
981
- if (newValue === void 0) {
982
- continue;
983
- }
984
- const oldValue = this._map.get(key);
985
- if (isLiveNode(oldValue)) {
986
- oldValue._detach();
987
- }
988
- if (isLiveNode(newValue)) {
989
- newValue._setParentLink(this, key);
990
- }
991
- this._map.set(key, newValue);
992
- }
993
- return;
994
- }
995
- const ops = [];
996
- const reverseOps = [];
997
- const opId = this._doc.generateOpId();
998
- const updatedProps = {};
999
- const reverseUpdateOp = {
1000
- id: this._id,
1001
- type: 3 /* UPDATE_OBJECT */,
1002
- data: {}
1003
- };
1004
- const updateDelta = {};
1005
- for (const key in overrides) {
1006
- const newValue = overrides[key];
1007
- if (newValue === void 0) {
1008
- continue;
1009
- }
1010
- const oldValue = this._map.get(key);
1011
- if (isLiveNode(oldValue)) {
1012
- reverseOps.push(...oldValue._serialize(this._id, key));
1013
- oldValue._detach();
1014
- } else if (oldValue === void 0) {
1015
- reverseOps.push({ type: 6 /* DELETE_OBJECT_KEY */, id: this._id, key });
1016
- } else {
1017
- reverseUpdateOp.data[key] = oldValue;
1018
- }
1019
- if (isLiveNode(newValue)) {
1020
- newValue._setParentLink(this, key);
1021
- newValue._attach(this._doc.generateId(), this._doc);
1022
- const newAttachChildOps = newValue._serialize(this._id, key, this._doc);
1023
- const createCrdtOp = newAttachChildOps.find(
1024
- (op) => op.parentId === this._id
1025
- );
1026
- if (createCrdtOp) {
1027
- this._propToLastUpdate.set(key, nn(createCrdtOp.opId));
1028
- }
1029
- ops.push(...newAttachChildOps);
1030
- } else {
1031
- updatedProps[key] = newValue;
1032
- this._propToLastUpdate.set(key, opId);
1033
- }
1034
- this._map.set(key, newValue);
1035
- updateDelta[key] = { type: "update" };
1036
- }
1037
- if (Object.keys(reverseUpdateOp.data).length !== 0) {
1038
- reverseOps.unshift(reverseUpdateOp);
1039
- }
1040
- if (Object.keys(updatedProps).length !== 0) {
1041
- ops.unshift({
1042
- opId,
1043
- id: this._id,
1044
- type: 3 /* UPDATE_OBJECT */,
1045
- data: updatedProps
1046
- });
1047
- }
1048
- const storageUpdates = /* @__PURE__ */ new Map();
1049
- storageUpdates.set(this._id, {
1050
- node: this,
1051
- type: "LiveObject",
1052
- updates: updateDelta
1053
- });
1054
- this._doc.dispatch(ops, reverseOps, storageUpdates);
1055
- }
1056
- };
1057
-
1058
- // src/utils.ts
1059
- function remove(array, item) {
1060
- for (let i = 0; i < array.length; i++) {
1061
- if (array[i] === item) {
1062
- array.splice(i, 1);
1063
- break;
1064
- }
1065
- }
1066
- }
1067
- function compact(items) {
1068
- return items.filter((item) => item != null);
1069
- }
1070
- function creationOpToLiveNode(op) {
1071
- return lsonToLiveNode(creationOpToLson(op));
1072
- }
1073
- function creationOpToLson(op) {
1074
- switch (op.type) {
1075
- case 8 /* CREATE_REGISTER */:
1076
- return op.data;
1077
- case 4 /* CREATE_OBJECT */:
1078
- return new LiveObject(op.data);
1079
- case 7 /* CREATE_MAP */:
1080
- return new LiveMap();
1081
- case 2 /* CREATE_LIST */:
1082
- return new LiveList();
1083
- default:
1084
- return assertNever(op, "Unknown creation Op");
1085
- }
1086
- }
1087
- function isSameNodeOrChildOf(node, parent) {
1088
- if (node === parent) {
1089
- return true;
1090
- }
1091
- if (node.parent.type === "HasParent") {
1092
- return isSameNodeOrChildOf(node.parent.node, parent);
1093
- }
1094
- return false;
1095
- }
1096
- function deserialize([id, crdt], parentToChildren, doc) {
1097
- switch (crdt.type) {
1098
- case 0 /* OBJECT */: {
1099
- return LiveObject._deserialize([id, crdt], parentToChildren, doc);
1100
- }
1101
- case 1 /* LIST */: {
1102
- return LiveList._deserialize([id, crdt], parentToChildren, doc);
1103
- }
1104
- case 2 /* MAP */: {
1105
- return LiveMap._deserialize([id, crdt], parentToChildren, doc);
1106
- }
1107
- case 3 /* REGISTER */: {
1108
- return LiveRegister._deserialize([id, crdt], parentToChildren, doc);
1109
- }
1110
- default: {
1111
- throw new Error("Unexpected CRDT type");
1112
- }
1113
- }
1114
- }
1115
- function deserializeToLson([id, crdt], parentToChildren, doc) {
1116
- switch (crdt.type) {
1117
- case 0 /* OBJECT */: {
1118
- return LiveObject._deserialize([id, crdt], parentToChildren, doc);
1119
- }
1120
- case 1 /* LIST */: {
1121
- return LiveList._deserialize([id, crdt], parentToChildren, doc);
1122
- }
1123
- case 2 /* MAP */: {
1124
- return LiveMap._deserialize([id, crdt], parentToChildren, doc);
1125
- }
1126
- case 3 /* REGISTER */: {
1127
- return crdt.data;
1128
- }
1129
- default: {
1130
- throw new Error("Unexpected CRDT type");
1131
- }
1132
- }
1133
- }
1134
- function isLiveStructure(value) {
1135
- return isLiveList(value) || isLiveMap(value) || isLiveObject(value);
1136
- }
1137
- function isLiveNode(value) {
1138
- return isLiveStructure(value) || isLiveRegister(value);
1139
- }
1140
- function isLiveList(value) {
1141
- return value instanceof LiveList;
1142
- }
1143
- function isLiveMap(value) {
1144
- return value instanceof LiveMap;
1145
- }
1146
- function isLiveObject(value) {
1147
- return value instanceof LiveObject;
1148
- }
1149
- function isLiveRegister(value) {
1150
- return value instanceof LiveRegister;
1151
- }
1152
- function liveNodeToLson(obj) {
1153
- if (obj instanceof LiveRegister) {
1154
- return obj.data;
1155
- } else if (obj instanceof LiveList || obj instanceof LiveMap || obj instanceof LiveObject) {
1156
- return obj;
1157
- } else {
1158
- return assertNever(obj, "Unknown AbstractCrdt");
1159
- }
1160
- }
1161
- function lsonToLiveNode(value) {
1162
- if (value instanceof LiveObject || value instanceof LiveMap || value instanceof LiveList) {
1163
- return value;
1164
- } else {
1165
- return new LiveRegister(value);
1166
- }
1167
- }
1168
- function getTreesDiffOperations(currentItems, newItems) {
1169
- const ops = [];
1170
- currentItems.forEach((_, id) => {
1171
- if (!newItems.get(id)) {
1172
- ops.push({
1173
- type: 5 /* DELETE_CRDT */,
1174
- id
1175
- });
1176
- }
1177
- });
1178
- newItems.forEach((crdt, id) => {
1179
- const currentCrdt = currentItems.get(id);
1180
- if (currentCrdt) {
1181
- if (crdt.type === 0 /* OBJECT */) {
1182
- if (currentCrdt.type !== 0 /* OBJECT */ || JSON.stringify(crdt.data) !== JSON.stringify(currentCrdt.data)) {
1183
- ops.push({
1184
- type: 3 /* UPDATE_OBJECT */,
1185
- id,
1186
- data: crdt.data
1187
- });
1188
- }
1189
- }
1190
- if (crdt.parentKey !== currentCrdt.parentKey) {
1191
- ops.push({
1192
- type: 1 /* SET_PARENT_KEY */,
1193
- id,
1194
- parentKey: nn(crdt.parentKey, "Parent key must not be missing")
1195
- });
1196
- }
1197
- } else {
1198
- switch (crdt.type) {
1199
- case 3 /* REGISTER */:
1200
- ops.push({
1201
- type: 8 /* CREATE_REGISTER */,
1202
- id,
1203
- parentId: crdt.parentId,
1204
- parentKey: crdt.parentKey,
1205
- data: crdt.data
1206
- });
1207
- break;
1208
- case 1 /* LIST */:
1209
- ops.push({
1210
- type: 2 /* CREATE_LIST */,
1211
- id,
1212
- parentId: crdt.parentId,
1213
- parentKey: crdt.parentKey
1214
- });
1215
- break;
1216
- case 0 /* OBJECT */:
1217
- ops.push(
1218
- crdt.parentId ? {
1219
- type: 4 /* CREATE_OBJECT */,
1220
- id,
1221
- parentId: crdt.parentId,
1222
- parentKey: crdt.parentKey,
1223
- data: crdt.data
1224
- } : { type: 4 /* CREATE_OBJECT */, id, data: crdt.data }
1225
- );
1226
- break;
1227
- case 2 /* MAP */:
1228
- ops.push({
1229
- type: 7 /* CREATE_MAP */,
1230
- id,
1231
- parentId: crdt.parentId,
1232
- parentKey: crdt.parentKey
1233
- });
1234
- break;
1235
- }
1236
- }
1237
- });
1238
- return ops;
1239
- }
1240
- function mergeObjectStorageUpdates(first, second) {
1241
- const updates = first.updates;
1242
- for (const [key, value] of entries(second.updates)) {
1243
- updates[key] = value;
1244
- }
1245
- return {
1246
- ...second,
1247
- updates
1248
- };
1249
- }
1250
- function mergeMapStorageUpdates(first, second) {
1251
- const updates = first.updates;
1252
- for (const [key, value] of entries(second.updates)) {
1253
- updates[key] = value;
1254
- }
1255
- return {
1256
- ...second,
1257
- updates
1258
- };
1259
- }
1260
- function mergeListStorageUpdates(first, second) {
1261
- const updates = first.updates;
1262
- return {
1263
- ...second,
1264
- updates: updates.concat(second.updates)
1265
- };
1266
- }
1267
- function mergeStorageUpdates(first, second) {
1268
- if (!first) {
1269
- return second;
1270
- }
1271
- if (first.type === "LiveObject" && second.type === "LiveObject") {
1272
- return mergeObjectStorageUpdates(first, second);
1273
- } else if (first.type === "LiveMap" && second.type === "LiveMap") {
1274
- return mergeMapStorageUpdates(first, second);
1275
- } else if (first.type === "LiveList" && second.type === "LiveList") {
1276
- return mergeListStorageUpdates(first, second);
1277
- } else {
1278
- }
1279
- return second;
1280
- }
1281
- function isPlain(value) {
1282
- const type = typeof value;
1283
- return value === void 0 || value === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(value) || isPlainObject(value);
1284
- }
1285
- function isPlainObject(blob) {
1286
- return blob !== null && typeof blob === "object" && Object.prototype.toString.call(blob) === "[object Object]";
1287
- }
1288
- function findNonSerializableValue(value, path = "") {
1289
- if (!isPlain) {
1290
- return {
1291
- path: path || "root",
1292
- value
1293
- };
1294
- }
1295
- if (typeof value !== "object" || value === null) {
1296
- return false;
1297
- }
1298
- for (const [key, nestedValue] of Object.entries(value)) {
1299
- const nestedPath = path ? path + "." + key : key;
1300
- if (!isPlain(nestedValue)) {
1301
- return {
1302
- path: nestedPath,
1303
- value: nestedValue
1304
- };
1305
- }
1306
- if (typeof nestedValue === "object") {
1307
- const nonSerializableNestedValue = findNonSerializableValue(
1308
- nestedValue,
1309
- nestedPath
1310
- );
1311
- if (nonSerializableNestedValue) {
1312
- return nonSerializableNestedValue;
1313
- }
1314
- }
1315
- }
1316
- return false;
1317
- }
1318
- function fromEntries(iterable) {
1319
- const obj = {};
1320
- for (const [key, val] of iterable) {
1321
- obj[key] = val;
1322
- }
1323
- return obj;
1324
- }
1325
- function entries(obj) {
1326
- return Object.entries(obj);
1327
- }
1328
- function tryParseJson(rawMessage) {
1329
- try {
1330
- return JSON.parse(rawMessage);
1331
- } catch (e) {
1332
- return void 0;
1333
- }
1334
- }
1335
- function b64decode(b64value) {
1336
- try {
1337
- const formattedValue = b64value.replace(/-/g, "+").replace(/_/g, "/");
1338
- const decodedValue = decodeURIComponent(
1339
- atob(formattedValue).split("").map(function(c) {
1340
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
1341
- }).join("")
1342
- );
1343
- return decodedValue;
1344
- } catch (err) {
1345
- return atob(b64value);
1346
- }
1347
- }
1348
-
1349
- // src/LiveList.ts
1350
- function compareNodePosition(itemA, itemB) {
1351
- return comparePosition(
1352
- itemA._getParentKeyOrThrow(),
1353
- itemB._getParentKeyOrThrow()
1354
- );
1355
- }
1356
- var LiveList = class extends AbstractCrdt {
1357
- constructor(items = []) {
1358
- super();
1359
- this._items = [];
1360
- this._implicitlyDeletedItems = /* @__PURE__ */ new Set();
1361
- this._unacknowledgedSets = /* @__PURE__ */ new Map();
1362
- let position = void 0;
1363
- for (let i = 0; i < items.length; i++) {
1364
- const newPosition = makePosition(position);
1365
- const item = lsonToLiveNode(items[i]);
1366
- item._setParentLink(this, newPosition);
1367
- this._items.push(item);
1368
- position = newPosition;
1369
- }
1370
- }
1371
- static _deserialize([id], parentToChildren, doc) {
1372
- const list = new LiveList();
1373
- list._attach(id, doc);
1374
- const children = parentToChildren.get(id);
1375
- if (children == null) {
1376
- return list;
1377
- }
1378
- for (const [id2, crdt] of children) {
1379
- const child = deserialize([id2, crdt], parentToChildren, doc);
1380
- child._setParentLink(list, crdt.parentKey);
1381
- list._insertAndSort(child);
1382
- }
1383
- return list;
1384
- }
1385
- _serialize(parentId, parentKey, doc) {
1386
- if (this._id == null) {
1387
- throw new Error("Cannot serialize item is not attached");
1388
- }
1389
- const ops = [];
1390
- const op = {
1391
- id: this._id,
1392
- opId: doc?.generateOpId(),
1393
- type: 2 /* CREATE_LIST */,
1394
- parentId,
1395
- parentKey
1396
- };
1397
- ops.push(op);
1398
- for (const item of this._items) {
1399
- ops.push(...item._serialize(this._id, item._getParentKeyOrThrow(), doc));
1400
- }
1401
- return ops;
1402
- }
1403
- _insertAndSort(item) {
1404
- this._items.push(item);
1405
- this._sortItems();
1406
- }
1407
- _sortItems() {
1408
- this._items.sort(compareNodePosition);
1409
- }
1410
- _indexOfPosition(position) {
1411
- return this._items.findIndex(
1412
- (item) => item._getParentKeyOrThrow() === position
1413
- );
1414
- }
1415
- _attach(id, doc) {
1416
- super._attach(id, doc);
1417
- for (const item of this._items) {
1418
- item._attach(doc.generateId(), doc);
1419
- }
1420
- }
1421
- _detach() {
1422
- super._detach();
1423
- for (const item of this._items) {
1424
- item._detach();
1425
- }
1426
- }
1427
- _applySetRemote(op) {
1428
- if (this._doc == null) {
1429
- throw new Error("Can't attach child if doc is not present");
1430
- }
1431
- const { id, parentKey: key } = op;
1432
- const child = creationOpToLiveNode(op);
1433
- child._attach(id, this._doc);
1434
- child._setParentLink(this, key);
1435
- const deletedId = op.deletedId;
1436
- const indexOfItemWithSamePosition = this._indexOfPosition(key);
1437
- if (indexOfItemWithSamePosition !== -1) {
1438
- const itemWithSamePosition = this._items[indexOfItemWithSamePosition];
1439
- if (itemWithSamePosition._id === deletedId) {
1440
- itemWithSamePosition._detach();
1441
- this._items[indexOfItemWithSamePosition] = child;
1442
- return {
1443
- modified: makeUpdate(this, [
1444
- setDelta(indexOfItemWithSamePosition, child)
1445
- ]),
1446
- reverse: []
1447
- };
1448
- } else {
1449
- this._implicitlyDeletedItems.add(itemWithSamePosition);
1450
- this._items[indexOfItemWithSamePosition] = child;
1451
- const delta = [
1452
- setDelta(indexOfItemWithSamePosition, child)
1453
- ];
1454
- const deleteDelta2 = this._detachItemAssociatedToSetOperation(
1455
- op.deletedId
1456
- );
1457
- if (deleteDelta2) {
1458
- delta.push(deleteDelta2);
1459
- }
1460
- return {
1461
- modified: makeUpdate(this, delta),
1462
- reverse: []
1463
- };
1464
- }
1465
- } else {
1466
- const updates = [];
1467
- const deleteDelta2 = this._detachItemAssociatedToSetOperation(
1468
- op.deletedId
1469
- );
1470
- if (deleteDelta2) {
1471
- updates.push(deleteDelta2);
1472
- }
1473
- this._insertAndSort(child);
1474
- updates.push(insertDelta(this._indexOfPosition(key), child));
1475
- return {
1476
- reverse: [],
1477
- modified: makeUpdate(this, updates)
1478
- };
1479
- }
1480
- }
1481
- _applySetAck(op) {
1482
- if (this._doc == null) {
1483
- throw new Error("Can't attach child if doc is not present");
1484
- }
1485
- const delta = [];
1486
- const deletedDelta = this._detachItemAssociatedToSetOperation(op.deletedId);
1487
- if (deletedDelta) {
1488
- delta.push(deletedDelta);
1489
- }
1490
- const unacknowledgedOpId = this._unacknowledgedSets.get(op.parentKey);
1491
- if (unacknowledgedOpId != null) {
1492
- if (unacknowledgedOpId !== op.opId) {
1493
- return delta.length === 0 ? { modified: false } : { modified: makeUpdate(this, delta), reverse: [] };
1494
- } else {
1495
- this._unacknowledgedSets.delete(op.parentKey);
1496
- }
1497
- }
1498
- const indexOfItemWithSamePosition = this._indexOfPosition(op.parentKey);
1499
- const existingItem = this._items.find((item) => item._id === op.id);
1500
- if (existingItem != null) {
1501
- if (existingItem._parentKey === op.parentKey) {
1502
- return {
1503
- modified: delta.length > 0 ? makeUpdate(this, delta) : false,
1504
- reverse: []
1505
- };
1506
- }
1507
- if (indexOfItemWithSamePosition !== -1) {
1508
- this._implicitlyDeletedItems.add(
1509
- this._items[indexOfItemWithSamePosition]
1510
- );
1511
- this._items.splice(indexOfItemWithSamePosition, 1);
1512
- delta.push(deleteDelta(indexOfItemWithSamePosition));
1513
- }
1514
- const previousIndex = this._items.indexOf(existingItem);
1515
- existingItem._setParentLink(this, op.parentKey);
1516
- this._sortItems();
1517
- const newIndex = this._items.indexOf(existingItem);
1518
- if (newIndex !== previousIndex) {
1519
- delta.push(moveDelta(previousIndex, newIndex, existingItem));
1520
- }
1521
- return {
1522
- modified: delta.length > 0 ? makeUpdate(this, delta) : false,
1523
- reverse: []
1524
- };
1525
- } else {
1526
- const orphan = this._doc.getItem(op.id);
1527
- if (orphan && this._implicitlyDeletedItems.has(orphan)) {
1528
- orphan._setParentLink(this, op.parentKey);
1529
- this._implicitlyDeletedItems.delete(orphan);
1530
- this._insertAndSort(orphan);
1531
- const recreatedItemIndex = this._items.indexOf(orphan);
1532
- return {
1533
- modified: makeUpdate(this, [
1534
- indexOfItemWithSamePosition === -1 ? insertDelta(recreatedItemIndex, orphan) : setDelta(recreatedItemIndex, orphan),
1535
- ...delta
1536
- ]),
1537
- reverse: []
1538
- };
1539
- } else {
1540
- if (indexOfItemWithSamePosition !== -1) {
1541
- this._items.splice(indexOfItemWithSamePosition, 1);
1542
- }
1543
- const { newItem, newIndex } = this._createAttachItemAndSort(
1544
- op,
1545
- op.parentKey
1546
- );
1547
- return {
1548
- modified: makeUpdate(this, [
1549
- indexOfItemWithSamePosition === -1 ? insertDelta(newIndex, newItem) : setDelta(newIndex, newItem),
1550
- ...delta
1551
- ]),
1552
- reverse: []
1553
- };
1554
- }
1555
- }
1556
- }
1557
- _detachItemAssociatedToSetOperation(deletedId) {
1558
- if (deletedId == null || this._doc == null) {
1559
- return null;
1560
- }
1561
- const deletedItem = this._doc.getItem(deletedId);
1562
- if (deletedItem == null) {
1563
- return null;
1564
- }
1565
- const result = this._detachChild(deletedItem);
1566
- if (result.modified === false) {
1567
- return null;
1568
- }
1569
- return result.modified.updates[0];
1570
- }
1571
- _applyRemoteInsert(op) {
1572
- if (this._doc == null) {
1573
- throw new Error("Can't attach child if doc is not present");
1574
- }
1575
- const key = op.parentKey;
1576
- const existingItemIndex = this._indexOfPosition(key);
1577
- if (existingItemIndex !== -1) {
1578
- this._shiftItemPosition(existingItemIndex, key);
1579
- }
1580
- const { newItem, newIndex } = this._createAttachItemAndSort(op, key);
1581
- return {
1582
- modified: makeUpdate(this, [insertDelta(newIndex, newItem)]),
1583
- reverse: []
1584
- };
1585
- }
1586
- _applyInsertAck(op) {
1587
- const existingItem = this._items.find((item) => item._id === op.id);
1588
- const key = op.parentKey;
1589
- const itemIndexAtPosition = this._indexOfPosition(key);
1590
- if (existingItem) {
1591
- if (existingItem._parentKey === key) {
1592
- return {
1593
- modified: false
1594
- };
1595
- } else {
1596
- const oldPositionIndex = this._items.indexOf(existingItem);
1597
- if (itemIndexAtPosition !== -1) {
1598
- this._shiftItemPosition(itemIndexAtPosition, key);
1599
- }
1600
- existingItem._setParentLink(this, key);
1601
- this._sortItems();
1602
- const newIndex = this._indexOfPosition(key);
1603
- if (newIndex === oldPositionIndex) {
1604
- return { modified: false };
1605
- }
1606
- return {
1607
- modified: makeUpdate(this, [
1608
- moveDelta(oldPositionIndex, newIndex, existingItem)
1609
- ]),
1610
- reverse: []
1611
- };
1612
- }
1613
- } else {
1614
- const orphan = nn(this._doc).getItem(op.id);
1615
- if (orphan && this._implicitlyDeletedItems.has(orphan)) {
1616
- orphan._setParentLink(this, key);
1617
- this._implicitlyDeletedItems.delete(orphan);
1618
- this._insertAndSort(orphan);
1619
- const newIndex = this._indexOfPosition(key);
1620
- return {
1621
- modified: makeUpdate(this, [insertDelta(newIndex, orphan)]),
1622
- reverse: []
1623
- };
1624
- } else {
1625
- if (itemIndexAtPosition !== -1) {
1626
- this._shiftItemPosition(itemIndexAtPosition, key);
1627
- }
1628
- const { newItem, newIndex } = this._createAttachItemAndSort(op, key);
1629
- return {
1630
- modified: makeUpdate(this, [insertDelta(newIndex, newItem)]),
1631
- reverse: []
1632
- };
1633
- }
1634
- }
1635
- }
1636
- _applyInsertUndoRedo(op) {
1637
- const { id, parentKey: key } = op;
1638
- const child = creationOpToLiveNode(op);
1639
- if (this._doc?.getItem(id) !== void 0) {
1640
- return { modified: false };
1641
- }
1642
- child._attach(id, nn(this._doc));
1643
- child._setParentLink(this, key);
1644
- const existingItemIndex = this._indexOfPosition(key);
1645
- let newKey = key;
1646
- if (existingItemIndex !== -1) {
1647
- const before = this._items[existingItemIndex] ? this._items[existingItemIndex]._getParentKeyOrThrow() : void 0;
1648
- const after = this._items[existingItemIndex + 1] ? this._items[existingItemIndex + 1]._getParentKeyOrThrow() : void 0;
1649
- newKey = makePosition(before, after);
1650
- child._setParentLink(this, newKey);
1651
- }
1652
- this._insertAndSort(child);
1653
- const newIndex = this._indexOfPosition(newKey);
1654
- return {
1655
- modified: makeUpdate(this, [insertDelta(newIndex, child)]),
1656
- reverse: [{ type: 5 /* DELETE_CRDT */, id }]
1657
- };
1658
- }
1659
- _applySetUndoRedo(op) {
1660
- const { id, parentKey: key } = op;
1661
- const child = creationOpToLiveNode(op);
1662
- if (this._doc?.getItem(id) !== void 0) {
1663
- return { modified: false };
1664
- }
1665
- this._unacknowledgedSets.set(key, nn(op.opId));
1666
- const indexOfItemWithSameKey = this._indexOfPosition(key);
1667
- child._attach(id, nn(this._doc));
1668
- child._setParentLink(this, key);
1669
- const newKey = key;
1670
- if (indexOfItemWithSameKey !== -1) {
1671
- const existingItem = this._items[indexOfItemWithSameKey];
1672
- existingItem._detach();
1673
- this._items[indexOfItemWithSameKey] = child;
1674
- const reverse = existingItem._serialize(nn(this._id), key, this._doc);
1675
- addIntentAndDeletedIdToOperation(reverse, op.id);
1676
- const delta = [setDelta(indexOfItemWithSameKey, child)];
1677
- const deletedDelta = this._detachItemAssociatedToSetOperation(
1678
- op.deletedId
1679
- );
1680
- if (deletedDelta) {
1681
- delta.push(deletedDelta);
1682
- }
1683
- return {
1684
- modified: makeUpdate(this, delta),
1685
- reverse
1686
- };
1687
- } else {
1688
- this._insertAndSort(child);
1689
- this._detachItemAssociatedToSetOperation(op.deletedId);
1690
- const newIndex = this._indexOfPosition(newKey);
1691
- return {
1692
- reverse: [{ type: 5 /* DELETE_CRDT */, id }],
1693
- modified: makeUpdate(this, [insertDelta(newIndex, child)])
1694
- };
1695
- }
1696
- }
1697
- _attachChild(op, source) {
1698
- if (this._doc == null) {
1699
- throw new Error("Can't attach child if doc is not present");
1700
- }
1701
- if (op.intent === "set") {
1702
- if (source === 1 /* REMOTE */) {
1703
- return this._applySetRemote(op);
1704
- }
1705
- if (source === 0 /* UNDOREDO_RECONNECT */) {
1706
- return this._applySetUndoRedo(op);
1707
- }
1708
- if (source === 2 /* ACK */) {
1709
- return this._applySetAck(op);
1710
- }
1711
- }
1712
- if (source === 1 /* REMOTE */) {
1713
- return this._applyRemoteInsert(op);
1714
- } else if (source === 2 /* ACK */) {
1715
- return this._applyInsertAck(op);
1716
- } else {
1717
- return this._applyInsertUndoRedo(op);
1718
- }
1719
- }
1720
- _detachChild(child) {
1721
- if (child) {
1722
- const parentKey = nn(child._parentKey);
1723
- const reverse = child._serialize(nn(this._id), parentKey, this._doc);
1724
- const indexToDelete = this._items.indexOf(child);
1725
- if (indexToDelete === -1) {
1726
- return {
1727
- modified: false
1728
- };
1729
- }
1730
- this._items.splice(indexToDelete, 1);
1731
- child._detach();
1732
- return {
1733
- modified: makeUpdate(this, [deleteDelta(indexToDelete)]),
1734
- reverse
1735
- };
1736
- }
1737
- return { modified: false };
1738
- }
1739
- _applySetChildKeyRemote(newKey, child) {
1740
- if (this._implicitlyDeletedItems.has(child)) {
1741
- this._implicitlyDeletedItems.delete(child);
1742
- child._setParentLink(this, newKey);
1743
- this._insertAndSort(child);
1744
- const newIndex = this._items.indexOf(child);
1745
- return {
1746
- modified: makeUpdate(this, [insertDelta(newIndex, child)]),
1747
- reverse: []
1748
- };
1749
- }
1750
- const previousKey = child._parentKey;
1751
- if (newKey === previousKey) {
1752
- return {
1753
- modified: false
1754
- };
1755
- }
1756
- const existingItemIndex = this._indexOfPosition(newKey);
1757
- if (existingItemIndex === -1) {
1758
- const previousIndex = this._items.indexOf(child);
1759
- child._setParentLink(this, newKey);
1760
- this._sortItems();
1761
- const newIndex = this._items.indexOf(child);
1762
- if (newIndex === previousIndex) {
1763
- return {
1764
- modified: false
1765
- };
1766
- }
1767
- return {
1768
- modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
1769
- reverse: []
1770
- };
1771
- } else {
1772
- this._items[existingItemIndex]._setParentLink(
1773
- this,
1774
- makePosition(
1775
- newKey,
1776
- this._items[existingItemIndex + 1]?._getParentKeyOrThrow()
1777
- )
1778
- );
1779
- const previousIndex = this._items.indexOf(child);
1780
- child._setParentLink(this, newKey);
1781
- this._sortItems();
1782
- const newIndex = this._items.indexOf(child);
1783
- if (newIndex === previousIndex) {
1784
- return {
1785
- modified: false
1786
- };
1787
- }
1788
- return {
1789
- modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
1790
- reverse: []
1791
- };
1792
- }
1793
- }
1794
- _applySetChildKeyAck(newKey, child) {
1795
- const previousKey = nn(child._parentKey);
1796
- if (this._implicitlyDeletedItems.has(child)) {
1797
- const existingItemIndex = this._indexOfPosition(newKey);
1798
- this._implicitlyDeletedItems.delete(child);
1799
- if (existingItemIndex !== -1) {
1800
- this._items[existingItemIndex]._setParentLink(
1801
- this,
1802
- makePosition(
1803
- newKey,
1804
- this._items[existingItemIndex + 1]?._getParentKeyOrThrow()
1805
- )
1806
- );
1807
- }
1808
- child._setParentLink(this, newKey);
1809
- this._insertAndSort(child);
1810
- return {
1811
- modified: false
1812
- };
1813
- } else {
1814
- if (newKey === previousKey) {
1815
- return {
1816
- modified: false
1817
- };
1818
- }
1819
- const previousIndex = this._items.indexOf(child);
1820
- const existingItemIndex = this._indexOfPosition(newKey);
1821
- if (existingItemIndex !== -1) {
1822
- this._items[existingItemIndex]._setParentLink(
1823
- this,
1824
- makePosition(
1825
- newKey,
1826
- this._items[existingItemIndex + 1]?._getParentKeyOrThrow()
1827
- )
1828
- );
1829
- }
1830
- child._setParentLink(this, newKey);
1831
- this._sortItems();
1832
- const newIndex = this._items.indexOf(child);
1833
- if (previousIndex === newIndex) {
1834
- return {
1835
- modified: false
1836
- };
1837
- } else {
1838
- return {
1839
- modified: makeUpdate(this, [
1840
- moveDelta(previousIndex, newIndex, child)
1841
- ]),
1842
- reverse: []
1843
- };
1844
- }
1845
- }
1846
- }
1847
- _applySetChildKeyUndoRedo(newKey, child) {
1848
- const previousKey = nn(child._parentKey);
1849
- const previousIndex = this._items.indexOf(child);
1850
- const existingItemIndex = this._indexOfPosition(newKey);
1851
- if (existingItemIndex !== -1) {
1852
- this._items[existingItemIndex]._setParentLink(
1853
- this,
1854
- makePosition(
1855
- newKey,
1856
- this._items[existingItemIndex + 1]?._getParentKeyOrThrow()
1857
- )
1858
- );
1859
- }
1860
- child._setParentLink(this, newKey);
1861
- this._sortItems();
1862
- const newIndex = this._items.indexOf(child);
1863
- if (previousIndex === newIndex) {
1864
- return {
1865
- modified: false
1866
- };
1867
- }
1868
- return {
1869
- modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
1870
- reverse: [
1871
- {
1872
- type: 1 /* SET_PARENT_KEY */,
1873
- id: nn(child._id),
1874
- parentKey: previousKey
1875
- }
1876
- ]
1877
- };
1878
- }
1879
- _setChildKey(newKey, child, source) {
1880
- if (source === 1 /* REMOTE */) {
1881
- return this._applySetChildKeyRemote(newKey, child);
1882
- } else if (source === 2 /* ACK */) {
1883
- return this._applySetChildKeyAck(newKey, child);
1884
- } else {
1885
- return this._applySetChildKeyUndoRedo(newKey, child);
1886
- }
1887
- }
1888
- _apply(op, isLocal) {
1889
- return super._apply(op, isLocal);
1890
- }
1891
- _toSerializedCrdt() {
1892
- if (this.parent.type !== "HasParent") {
1893
- throw new Error("Cannot serialize LiveList if parent is missing");
1894
- }
1895
- return {
1896
- type: 1 /* LIST */,
1897
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
1898
- parentKey: this.parent.key
1899
- };
1900
- }
1901
- get length() {
1902
- return this._items.length;
1903
- }
1904
- push(element) {
1905
- return this.insert(element, this.length);
1906
- }
1907
- insert(element, index) {
1908
- if (index < 0 || index > this._items.length) {
1909
- throw new Error(
1910
- `Cannot insert list item at index "${index}". index should be between 0 and ${this._items.length}`
1911
- );
1912
- }
1913
- const before = this._items[index - 1] ? this._items[index - 1]._getParentKeyOrThrow() : void 0;
1914
- const after = this._items[index] ? this._items[index]._getParentKeyOrThrow() : void 0;
1915
- const position = makePosition(before, after);
1916
- const value = lsonToLiveNode(element);
1917
- value._setParentLink(this, position);
1918
- this._insertAndSort(value);
1919
- if (this._doc && this._id) {
1920
- const id = this._doc.generateId();
1921
- value._attach(id, this._doc);
1922
- this._doc.dispatch(
1923
- value._serialize(this._id, position, this._doc),
1924
- [{ type: 5 /* DELETE_CRDT */, id }],
1925
- /* @__PURE__ */ new Map([
1926
- [this._id, makeUpdate(this, [insertDelta(index, value)])]
1927
- ])
1928
- );
1929
- }
1930
- }
1931
- move(index, targetIndex) {
1932
- if (targetIndex < 0) {
1933
- throw new Error("targetIndex cannot be less than 0");
1934
- }
1935
- if (targetIndex >= this._items.length) {
1936
- throw new Error(
1937
- "targetIndex cannot be greater or equal than the list length"
1938
- );
1939
- }
1940
- if (index < 0) {
1941
- throw new Error("index cannot be less than 0");
1942
- }
1943
- if (index >= this._items.length) {
1944
- throw new Error("index cannot be greater or equal than the list length");
1945
- }
1946
- let beforePosition = null;
1947
- let afterPosition = null;
1948
- if (index < targetIndex) {
1949
- afterPosition = targetIndex === this._items.length - 1 ? void 0 : this._items[targetIndex + 1]._getParentKeyOrThrow();
1950
- beforePosition = this._items[targetIndex]._getParentKeyOrThrow();
1951
- } else {
1952
- afterPosition = this._items[targetIndex]._getParentKeyOrThrow();
1953
- beforePosition = targetIndex === 0 ? void 0 : this._items[targetIndex - 1]._getParentKeyOrThrow();
1954
- }
1955
- const position = makePosition(beforePosition, afterPosition);
1956
- const item = this._items[index];
1957
- const previousPosition = item._getParentKeyOrThrow();
1958
- item._setParentLink(this, position);
1959
- this._sortItems();
1960
- if (this._doc && this._id) {
1961
- const storageUpdates = /* @__PURE__ */ new Map([
1962
- [this._id, makeUpdate(this, [moveDelta(index, targetIndex, item)])]
1963
- ]);
1964
- this._doc.dispatch(
1965
- [
1966
- {
1967
- type: 1 /* SET_PARENT_KEY */,
1968
- id: nn(item._id),
1969
- opId: this._doc.generateOpId(),
1970
- parentKey: position
1971
- }
1972
- ],
1973
- [
1974
- {
1975
- type: 1 /* SET_PARENT_KEY */,
1976
- id: nn(item._id),
1977
- parentKey: previousPosition
1978
- }
1979
- ],
1980
- storageUpdates
1981
- );
1982
- }
1983
- }
1984
- delete(index) {
1985
- if (index < 0 || index >= this._items.length) {
1986
- throw new Error(
1987
- `Cannot delete list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
1988
- );
1989
- }
1990
- const item = this._items[index];
1991
- item._detach();
1992
- this._items.splice(index, 1);
1993
- if (this._doc) {
1994
- const childRecordId = item._id;
1995
- if (childRecordId) {
1996
- const storageUpdates = /* @__PURE__ */ new Map();
1997
- storageUpdates.set(
1998
- nn(this._id),
1999
- makeUpdate(this, [deleteDelta(index)])
2000
- );
2001
- this._doc.dispatch(
2002
- [
2003
- {
2004
- id: childRecordId,
2005
- opId: this._doc.generateOpId(),
2006
- type: 5 /* DELETE_CRDT */
2007
- }
2008
- ],
2009
- item._serialize(nn(this._id), item._getParentKeyOrThrow()),
2010
- storageUpdates
2011
- );
2012
- }
2013
- }
2014
- }
2015
- clear() {
2016
- if (this._doc) {
2017
- const ops = [];
2018
- const reverseOps = [];
2019
- const updateDelta = [];
2020
- for (const item of this._items) {
2021
- item._detach();
2022
- const childId = item._id;
2023
- if (childId) {
2024
- ops.push({
2025
- type: 5 /* DELETE_CRDT */,
2026
- id: childId,
2027
- opId: this._doc.generateOpId()
2028
- });
2029
- reverseOps.push(
2030
- ...item._serialize(nn(this._id), item._getParentKeyOrThrow())
2031
- );
2032
- updateDelta.push(deleteDelta(0));
2033
- }
2034
- }
2035
- this._items = [];
2036
- const storageUpdates = /* @__PURE__ */ new Map();
2037
- storageUpdates.set(nn(this._id), makeUpdate(this, updateDelta));
2038
- this._doc.dispatch(ops, reverseOps, storageUpdates);
2039
- } else {
2040
- for (const item of this._items) {
2041
- item._detach();
2042
- }
2043
- this._items = [];
2044
- }
2045
- }
2046
- set(index, item) {
2047
- if (index < 0 || index >= this._items.length) {
2048
- throw new Error(
2049
- `Cannot set list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
2050
- );
2051
- }
2052
- const existingItem = this._items[index];
2053
- const position = existingItem._getParentKeyOrThrow();
2054
- const existingId = existingItem._id;
2055
- existingItem._detach();
2056
- const value = lsonToLiveNode(item);
2057
- value._setParentLink(this, position);
2058
- this._items[index] = value;
2059
- if (this._doc && this._id) {
2060
- const id = this._doc.generateId();
2061
- value._attach(id, this._doc);
2062
- const storageUpdates = /* @__PURE__ */ new Map();
2063
- storageUpdates.set(this._id, makeUpdate(this, [setDelta(index, value)]));
2064
- const ops = value._serialize(this._id, position, this._doc);
2065
- addIntentAndDeletedIdToOperation(ops, existingId);
2066
- this._unacknowledgedSets.set(position, nn(ops[0].opId));
2067
- const reverseOps = existingItem._serialize(this._id, position, void 0);
2068
- addIntentAndDeletedIdToOperation(reverseOps, id);
2069
- this._doc.dispatch(ops, reverseOps, storageUpdates);
2070
- }
2071
- }
2072
- toArray() {
2073
- return this._items.map(
2074
- (entry) => liveNodeToLson(entry)
2075
- );
2076
- }
2077
- every(predicate) {
2078
- return this.toArray().every(predicate);
2079
- }
2080
- filter(predicate) {
2081
- return this.toArray().filter(predicate);
2082
- }
2083
- find(predicate) {
2084
- return this.toArray().find(predicate);
2085
- }
2086
- findIndex(predicate) {
2087
- return this.toArray().findIndex(predicate);
2088
- }
2089
- forEach(callbackfn) {
2090
- return this.toArray().forEach(callbackfn);
2091
- }
2092
- get(index) {
2093
- if (index < 0 || index >= this._items.length) {
2094
- return void 0;
2095
- }
2096
- return liveNodeToLson(this._items[index]);
2097
- }
2098
- indexOf(searchElement, fromIndex) {
2099
- return this.toArray().indexOf(searchElement, fromIndex);
2100
- }
2101
- lastIndexOf(searchElement, fromIndex) {
2102
- return this.toArray().lastIndexOf(searchElement, fromIndex);
2103
- }
2104
- map(callback) {
2105
- return this._items.map(
2106
- (entry, i) => callback(
2107
- liveNodeToLson(entry),
2108
- i
2109
- )
2110
- );
2111
- }
2112
- some(predicate) {
2113
- return this.toArray().some(predicate);
2114
- }
2115
- [Symbol.iterator]() {
2116
- return new LiveListIterator(this._items);
2117
- }
2118
- _createAttachItemAndSort(op, key) {
2119
- const newItem = creationOpToLiveNode(op);
2120
- newItem._attach(op.id, nn(this._doc));
2121
- newItem._setParentLink(this, key);
2122
- this._insertAndSort(newItem);
2123
- const newIndex = this._indexOfPosition(key);
2124
- return { newItem, newIndex };
2125
- }
2126
- _shiftItemPosition(index, key) {
2127
- const shiftedPosition = makePosition(
2128
- key,
2129
- this._items.length > index + 1 ? this._items[index + 1]?._getParentKeyOrThrow() : void 0
2130
- );
2131
- this._items[index]._setParentLink(this, shiftedPosition);
2132
- }
2133
- };
2134
- var LiveListIterator = class {
2135
- constructor(items) {
2136
- this._innerIterator = items[Symbol.iterator]();
2137
- }
2138
- [Symbol.iterator]() {
2139
- return this;
2140
- }
2141
- next() {
2142
- const result = this._innerIterator.next();
2143
- if (result.done) {
2144
- return {
2145
- done: true,
2146
- value: void 0
2147
- };
2148
- }
2149
- const value = liveNodeToLson(result.value);
2150
- return { value };
2151
- }
2152
- };
2153
- function makeUpdate(liveList, deltaUpdates) {
2154
- return {
2155
- node: liveList,
2156
- type: "LiveList",
2157
- updates: deltaUpdates
2158
- };
2159
- }
2160
- function setDelta(index, item) {
2161
- return {
2162
- index,
2163
- type: "set",
2164
- item: item instanceof LiveRegister ? item.data : item
2165
- };
2166
- }
2167
- function deleteDelta(index) {
2168
- return {
2169
- index,
2170
- type: "delete"
2171
- };
2172
- }
2173
- function insertDelta(index, item) {
2174
- return {
2175
- index,
2176
- type: "insert",
2177
- item: item instanceof LiveRegister ? item.data : item
2178
- };
2179
- }
2180
- function moveDelta(previousIndex, index, item) {
2181
- return {
2182
- index,
2183
- type: "move",
2184
- previousIndex,
2185
- item: item instanceof LiveRegister ? item.data : item
2186
- };
2187
- }
2188
- function addIntentAndDeletedIdToOperation(ops, deletedId) {
2189
- if (ops.length === 0) {
2190
- throw new Error(
2191
- "Internal error. Serialized LiveStructure should have at least 1 operation"
2192
- );
2193
- }
2194
- const firstOp = ops[0];
2195
- firstOp.intent = "set";
2196
- firstOp.deletedId = deletedId;
2197
- }
2198
-
2199
- // src/AuthToken.ts
2200
- var SCOPES = [
2201
- "websocket:presence",
2202
- "websocket:storage",
2203
- "room:read",
2204
- "room:write",
2205
- "rooms:read",
2206
- "rooms:write"
2207
- ];
2208
- function hasJwtMeta(data) {
2209
- if (!isPlainObject(data)) {
2210
- return false;
2211
- }
2212
- const { iat, exp } = data;
2213
- return typeof iat === "number" && typeof exp === "number";
2214
- }
2215
- function isTokenExpired(token) {
2216
- const now = Date.now() / 1e3;
2217
- return now > token.exp - 300 || now < token.iat + 300;
2218
- }
2219
- function isScope(value) {
2220
- return SCOPES.includes(value);
2221
- }
2222
- function isStringList(value) {
2223
- return Array.isArray(value) && value.every((i) => typeof i === "string");
2224
- }
2225
- function isAppOnlyAuthToken(data) {
2226
- return typeof data.appId === "string" && data.roomId === void 0 && isStringList(data.scopes);
2227
- }
2228
- function isRoomAuthToken(data) {
2229
- return typeof data.appId === "string" && typeof data.roomId === "string" && typeof data.actor === "number" && (data.id === void 0 || typeof data.id === "string") && isStringList(data.scopes) && (data.maxConnectionsPerRoom === void 0 || typeof data.maxConnectionsPerRoom === "number");
2230
- }
2231
- function isAuthToken(data) {
2232
- return isAppOnlyAuthToken(data) || isRoomAuthToken(data);
2233
- }
2234
- function parseJwtToken(token) {
2235
- const tokenParts = token.split(".");
2236
- if (tokenParts.length !== 3) {
2237
- throw new Error("Authentication error: invalid JWT token");
2238
- }
2239
- const data = tryParseJson(b64decode(tokenParts[1]));
2240
- if (data && hasJwtMeta(data)) {
2241
- return data;
2242
- } else {
2243
- throw new Error("Authentication error: missing JWT metadata");
2244
- }
2245
- }
2246
- function parseRoomAuthToken(tokenString) {
2247
- const data = parseJwtToken(tokenString);
2248
- if (data && isRoomAuthToken(data)) {
2249
- const {
2250
- maxConnections: _legacyField,
2251
- ...token
2252
- } = data;
2253
- return token;
2254
- } else {
2255
- throw new Error(
2256
- "Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback"
2257
- );
2258
- }
2259
- }
2260
-
2261
- // src/types/Json.ts
2262
- function isJsonScalar(data) {
2263
- return data === null || typeof data === "string" || typeof data === "number" || typeof data === "boolean";
2264
- }
2265
- function isJsonArray(data) {
2266
- return Array.isArray(data);
2267
- }
2268
- function isJsonObject(data) {
2269
- return !isJsonScalar(data) && !isJsonArray(data);
2270
- }
2271
-
2272
- export {
2273
- deprecate,
2274
- deprecateIf,
2275
- throwUsageError,
2276
- errorIf,
2277
- assertNever,
2278
- nn,
2279
- ClientMsgCode,
2280
- OpCode,
2281
- CrdtType,
2282
- isRootCrdt,
2283
- isChildCrdt,
2284
- ServerMsgCode,
2285
- isRoomEventName,
2286
- WebsocketCloseCodes,
2287
- LiveRegister,
2288
- makePosition,
2289
- comparePosition,
2290
- LiveList,
2291
- LiveMap,
2292
- LiveObject,
2293
- remove,
2294
- compact,
2295
- isSameNodeOrChildOf,
2296
- isLiveNode,
2297
- isLiveList,
2298
- isLiveObject,
2299
- getTreesDiffOperations,
2300
- mergeStorageUpdates,
2301
- isPlainObject,
2302
- findNonSerializableValue,
2303
- tryParseJson,
2304
- b64decode,
2305
- isTokenExpired,
2306
- isScope,
2307
- isAppOnlyAuthToken,
2308
- isRoomAuthToken,
2309
- isAuthToken,
2310
- parseRoomAuthToken,
2311
- isJsonScalar,
2312
- isJsonArray,
2313
- isJsonObject
2314
- };