@johnhenry/browsermesh-primitives 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/crdt.mjs ADDED
@@ -0,0 +1,919 @@
1
+ /**
2
+ * CRDT (Conflict-free Replicated Data Types) for mesh-primitives.
3
+ *
4
+ * Pure, deterministic, zero-dependency implementations suitable for
5
+ * browser-to-browser state synchronization in BrowserMesh.
6
+ */
7
+
8
+ // ── VectorClock ─────────────────────────────────────────────────────────────
9
+
10
+ /**
11
+ * A vector clock tracks causal ordering across distributed nodes.
12
+ * Each node maintains a monotonically increasing counter.
13
+ */
14
+ export class VectorClock {
15
+ /** @type {Map<string, number>} */
16
+ #entries;
17
+
18
+ /**
19
+ * @param {Map<string, number> | Iterable<[string, number]>} [entries]
20
+ */
21
+ constructor(entries = new Map()) {
22
+ this.#entries = new Map(entries);
23
+ }
24
+
25
+ /**
26
+ * Increment the counter for the given node and return this clock.
27
+ * @param {string} nodeId
28
+ * @returns {VectorClock} this
29
+ */
30
+ increment(nodeId) {
31
+ this.#entries.set(nodeId, (this.#entries.get(nodeId) ?? 0) + 1);
32
+ return this;
33
+ }
34
+
35
+ /**
36
+ * Get the counter value for a node (0 if absent).
37
+ * @param {string} nodeId
38
+ * @returns {number}
39
+ */
40
+ get(nodeId) {
41
+ return this.#entries.get(nodeId) ?? 0;
42
+ }
43
+
44
+ /**
45
+ * Merge with another VectorClock, taking the max of each entry.
46
+ * Returns a new VectorClock.
47
+ * @param {VectorClock} other
48
+ * @returns {VectorClock}
49
+ */
50
+ merge(other) {
51
+ const merged = new Map(this.#entries);
52
+ const otherEntries = other.#entries;
53
+ for (const [nodeId, count] of otherEntries) {
54
+ merged.set(nodeId, Math.max(merged.get(nodeId) ?? 0, count));
55
+ }
56
+ return new VectorClock(merged);
57
+ }
58
+
59
+ /**
60
+ * Compare this clock with another.
61
+ * @param {VectorClock} other
62
+ * @returns {'before' | 'after' | 'concurrent' | 'equal'}
63
+ */
64
+ compare(other) {
65
+ const allKeys = new Set([...this.#entries.keys(), ...other.#entries.keys()]);
66
+ let hasLess = false;
67
+ let hasGreater = false;
68
+
69
+ for (const key of allKeys) {
70
+ const a = this.get(key);
71
+ const b = other.get(key);
72
+ if (a < b) hasLess = true;
73
+ if (a > b) hasGreater = true;
74
+ if (hasLess && hasGreater) return 'concurrent';
75
+ }
76
+
77
+ if (!hasLess && !hasGreater) return 'equal';
78
+ if (hasLess) return 'before';
79
+ return 'after';
80
+ }
81
+
82
+ /**
83
+ * Serialize to a plain object.
84
+ * @returns {Record<string, number>}
85
+ */
86
+ toJSON() {
87
+ const obj = {};
88
+ for (const [k, v] of this.#entries) obj[k] = v;
89
+ return obj;
90
+ }
91
+
92
+ /**
93
+ * Reconstruct from a plain object.
94
+ * @param {Record<string, number>} data
95
+ * @returns {VectorClock}
96
+ */
97
+ static fromJSON(data) {
98
+ return new VectorClock(new Map(Object.entries(data)));
99
+ }
100
+ }
101
+
102
+ // ── LWWRegister ─────────────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * A Last-Writer-Wins Register. Conflicts are resolved by timestamp;
106
+ * ties are broken by nodeId (lexicographic, higher wins).
107
+ */
108
+ export class LWWRegister {
109
+ #value;
110
+ #timestamp;
111
+ #nodeId;
112
+
113
+ /**
114
+ * @param {*} [value=null]
115
+ * @param {number} [timestamp=0]
116
+ * @param {string} [nodeId='']
117
+ */
118
+ constructor(value = null, timestamp = 0, nodeId = '') {
119
+ this.#value = value;
120
+ this.#timestamp = timestamp;
121
+ this.#nodeId = nodeId;
122
+ }
123
+
124
+ /** @returns {*} Current value */
125
+ get value() {
126
+ return this.#value;
127
+ }
128
+
129
+ /**
130
+ * Update the register if the new write is newer.
131
+ * @param {*} value
132
+ * @param {number} timestamp
133
+ * @param {string} nodeId
134
+ */
135
+ set(value, timestamp, nodeId) {
136
+ if (
137
+ timestamp > this.#timestamp ||
138
+ (timestamp === this.#timestamp && nodeId > this.#nodeId)
139
+ ) {
140
+ this.#value = value;
141
+ this.#timestamp = timestamp;
142
+ this.#nodeId = nodeId;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Merge with another LWWRegister, keeping the latest value.
148
+ * Returns a new LWWRegister.
149
+ * @param {LWWRegister} other
150
+ * @returns {LWWRegister}
151
+ */
152
+ merge(other) {
153
+ const otherState = other.state();
154
+ const thisState = this.state();
155
+
156
+ if (
157
+ otherState.timestamp > thisState.timestamp ||
158
+ (otherState.timestamp === thisState.timestamp && otherState.nodeId > thisState.nodeId)
159
+ ) {
160
+ return new LWWRegister(otherState.value, otherState.timestamp, otherState.nodeId);
161
+ }
162
+ return new LWWRegister(thisState.value, thisState.timestamp, thisState.nodeId);
163
+ }
164
+
165
+ /**
166
+ * @returns {{ value: *, timestamp: number, nodeId: string }}
167
+ */
168
+ state() {
169
+ return { value: this.#value, timestamp: this.#timestamp, nodeId: this.#nodeId };
170
+ }
171
+
172
+ toJSON() {
173
+ return { value: this.#value, timestamp: this.#timestamp, nodeId: this.#nodeId };
174
+ }
175
+
176
+ /**
177
+ * @param {{ value: *, timestamp: number, nodeId: string }} data
178
+ * @returns {LWWRegister}
179
+ */
180
+ static fromJSON(data) {
181
+ return new LWWRegister(data.value, data.timestamp, data.nodeId);
182
+ }
183
+ }
184
+
185
+ // ── GCounter ────────────────────────────────────────────────────────────────
186
+
187
+ /**
188
+ * Grow-only counter. Each node maintains its own monotonic counter.
189
+ * The total value is the sum of all per-node counters.
190
+ */
191
+ export class GCounter {
192
+ /** @type {Map<string, number>} */
193
+ #counts;
194
+
195
+ /**
196
+ * @param {Map<string, number> | Iterable<[string, number]>} [counts]
197
+ */
198
+ constructor(counts = new Map()) {
199
+ this.#counts = new Map(counts);
200
+ }
201
+
202
+ /** @returns {number} Sum of all node counters */
203
+ get value() {
204
+ let sum = 0;
205
+ for (const v of this.#counts.values()) sum += v;
206
+ return sum;
207
+ }
208
+
209
+ /**
210
+ * Increment the counter for a node.
211
+ * @param {string} nodeId
212
+ * @param {number} [amount=1]
213
+ */
214
+ increment(nodeId, amount = 1) {
215
+ if (amount < 0) throw new RangeError('GCounter increment amount must be non-negative');
216
+ this.#counts.set(nodeId, (this.#counts.get(nodeId) ?? 0) + amount);
217
+ }
218
+
219
+ /**
220
+ * Merge with another GCounter, taking the max per node.
221
+ * Returns a new GCounter.
222
+ * @param {GCounter} other
223
+ * @returns {GCounter}
224
+ */
225
+ merge(other) {
226
+ const merged = new Map(this.#counts);
227
+ const otherCounts = other.state();
228
+ for (const [nodeId, count] of otherCounts) {
229
+ merged.set(nodeId, Math.max(merged.get(nodeId) ?? 0, count));
230
+ }
231
+ return new GCounter(merged);
232
+ }
233
+
234
+ /**
235
+ * @returns {Map<string, number>} Copy of internal counters
236
+ */
237
+ state() {
238
+ return new Map(this.#counts);
239
+ }
240
+
241
+ toJSON() {
242
+ const obj = {};
243
+ for (const [k, v] of this.#counts) obj[k] = v;
244
+ return obj;
245
+ }
246
+
247
+ /**
248
+ * @param {Record<string, number>} data
249
+ * @returns {GCounter}
250
+ */
251
+ static fromJSON(data) {
252
+ return new GCounter(new Map(Object.entries(data)));
253
+ }
254
+ }
255
+
256
+ // ── PNCounter ───────────────────────────────────────────────────────────────
257
+
258
+ /**
259
+ * Positive-Negative Counter. Composed of two GCounters:
260
+ * one for increments and one for decrements.
261
+ */
262
+ export class PNCounter {
263
+ /** @type {GCounter} */
264
+ #pos;
265
+ /** @type {GCounter} */
266
+ #neg;
267
+
268
+ /**
269
+ * @param {GCounter} [pos]
270
+ * @param {GCounter} [neg]
271
+ */
272
+ constructor(pos = new GCounter(), neg = new GCounter()) {
273
+ this.#pos = pos;
274
+ this.#neg = neg;
275
+ }
276
+
277
+ /** @returns {number} pos.value - neg.value */
278
+ get value() {
279
+ return this.#pos.value - this.#neg.value;
280
+ }
281
+
282
+ /**
283
+ * Increment the counter.
284
+ * @param {string} nodeId
285
+ * @param {number} [amount=1]
286
+ */
287
+ increment(nodeId, amount = 1) {
288
+ this.#pos.increment(nodeId, amount);
289
+ }
290
+
291
+ /**
292
+ * Decrement the counter.
293
+ * @param {string} nodeId
294
+ * @param {number} [amount=1]
295
+ */
296
+ decrement(nodeId, amount = 1) {
297
+ this.#neg.increment(nodeId, amount);
298
+ }
299
+
300
+ /**
301
+ * Merge with another PNCounter.
302
+ * Returns a new PNCounter.
303
+ * @param {PNCounter} other
304
+ * @returns {PNCounter}
305
+ */
306
+ merge(other) {
307
+ const otherState = other.state();
308
+ return new PNCounter(this.#pos.merge(otherState.pos), this.#neg.merge(otherState.neg));
309
+ }
310
+
311
+ /**
312
+ * @returns {{ pos: GCounter, neg: GCounter }}
313
+ */
314
+ state() {
315
+ return { pos: this.#pos, neg: this.#neg };
316
+ }
317
+
318
+ toJSON() {
319
+ return { pos: this.#pos.toJSON(), neg: this.#neg.toJSON() };
320
+ }
321
+
322
+ /**
323
+ * @param {{ pos: Record<string, number>, neg: Record<string, number> }} data
324
+ * @returns {PNCounter}
325
+ */
326
+ static fromJSON(data) {
327
+ return new PNCounter(GCounter.fromJSON(data.pos), GCounter.fromJSON(data.neg));
328
+ }
329
+ }
330
+
331
+ // ── ORSet ───────────────────────────────────────────────────────────────────
332
+
333
+ /**
334
+ * Observed-Remove Set.
335
+ * Each add generates a unique tag; remove tombstones all current tags for an element.
336
+ * Concurrent add + remove results in the element being present (add wins).
337
+ */
338
+ export class ORSet {
339
+ /** @type {Map<*, Set<string>>} element -> set of unique tags */
340
+ #elements;
341
+ /** @type {Set<string>} removed tags */
342
+ #tombstones;
343
+ /** @type {number} auto-incrementing tag counter */
344
+ #counter;
345
+
346
+ constructor() {
347
+ this.#elements = new Map();
348
+ this.#tombstones = new Set();
349
+ this.#counter = 0;
350
+ }
351
+
352
+ /** @returns {Set<*>} Current live elements */
353
+ get value() {
354
+ const result = new Set();
355
+ for (const [element, tags] of this.#elements) {
356
+ for (const tag of tags) {
357
+ if (!this.#tombstones.has(tag)) {
358
+ result.add(element);
359
+ break;
360
+ }
361
+ }
362
+ }
363
+ return result;
364
+ }
365
+
366
+ /**
367
+ * Add an element with a unique tag.
368
+ * @param {*} element
369
+ * @param {string} nodeId
370
+ */
371
+ add(element, nodeId) {
372
+ const tag = `${nodeId}:${this.#counter++}`;
373
+ if (!this.#elements.has(element)) {
374
+ this.#elements.set(element, new Set());
375
+ }
376
+ this.#elements.get(element).add(tag);
377
+ }
378
+
379
+ /**
380
+ * Remove an element by tombstoning all its current tags.
381
+ * @param {*} element
382
+ */
383
+ remove(element) {
384
+ const tags = this.#elements.get(element);
385
+ if (tags) {
386
+ for (const tag of tags) {
387
+ this.#tombstones.add(tag);
388
+ }
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Check if element is currently in the set.
394
+ * @param {*} element
395
+ * @returns {boolean}
396
+ */
397
+ has(element) {
398
+ const tags = this.#elements.get(element);
399
+ if (!tags) return false;
400
+ for (const tag of tags) {
401
+ if (!this.#tombstones.has(tag)) return true;
402
+ }
403
+ return false;
404
+ }
405
+
406
+ /**
407
+ * Merge with another ORSet.
408
+ * Union of elements minus union of tombstones.
409
+ * Returns a new ORSet.
410
+ * @param {ORSet} other
411
+ * @returns {ORSet}
412
+ */
413
+ merge(other) {
414
+ const otherState = other.state();
415
+ const merged = new ORSet();
416
+
417
+ // Union all elements and their tags
418
+ const allElements = new Map();
419
+ for (const [element, tags] of this.#elements) {
420
+ allElements.set(element, new Set(tags));
421
+ }
422
+ for (const [element, tags] of otherState.elements) {
423
+ if (!allElements.has(element)) {
424
+ allElements.set(element, new Set());
425
+ }
426
+ const existing = allElements.get(element);
427
+ for (const tag of tags) {
428
+ existing.add(tag);
429
+ }
430
+ }
431
+
432
+ // Union all tombstones
433
+ const allTombstones = new Set([...this.#tombstones, ...otherState.tombstones]);
434
+
435
+ // Set internal state on the merged ORSet via its _setInternal method
436
+ merged._setInternal(allElements, allTombstones);
437
+ return merged;
438
+ }
439
+
440
+ /**
441
+ * Internal method to set state during merge/fromJSON.
442
+ * @param {Map<*, Set<string>>} elements
443
+ * @param {Set<string>} tombstones
444
+ */
445
+ _setInternal(elements, tombstones) {
446
+ this.#elements = elements;
447
+ this.#tombstones = tombstones;
448
+ // Compute max counter from existing tags
449
+ let maxCounter = 0;
450
+ for (const tags of elements.values()) {
451
+ for (const tag of tags) {
452
+ const parts = tag.split(':');
453
+ const num = parseInt(parts[parts.length - 1], 10);
454
+ if (!isNaN(num) && num >= maxCounter) maxCounter = num + 1;
455
+ }
456
+ }
457
+ this.#counter = maxCounter;
458
+ }
459
+
460
+ /**
461
+ * @returns {{ elements: Map<*, Set<string>>, tombstones: Set<string> }}
462
+ */
463
+ state() {
464
+ // Return deep copies
465
+ const elements = new Map();
466
+ for (const [k, v] of this.#elements) {
467
+ elements.set(k, new Set(v));
468
+ }
469
+ return { elements, tombstones: new Set(this.#tombstones) };
470
+ }
471
+
472
+ toJSON() {
473
+ const elements = [];
474
+ for (const [element, tags] of this.#elements) {
475
+ elements.push({ element, tags: [...tags] });
476
+ }
477
+ return { elements, tombstones: [...this.#tombstones] };
478
+ }
479
+
480
+ /**
481
+ * @param {{ elements: Array<{ element: *, tags: string[] }>, tombstones: string[] }} data
482
+ * @returns {ORSet}
483
+ */
484
+ static fromJSON(data) {
485
+ const set = new ORSet();
486
+ const elements = new Map();
487
+ for (const { element, tags } of data.elements) {
488
+ elements.set(element, new Set(tags));
489
+ }
490
+ set._setInternal(elements, new Set(data.tombstones));
491
+ return set;
492
+ }
493
+ }
494
+
495
+ // ── RGA ─────────────────────────────────────────────────────────────────────
496
+
497
+ /**
498
+ * Replicated Growable Array.
499
+ * An ordered sequence that supports concurrent insertions via unique node IDs.
500
+ * Deleted elements are tombstoned.
501
+ */
502
+ export class RGA {
503
+ /** @type {Array<{ id: string, value: *, deleted: boolean }>} */
504
+ #nodes;
505
+ /** @type {VectorClock} */
506
+ #vclock;
507
+
508
+ constructor() {
509
+ this.#nodes = [];
510
+ this.#vclock = new VectorClock();
511
+ }
512
+
513
+ /** @returns {Array<*>} Non-deleted values in order */
514
+ get value() {
515
+ return this.#nodes.filter(n => !n.deleted).map(n => n.value);
516
+ }
517
+
518
+ /** @returns {number} Count of non-deleted elements */
519
+ get length() {
520
+ return this.#nodes.filter(n => !n.deleted).length;
521
+ }
522
+
523
+ /**
524
+ * Insert a value at the given logical index (among non-deleted elements).
525
+ * @param {number} index - Position among visible elements (0 = beginning)
526
+ * @param {*} value
527
+ * @param {string} nodeId
528
+ */
529
+ insertAt(index, value, nodeId) {
530
+ this.#vclock.increment(nodeId);
531
+ const seq = this.#vclock.get(nodeId);
532
+ const id = `${nodeId}:${seq}`;
533
+ const newNode = { id, value, deleted: false };
534
+
535
+ // Map visible index to physical position
536
+ const physicalIndex = this._visibleToPhysical(index);
537
+ this.#nodes.splice(physicalIndex, 0, newNode);
538
+ }
539
+
540
+ /**
541
+ * Delete the element at the given logical index.
542
+ * @param {number} index - Position among visible elements
543
+ */
544
+ deleteAt(index) {
545
+ const physicalIndex = this._visibleToPhysical(index);
546
+ // The physical index from _visibleToPhysical for an existing element:
547
+ // we need the element AT the index, not after it
548
+ // Find the physical index of the nth visible element
549
+ let count = 0;
550
+ for (let i = 0; i < this.#nodes.length; i++) {
551
+ if (!this.#nodes[i].deleted) {
552
+ if (count === index) {
553
+ this.#nodes[i].deleted = true;
554
+ return;
555
+ }
556
+ count++;
557
+ }
558
+ }
559
+ throw new RangeError(`Index ${index} out of bounds`);
560
+ }
561
+
562
+ /**
563
+ * Convert a visible index to a physical insertion position.
564
+ * @param {number} visibleIndex
565
+ * @returns {number}
566
+ */
567
+ _visibleToPhysical(visibleIndex) {
568
+ if (visibleIndex === 0) return 0;
569
+ let count = 0;
570
+ for (let i = 0; i < this.#nodes.length; i++) {
571
+ if (!this.#nodes[i].deleted) {
572
+ count++;
573
+ if (count === visibleIndex) return i + 1;
574
+ }
575
+ }
576
+ // If index equals the number of visible elements, append
577
+ if (count === visibleIndex) return this.#nodes.length;
578
+ // If beyond visible count, also append
579
+ return this.#nodes.length;
580
+ }
581
+
582
+ /**
583
+ * Merge with another RGA. Interleaves based on node IDs for
584
+ * deterministic conflict resolution.
585
+ * @param {RGA} other
586
+ * @returns {RGA}
587
+ */
588
+ merge(other) {
589
+ const otherState = other.state();
590
+ const merged = new RGA();
591
+
592
+ // Build a set of all nodes from both sides, keyed by id
593
+ const nodeMap = new Map();
594
+ for (const node of this.#nodes) {
595
+ nodeMap.set(node.id, { ...node });
596
+ }
597
+ for (const node of otherState.nodes) {
598
+ if (nodeMap.has(node.id)) {
599
+ // If either side deleted it, it stays deleted
600
+ const existing = nodeMap.get(node.id);
601
+ existing.deleted = existing.deleted || node.deleted;
602
+ } else {
603
+ nodeMap.set(node.id, { ...node });
604
+ }
605
+ }
606
+
607
+ // Merge the two ordered sequences
608
+ const mergedNodes = this._mergeSequences(this.#nodes, otherState.nodes, nodeMap);
609
+ merged._setInternal(mergedNodes, this.#vclock.merge(otherState.vclock));
610
+ return merged;
611
+ }
612
+
613
+ /**
614
+ * Merge two node sequences, preserving local order and interleaving
615
+ * concurrent insertions deterministically by ID.
616
+ * @param {Array} seqA
617
+ * @param {Array} seqB
618
+ * @param {Map} nodeMap - merged node states
619
+ * @returns {Array}
620
+ */
621
+ _mergeSequences(seqA, seqB, nodeMap) {
622
+ const result = [];
623
+ const seen = new Set();
624
+ let i = 0;
625
+ let j = 0;
626
+
627
+ while (i < seqA.length || j < seqB.length) {
628
+ // Skip already-seen nodes
629
+ while (i < seqA.length && seen.has(seqA[i].id)) i++;
630
+ while (j < seqB.length && seen.has(seqB[j].id)) j++;
631
+
632
+ if (i >= seqA.length && j >= seqB.length) break;
633
+
634
+ if (i >= seqA.length) {
635
+ // Only B has remaining
636
+ const node = nodeMap.get(seqB[j].id);
637
+ if (!seen.has(node.id)) {
638
+ result.push(node);
639
+ seen.add(node.id);
640
+ }
641
+ j++;
642
+ } else if (j >= seqB.length) {
643
+ // Only A has remaining
644
+ const node = nodeMap.get(seqA[i].id);
645
+ if (!seen.has(node.id)) {
646
+ result.push(node);
647
+ seen.add(node.id);
648
+ }
649
+ i++;
650
+ } else if (seqA[i].id === seqB[j].id) {
651
+ // Same node in both
652
+ const node = nodeMap.get(seqA[i].id);
653
+ if (!seen.has(node.id)) {
654
+ result.push(node);
655
+ seen.add(node.id);
656
+ }
657
+ i++;
658
+ j++;
659
+ } else {
660
+ // Different nodes: check if either appears later in the other sequence
661
+ const aInB = seqB.slice(j).some(n => n.id === seqA[i].id);
662
+ const bInA = seqA.slice(i).some(n => n.id === seqB[j].id);
663
+
664
+ if (aInB && !bInA) {
665
+ // B's node is unique to B, insert it first
666
+ const node = nodeMap.get(seqB[j].id);
667
+ if (!seen.has(node.id)) {
668
+ result.push(node);
669
+ seen.add(node.id);
670
+ }
671
+ j++;
672
+ } else if (bInA && !aInB) {
673
+ // A's node is unique to A, insert it first
674
+ const node = nodeMap.get(seqA[i].id);
675
+ if (!seen.has(node.id)) {
676
+ result.push(node);
677
+ seen.add(node.id);
678
+ }
679
+ i++;
680
+ } else {
681
+ // Both are concurrent (or both in each other's sequence)
682
+ // Deterministic tiebreak: lower ID first
683
+ if (seqA[i].id < seqB[j].id) {
684
+ const node = nodeMap.get(seqA[i].id);
685
+ if (!seen.has(node.id)) {
686
+ result.push(node);
687
+ seen.add(node.id);
688
+ }
689
+ i++;
690
+ } else {
691
+ const node = nodeMap.get(seqB[j].id);
692
+ if (!seen.has(node.id)) {
693
+ result.push(node);
694
+ seen.add(node.id);
695
+ }
696
+ j++;
697
+ }
698
+ }
699
+ }
700
+ }
701
+
702
+ return result;
703
+ }
704
+
705
+ /**
706
+ * Internal method to set state during merge/fromJSON.
707
+ * @param {Array<{ id: string, value: *, deleted: boolean }>} nodes
708
+ * @param {VectorClock} vclock
709
+ */
710
+ _setInternal(nodes, vclock) {
711
+ this.#nodes = nodes;
712
+ this.#vclock = vclock;
713
+ }
714
+
715
+ /**
716
+ * @returns {{ nodes: Array<{ id: string, value: *, deleted: boolean }>, vclock: VectorClock }}
717
+ */
718
+ state() {
719
+ return {
720
+ nodes: this.#nodes.map(n => ({ ...n })),
721
+ vclock: this.#vclock,
722
+ };
723
+ }
724
+
725
+ toJSON() {
726
+ return {
727
+ nodes: this.#nodes.map(n => ({ id: n.id, value: n.value, deleted: n.deleted })),
728
+ vclock: this.#vclock.toJSON(),
729
+ };
730
+ }
731
+
732
+ /**
733
+ * @param {{ nodes: Array<{ id: string, value: *, deleted: boolean }>, vclock: Record<string, number> }} data
734
+ * @returns {RGA}
735
+ */
736
+ static fromJSON(data) {
737
+ const rga = new RGA();
738
+ rga._setInternal(
739
+ data.nodes.map(n => ({ id: n.id, value: n.value, deleted: n.deleted })),
740
+ VectorClock.fromJSON(data.vclock),
741
+ );
742
+ return rga;
743
+ }
744
+ }
745
+
746
+ // ── LWWMap ──────────────────────────────────────────────────────────────────
747
+
748
+ /** Sentinel for deleted entries in LWWMap */
749
+ const TOMBSTONE = Symbol('TOMBSTONE');
750
+
751
+ /** Sentinel string for JSON serialization of tombstones */
752
+ const TOMBSTONE_JSON = '__TOMBSTONE__';
753
+
754
+ /**
755
+ * Last-Writer-Wins Map.
756
+ * Each key is backed by an LWWRegister. Deletions are represented
757
+ * by a sentinel TOMBSTONE value.
758
+ */
759
+ export class LWWMap {
760
+ /** @type {Map<string, LWWRegister>} */
761
+ #entries;
762
+
763
+ constructor() {
764
+ this.#entries = new Map();
765
+ }
766
+
767
+ /** @returns {Record<string, *>} Plain object of live key-value pairs */
768
+ get value() {
769
+ const obj = {};
770
+ for (const [key, reg] of this.#entries) {
771
+ if (reg.value !== TOMBSTONE) {
772
+ obj[key] = reg.value;
773
+ }
774
+ }
775
+ return obj;
776
+ }
777
+
778
+ /** @returns {number} Count of live (non-tombstoned) entries */
779
+ get size() {
780
+ let count = 0;
781
+ for (const reg of this.#entries.values()) {
782
+ if (reg.value !== TOMBSTONE) count++;
783
+ }
784
+ return count;
785
+ }
786
+
787
+ /**
788
+ * Set or update a key.
789
+ * @param {string} key
790
+ * @param {*} value
791
+ * @param {number} timestamp
792
+ * @param {string} nodeId
793
+ */
794
+ set(key, value, timestamp, nodeId) {
795
+ if (!this.#entries.has(key)) {
796
+ this.#entries.set(key, new LWWRegister(value, timestamp, nodeId));
797
+ } else {
798
+ this.#entries.get(key).set(value, timestamp, nodeId);
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Delete a key by writing the TOMBSTONE sentinel.
804
+ * @param {string} key
805
+ * @param {number} timestamp
806
+ * @param {string} nodeId
807
+ */
808
+ delete(key, timestamp, nodeId) {
809
+ this.set(key, TOMBSTONE, timestamp, nodeId);
810
+ }
811
+
812
+ /**
813
+ * Get the value for a key, or undefined if missing/tombstoned.
814
+ * @param {string} key
815
+ * @returns {*}
816
+ */
817
+ get(key) {
818
+ const reg = this.#entries.get(key);
819
+ if (!reg || reg.value === TOMBSTONE) return undefined;
820
+ return reg.value;
821
+ }
822
+
823
+ /**
824
+ * Check if a key exists and is not tombstoned.
825
+ * @param {string} key
826
+ * @returns {boolean}
827
+ */
828
+ has(key) {
829
+ const reg = this.#entries.get(key);
830
+ return reg !== undefined && reg.value !== TOMBSTONE;
831
+ }
832
+
833
+ /**
834
+ * Merge with another LWWMap. Merges each key's register.
835
+ * Returns a new LWWMap.
836
+ * @param {LWWMap} other
837
+ * @returns {LWWMap}
838
+ */
839
+ merge(other) {
840
+ const merged = new LWWMap();
841
+ const otherEntries = other.state();
842
+
843
+ // All keys from this map
844
+ for (const [key, reg] of this.#entries) {
845
+ const otherReg = otherEntries.get(key);
846
+ if (otherReg) {
847
+ merged.#entries.set(key, reg.merge(otherReg));
848
+ } else {
849
+ const s = reg.state();
850
+ merged.#entries.set(key, new LWWRegister(s.value, s.timestamp, s.nodeId));
851
+ }
852
+ }
853
+
854
+ // Keys only in other
855
+ for (const [key, reg] of otherEntries) {
856
+ if (!this.#entries.has(key)) {
857
+ const s = reg.state();
858
+ merged.#entries.set(key, new LWWRegister(s.value, s.timestamp, s.nodeId));
859
+ }
860
+ }
861
+
862
+ return merged;
863
+ }
864
+
865
+ /** @returns {IterableIterator<string>} Live keys */
866
+ *keys() {
867
+ for (const [key, reg] of this.#entries) {
868
+ if (reg.value !== TOMBSTONE) yield key;
869
+ }
870
+ }
871
+
872
+ /** @returns {IterableIterator<*>} Live values */
873
+ *values() {
874
+ for (const reg of this.#entries.values()) {
875
+ if (reg.value !== TOMBSTONE) yield reg.value;
876
+ }
877
+ }
878
+
879
+ /** @returns {IterableIterator<[string, *]>} Live entries */
880
+ *entries() {
881
+ for (const [key, reg] of this.#entries) {
882
+ if (reg.value !== TOMBSTONE) yield [key, reg.value];
883
+ }
884
+ }
885
+
886
+ /**
887
+ * @returns {Map<string, LWWRegister>} Copy of internal entries
888
+ */
889
+ state() {
890
+ return new Map(this.#entries);
891
+ }
892
+
893
+ toJSON() {
894
+ const entries = {};
895
+ for (const [key, reg] of this.#entries) {
896
+ const s = reg.state();
897
+ entries[key] = {
898
+ value: s.value === TOMBSTONE ? null : s.value,
899
+ timestamp: s.timestamp,
900
+ nodeId: s.nodeId,
901
+ tombstone: s.value === TOMBSTONE,
902
+ };
903
+ }
904
+ return { entries };
905
+ }
906
+
907
+ /**
908
+ * @param {{ entries: Record<string, { value: *, timestamp: number, nodeId: string, tombstone?: boolean }> }} data
909
+ * @returns {LWWMap}
910
+ */
911
+ static fromJSON(data) {
912
+ const map = new LWWMap();
913
+ for (const [key, entry] of Object.entries(data.entries)) {
914
+ const value = entry.tombstone ? TOMBSTONE : entry.value;
915
+ map.#entries.set(key, new LWWRegister(value, entry.timestamp, entry.nodeId));
916
+ }
917
+ return map;
918
+ }
919
+ }