@loro-extended/change 5.2.0 → 5.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loro-extended/change",
3
- "version": "5.2.0",
3
+ "version": "5.4.0",
4
4
  "description": "A schema-driven, type-safe wrapper for Loro CRDT that provides natural JavaScript syntax for collaborative data mutations",
5
5
  "author": "Duane Johnson",
6
6
  "license": "MIT",
@@ -25,13 +25,14 @@
25
25
  "tsup": "^8.5.0",
26
26
  "tsx": "^4.20.3",
27
27
  "typescript": "^5.9.2",
28
- "vitest": "^3.2.4"
28
+ "vitest": "^4.0.17"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "loro-crdt": "^1.10.3"
32
32
  },
33
33
  "scripts": {
34
34
  "build": "tsup",
35
+ "test": "verify logic",
35
36
  "verify": "verify"
36
37
  }
37
38
  }
package/src/conversion.ts CHANGED
@@ -108,17 +108,53 @@ function convertStructInput(
108
108
  }
109
109
 
110
110
  const map = new LoroMap()
111
- for (const [k, v] of Object.entries(value)) {
111
+
112
+ // Iterate over schema keys to ensure all nested containers are materialized
113
+ for (const k of Object.keys(shape.shapes)) {
112
114
  const nestedSchema = shape.shapes[k]
113
- if (nestedSchema) {
115
+ const v = value[k]
116
+
117
+ if (v !== undefined) {
114
118
  const convertedValue = convertInputToRef(v, nestedSchema)
115
119
  if (isContainer(convertedValue)) {
116
120
  map.setContainer(k, convertedValue)
117
121
  } else {
118
122
  map.set(k, convertedValue)
119
123
  }
120
- } else {
121
- map.set(k, value)
124
+ } else if (isContainerShape(nestedSchema)) {
125
+ // If value is missing but it's a container shape, create an empty container
126
+ // This ensures deterministic container IDs across peers
127
+ let emptyValue: any
128
+ if (nestedSchema._type === "struct" || nestedSchema._type === "record") {
129
+ emptyValue = {}
130
+ } else if (
131
+ nestedSchema._type === "list" ||
132
+ nestedSchema._type === "movableList"
133
+ ) {
134
+ emptyValue = []
135
+ } else if (nestedSchema._type === "text") {
136
+ emptyValue = ""
137
+ } else if (nestedSchema._type === "counter") {
138
+ emptyValue = 0
139
+ }
140
+
141
+ if (emptyValue !== undefined) {
142
+ const convertedValue = convertInputToRef(emptyValue, nestedSchema)
143
+ if (isContainer(convertedValue)) {
144
+ map.setContainer(k, convertedValue)
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ // Also handle keys present in value but not in schema (if any, though for structs this shouldn't happen ideally)
151
+ // But for backward compatibility or loose typing, we might want to preserve them?
152
+ // The original code did:
153
+ // if (nestedSchema) { ... } else { map.set(k, value) }
154
+ // So it allowed extra keys.
155
+ for (const [k, v] of Object.entries(value)) {
156
+ if (!shape.shapes[k]) {
157
+ map.set(k, v)
122
158
  }
123
159
  }
124
160
 
@@ -361,6 +361,131 @@ describe("functional helpers", () => {
361
361
  })
362
362
  })
363
363
 
364
+ describe("loro(ref).subscribe() for imported (remote) changes", () => {
365
+ it("should fire TextRef subscription when changes are imported", () => {
366
+ // Create two documents - simulating two clients
367
+ const doc1 = createTypedDoc(fullSchema)
368
+ const doc2 = createTypedDoc(fullSchema)
369
+
370
+ // Set up subscription on doc2's title ref
371
+ const callback = vi.fn()
372
+ const unsubscribe = loro(doc2.title).subscribe(callback)
373
+
374
+ // Make changes on doc1
375
+ doc1.title.insert(0, "Hello from doc1")
376
+ loro(doc1).doc.commit()
377
+
378
+ // Export from doc1 and import into doc2 (simulating sync)
379
+ const snapshot = loro(doc1).doc.export({ mode: "snapshot" })
380
+ loro(doc2).doc.import(snapshot)
381
+
382
+ // The subscription should have fired
383
+ expect(callback).toHaveBeenCalled()
384
+
385
+ // And the value should be updated
386
+ expect(doc2.title.toString()).toBe("Hello from doc1")
387
+
388
+ unsubscribe()
389
+ })
390
+
391
+ it("should fire CounterRef subscription when changes are imported", () => {
392
+ const doc1 = createTypedDoc(fullSchema)
393
+ const doc2 = createTypedDoc(fullSchema)
394
+
395
+ const callback = vi.fn()
396
+ const unsubscribe = loro(doc2.count).subscribe(callback)
397
+
398
+ doc1.count.increment(42)
399
+ loro(doc1).doc.commit()
400
+
401
+ const snapshot = loro(doc1).doc.export({ mode: "snapshot" })
402
+ loro(doc2).doc.import(snapshot)
403
+
404
+ expect(callback).toHaveBeenCalled()
405
+ expect(doc2.count.value).toBe(42)
406
+
407
+ unsubscribe()
408
+ })
409
+
410
+ it("should fire ListRef subscription when changes are imported", () => {
411
+ const doc1 = createTypedDoc(fullSchema)
412
+ const doc2 = createTypedDoc(fullSchema)
413
+
414
+ const callback = vi.fn()
415
+ const unsubscribe = loro(doc2.items).subscribe(callback)
416
+
417
+ doc1.items.push("item1")
418
+ doc1.items.push("item2")
419
+ loro(doc1).doc.commit()
420
+
421
+ const snapshot = loro(doc1).doc.export({ mode: "snapshot" })
422
+ loro(doc2).doc.import(snapshot)
423
+
424
+ expect(callback).toHaveBeenCalled()
425
+ expect(doc2.items.toJSON()).toEqual(["item1", "item2"])
426
+
427
+ unsubscribe()
428
+ })
429
+
430
+ it("should fire doc-level subscription when changes are imported", () => {
431
+ const doc1 = createTypedDoc(fullSchema)
432
+ const doc2 = createTypedDoc(fullSchema)
433
+
434
+ const callback = vi.fn()
435
+ const unsubscribe = loro(doc2).doc.subscribe(callback)
436
+
437
+ doc1.title.insert(0, "Hello")
438
+ loro(doc1).doc.commit()
439
+
440
+ const snapshot = loro(doc1).doc.export({ mode: "snapshot" })
441
+ loro(doc2).doc.import(snapshot)
442
+
443
+ expect(callback).toHaveBeenCalled()
444
+
445
+ unsubscribe()
446
+ })
447
+
448
+ it("should NOT fire subscription for containers that were not changed", () => {
449
+ const doc1 = createTypedDoc(fullSchema)
450
+ const doc2 = createTypedDoc(fullSchema)
451
+
452
+ // Subscribe to count, but only change title
453
+ const countCallback = vi.fn()
454
+ const unsubscribe = loro(doc2.count).subscribe(countCallback)
455
+
456
+ doc1.title.insert(0, "Hello")
457
+ loro(doc1).doc.commit()
458
+
459
+ const snapshot = loro(doc1).doc.export({ mode: "snapshot" })
460
+ loro(doc2).doc.import(snapshot)
461
+
462
+ // Count subscription should NOT have fired since count wasn't changed
463
+ expect(countCallback).not.toHaveBeenCalled()
464
+
465
+ unsubscribe()
466
+ })
467
+
468
+ it("should provide updated value in subscription callback", () => {
469
+ const doc1 = createTypedDoc(fullSchema)
470
+ const doc2 = createTypedDoc(fullSchema)
471
+
472
+ let capturedValue: string | undefined
473
+ const unsubscribe = loro(doc2.title).subscribe(() => {
474
+ capturedValue = doc2.title.toString()
475
+ })
476
+
477
+ doc1.title.insert(0, "Remote text")
478
+ loro(doc1).doc.commit()
479
+
480
+ const snapshot = loro(doc1).doc.export({ mode: "snapshot" })
481
+ loro(doc2).doc.import(snapshot)
482
+
483
+ expect(capturedValue).toBe("Remote text")
484
+
485
+ unsubscribe()
486
+ })
487
+ })
488
+
364
489
  describe("getLoroDoc() on refs", () => {
365
490
  it("should return LoroDoc from TextRef", () => {
366
491
  const doc = createTypedDoc(fullSchema)
@@ -1,11 +1,11 @@
1
- import type {
2
- LoroCounter,
1
+ import {
2
+ type LoroCounter,
3
3
  LoroDoc,
4
- LoroList,
5
- LoroMap,
6
- LoroMovableList,
7
- LoroText,
8
- LoroTree,
4
+ type LoroList,
5
+ type LoroMap,
6
+ type LoroMovableList,
7
+ type LoroText,
8
+ type LoroTree,
9
9
  } from "loro-crdt"
10
10
  import { loro } from "./loro.js"
11
11
  import type {
@@ -274,6 +274,52 @@ export function getLoroContainer(
274
274
  return loro(ref as any).container
275
275
  }
276
276
 
277
+ /**
278
+ * Creates a new TypedDoc as a fork of the current document.
279
+ * The forked doc contains all history up to the current version.
280
+ * The forked doc has a different PeerID from the original by default.
281
+ *
282
+ * For raw LoroDoc access, use: `loro(doc).doc.fork()`
283
+ *
284
+ * @param doc - The TypedDoc to fork
285
+ * @param options - Optional settings
286
+ * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork
287
+ * @returns A new TypedDoc with the same schema at the current version
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * import { fork, loro } from "@loro-extended/change"
292
+ *
293
+ * const doc = createTypedDoc(schema);
294
+ * doc.title.update("Hello");
295
+ *
296
+ * // Fork the document
297
+ * const forkedDoc = fork(doc);
298
+ * forkedDoc.title.update("World");
299
+ *
300
+ * console.log(doc.title.toString()); // "Hello"
301
+ * console.log(forkedDoc.title.toString()); // "World"
302
+ *
303
+ * // Fork with same peer ID (for World/Worldview pattern)
304
+ * const worldview = fork(world, { preservePeerId: true });
305
+ * ```
306
+ */
307
+ export function fork<Shape extends DocShape>(
308
+ doc: TypedDoc<Shape>,
309
+ options?: { preservePeerId?: boolean },
310
+ ): TypedDoc<Shape> {
311
+ const loroDoc = loro(doc).doc
312
+ const forkedLoroDoc = loroDoc.fork()
313
+ const shape = loro(doc).docShape as Shape
314
+
315
+ // Optionally preserve the peer ID (useful for World/Worldview pattern)
316
+ if (options?.preservePeerId) {
317
+ forkedLoroDoc.setPeerId(loroDoc.peerId)
318
+ }
319
+
320
+ return createTypedDoc(shape, forkedLoroDoc)
321
+ }
322
+
277
323
  /**
278
324
  * Creates a new TypedDoc at a specified version (frontiers).
279
325
  * The forked doc will only contain history before the specified frontiers.
@@ -309,3 +355,71 @@ export function forkAt<Shape extends DocShape>(
309
355
  const shape = loro(doc).docShape as Shape
310
356
  return createTypedDoc(shape, forkedLoroDoc)
311
357
  }
358
+
359
+ /**
360
+ * Creates a new TypedDoc at a specified version using a shallow snapshot.
361
+ * Unlike `forkAt`, this creates a "garbage-collected" snapshot that only
362
+ * contains the current state and history since the specified frontiers.
363
+ *
364
+ * This is more memory-efficient than `forkAt` for documents with long history,
365
+ * especially useful for the fork-and-merge pattern in LEA where we only need:
366
+ * 1. Read current state
367
+ * 2. Apply changes
368
+ * 3. Export delta and merge back
369
+ *
370
+ * The shallow fork has a different PeerID from the original by default.
371
+ * Use `preservePeerId: true` to copy the original's peer ID (useful for
372
+ * fork-and-merge patterns where you want consistent frontier progression).
373
+ *
374
+ * @param doc - The TypedDoc to fork
375
+ * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)
376
+ * @param options - Optional settings
377
+ * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork
378
+ * @returns A new TypedDoc with the same schema at the specified version (shallow)
379
+ *
380
+ * @example
381
+ * ```typescript
382
+ * import { shallowForkAt, loro } from "@loro-extended/change"
383
+ *
384
+ * const doc = createTypedDoc(schema);
385
+ * doc.title.update("Hello");
386
+ * const frontiers = loro(doc).doc.frontiers();
387
+ *
388
+ * // Create a shallow fork (memory-efficient)
389
+ * const shallowDoc = shallowForkAt(doc, frontiers, { preservePeerId: true });
390
+ *
391
+ * // Modify the shallow doc
392
+ * shallowDoc.title.update("World");
393
+ *
394
+ * // Merge changes back
395
+ * const update = loro(shallowDoc).doc.export({
396
+ * mode: "update",
397
+ * from: loro(doc).doc.version()
398
+ * });
399
+ * loro(doc).doc.import(update);
400
+ * ```
401
+ */
402
+ export function shallowForkAt<Shape extends DocShape>(
403
+ doc: TypedDoc<Shape>,
404
+ frontiers: Frontiers,
405
+ options?: { preservePeerId?: boolean },
406
+ ): TypedDoc<Shape> {
407
+ const loroDoc = loro(doc).doc
408
+ const shape = loro(doc).docShape as Shape
409
+
410
+ // Export a shallow snapshot at the specified frontiers
411
+ const shallowBytes = loroDoc.export({
412
+ mode: "shallow-snapshot",
413
+ frontiers,
414
+ })
415
+
416
+ // Create a new LoroDoc from the shallow snapshot
417
+ const shallowLoroDoc = LoroDoc.fromSnapshot(shallowBytes)
418
+
419
+ // Optionally preserve the peer ID for consistent frontier progression
420
+ if (options?.preservePeerId) {
421
+ shallowLoroDoc.setPeerId(loroDoc.peerId)
422
+ }
423
+
424
+ return createTypedDoc(shape, shallowLoroDoc)
425
+ }
package/src/index.ts CHANGED
@@ -4,13 +4,17 @@ export {
4
4
  derivePlaceholder,
5
5
  deriveShapePlaceholder,
6
6
  } from "./derive-placeholder.js"
7
+
7
8
  // Functional helpers (recommended API)
8
9
  export {
9
10
  change,
11
+ fork,
10
12
  forkAt,
11
13
  getLoroContainer,
12
14
  getLoroDoc,
15
+ shallowForkAt,
13
16
  } from "./functional-helpers.js"
17
+
14
18
  // The loro() escape hatch for CRDT internals
15
19
  export {
16
20
  LORO_SYMBOL,
@@ -23,6 +27,7 @@ export {
23
27
  type LoroTypedDocRef,
24
28
  loro,
25
29
  } from "./loro.js"
30
+
26
31
  export { mergeValue, overlayPlaceholder } from "./overlay.js"
27
32
  // Path selector DSL exports
28
33
  export { createPathBuilder } from "./path-builder.js"
@@ -35,43 +40,42 @@ export type {
35
40
  PathSelector,
36
41
  } from "./path-selector.js"
37
42
  export { createPlaceholderProxy } from "./placeholder-proxy.js"
43
+ export { replayDiff } from "./replay-diff.js"
44
+ // Shape utilities
45
+ // Container shapes
46
+ // Value shapes
38
47
  export type {
39
- // Escape hatch shapes for untyped integration
40
48
  AnyContainerShape,
41
49
  AnyValueShape,
42
50
  ArrayValueShape,
43
51
  ContainerOrValueShape,
44
52
  ContainerShape,
45
53
  ContainerType as RootContainerType,
46
- // Container shapes
47
54
  CounterContainerShape,
48
- // Discriminated union for tagged unions
55
+ // Tagged union
49
56
  DiscriminatedUnionValueShape,
50
- // Schema node types
51
57
  DocShape,
52
58
  ListContainerShape,
53
- /** @deprecated Use StructContainerShape instead */
54
- MapContainerShape,
55
59
  MovableListContainerShape,
56
- /** @deprecated Use StructValueShape instead */
57
- ObjectValueShape,
60
+ NumberValueShape,
58
61
  RecordContainerShape,
59
62
  RecordValueShape,
63
+ StringValueShape,
60
64
  StructContainerShape,
61
65
  StructValueShape,
62
66
  TextContainerShape,
63
67
  TreeContainerShape,
64
- // Tree-related types
65
68
  TreeNodeJSON,
66
69
  TreeRefInterface,
70
+ // Union of two or more plain value types
67
71
  UnionValueShape,
68
- // Value shapes
69
72
  ValueShape,
70
73
  // WithNullable type for shapes that support .nullable()
71
74
  WithNullable,
72
75
  // WithPlaceholder type for shapes that support .placeholder()
73
76
  WithPlaceholder,
74
77
  } from "./shape.js"
78
+
75
79
  // Schema and type exports
76
80
  export { Shape } from "./shape.js"
77
81
  export type { Frontiers, TypedDoc } from "./typed-doc.js"
package/src/loro.ts CHANGED
@@ -28,6 +28,7 @@ import type {
28
28
  Container,
29
29
  LoroCounter,
30
30
  LoroDoc,
31
+ LoroEventBatch,
31
32
  LoroList,
32
33
  LoroMap,
33
34
  LoroMovableList,
@@ -85,7 +86,7 @@ export interface LoroRefBase {
85
86
  * @param callback - Function called when the container changes
86
87
  * @returns Subscription that can be used to unsubscribe
87
88
  */
88
- subscribe(callback: (event: unknown) => void): Subscription
89
+ subscribe(callback: (event: LoroEventBatch) => void): Subscription
89
90
  }
90
91
 
91
92
  /**