json-patch-to-crdt 0.1.2 → 0.2.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/README.md +69 -386
- package/dist/{compact-BJBGW9tC.mjs → compact-BE9UsxEo.mjs} +794 -193
- package/dist/{compact-CkLd4Yh5.js → compact-DrmgKiVW.js} +823 -192
- package/dist/{depth-p6fX9Ak7.d.ts → depth-Cd3nyHWy.d.mts} +113 -5
- package/dist/{depth-wDeQ1hO1.d.mts → depth-tcJ8L1dj.d.ts} +113 -5
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -1
- package/dist/index.mjs +2 -2
- package/dist/internals.d.mts +13 -24
- package/dist/internals.d.ts +13 -24
- package/dist/internals.js +6 -1
- package/dist/internals.mjs +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,92 +1,62 @@
|
|
|
1
1
|
# json-patch-to-crdt
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/json-patch-to-crdt)
|
|
4
|
+
[](LICENSE.md)
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
Convert JSON Patch (RFC 6902) operations into a CRDT-backed state that can be merged across peers, then materialize JSON again.
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
- Maintain a CRDT-compatible document model for sync.
|
|
9
|
-
- Merge divergent document states from multiple peers.
|
|
10
|
-
- Serialize and restore CRDT state safely.
|
|
11
|
-
- Generate JSON Patch deltas using explicit base snapshots.
|
|
8
|
+
Useful when you want:
|
|
12
9
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
-
|
|
16
|
-
- An RGA sequence for arrays.
|
|
17
|
-
- A map with delete-wins semantics for objects.
|
|
10
|
+
- JSON Patch in/out at your app boundary
|
|
11
|
+
- CRDT merges internally for offline/collaborative edits
|
|
12
|
+
- deterministic JSON Patch diffs between snapshots
|
|
18
13
|
|
|
19
14
|
## Install
|
|
20
15
|
|
|
21
|
-
```bash
|
|
22
|
-
bun add json-patch-to-crdt
|
|
23
|
-
```
|
|
24
|
-
|
|
25
16
|
```bash
|
|
26
17
|
npm install json-patch-to-crdt
|
|
27
18
|
```
|
|
28
19
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
- Node.js `>= 18` (for package consumers).
|
|
32
|
-
- TypeScript `^5` when type-checking in your project.
|
|
33
|
-
- Bun `1.3.7` is used for this repo's own build/test scripts.
|
|
34
|
-
|
|
35
|
-
## Testing (Repo)
|
|
36
|
-
|
|
37
|
-
Run all tests:
|
|
20
|
+
Also works with Bun / pnpm:
|
|
38
21
|
|
|
39
22
|
```bash
|
|
40
|
-
bun
|
|
23
|
+
bun add json-patch-to-crdt
|
|
24
|
+
pnpm add json-patch-to-crdt
|
|
41
25
|
```
|
|
42
26
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
```bash
|
|
46
|
-
bun run test:state-core
|
|
47
|
-
bun run test:patch-diff-doc
|
|
48
|
-
bun run test:merge-compaction
|
|
49
|
-
bun run test:replica-session
|
|
50
|
-
bun run test:perf-regression
|
|
51
|
-
```
|
|
27
|
+
Node.js `>=18`.
|
|
52
28
|
|
|
53
|
-
## Quick Start
|
|
29
|
+
## Quick Start
|
|
54
30
|
|
|
55
31
|
```ts
|
|
56
32
|
import { applyPatch, createState, toJson, type JsonPatchOp } from "json-patch-to-crdt";
|
|
57
33
|
|
|
58
|
-
const state = createState(
|
|
34
|
+
const state = createState(
|
|
35
|
+
{ todos: ["write docs"], done: false },
|
|
36
|
+
{ actor: "client-A" },
|
|
37
|
+
);
|
|
59
38
|
|
|
60
39
|
const patch: JsonPatchOp[] = [
|
|
61
|
-
{ op: "add", path: "/
|
|
62
|
-
{ op: "replace", path: "/
|
|
40
|
+
{ op: "add", path: "/todos/-", value: "ship package" },
|
|
41
|
+
{ op: "replace", path: "/done", value: true },
|
|
63
42
|
];
|
|
64
43
|
|
|
65
|
-
|
|
66
|
-
const next = applyPatch(state, patch);
|
|
67
|
-
console.log(toJson(next));
|
|
68
|
-
} catch (err) {
|
|
69
|
-
// PatchError has a `.code` you can inspect if needed.
|
|
70
|
-
throw err;
|
|
71
|
-
}
|
|
72
|
-
```
|
|
44
|
+
const next = applyPatch(state, patch);
|
|
73
45
|
|
|
74
|
-
|
|
46
|
+
console.log(toJson(next));
|
|
47
|
+
// { todos: ["write docs", "ship package"], done: true }
|
|
48
|
+
```
|
|
75
49
|
|
|
76
|
-
|
|
50
|
+
## Merge Two Peers
|
|
77
51
|
|
|
78
52
|
```ts
|
|
79
53
|
import { applyPatch, createState, forkState, mergeState, toJson } from "json-patch-to-crdt";
|
|
80
54
|
|
|
81
|
-
// Both peers start from the same origin state.
|
|
82
55
|
const origin = createState({ count: 0, items: ["a"] }, { actor: "origin" });
|
|
83
56
|
|
|
84
|
-
// Fork shared-origin replicas with local actor identities.
|
|
85
|
-
// Actor IDs must be unique per live peer (same-actor reuse is rejected by default).
|
|
86
57
|
const peerA = forkState(origin, "A");
|
|
87
58
|
const peerB = forkState(origin, "B");
|
|
88
59
|
|
|
89
|
-
// Peers diverge with independent edits.
|
|
90
60
|
const a1 = applyPatch(peerA, [
|
|
91
61
|
{ op: "replace", path: "/count", value: 1 },
|
|
92
62
|
{ op: "add", path: "/items/-", value: "b" },
|
|
@@ -97,382 +67,95 @@ const b1 = applyPatch(peerB, [
|
|
|
97
67
|
{ op: "add", path: "/items/-", value: "c" },
|
|
98
68
|
]);
|
|
99
69
|
|
|
100
|
-
|
|
101
|
-
const mergedAtA = mergeState(a1, b1, { actor: "A" });
|
|
102
|
-
const mergedAtB = mergeState(b1, a1, { actor: "B" });
|
|
70
|
+
const merged = mergeState(a1, b1, { actor: "A" });
|
|
103
71
|
|
|
104
|
-
console.log(toJson(
|
|
72
|
+
console.log(toJson(merged));
|
|
105
73
|
// { count: 2, items: ["a", "c", "b"] }
|
|
106
|
-
// (both appends preserved; sibling order follows dot ordering)
|
|
107
|
-
|
|
108
|
-
// Both peers can continue editing safely.
|
|
109
|
-
const a2 = applyPatch(mergedAtA, [{ op: "replace", path: "/count", value: 3 }]);
|
|
110
|
-
const b2 = applyPatch(mergedAtB, [{ op: "add", path: "/items/-", value: "d" }]);
|
|
111
|
-
|
|
112
|
-
// Merge again to converge.
|
|
113
|
-
const converged = mergeState(a2, b2, { actor: "A" });
|
|
114
|
-
console.log(toJson(converged));
|
|
115
|
-
// { count: 3, items: ["a", "c", "b", "d"] }
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
## Concepts
|
|
119
|
-
|
|
120
|
-
- **Doc**: CRDT document node graph (primarily an internals concept).
|
|
121
|
-
- **State**: `{ doc, clock }`, used by the main API.
|
|
122
|
-
- **Base snapshot**: for `applyPatch`, pass a prior `CrdtState`; internals APIs may use raw `Doc` snapshots.
|
|
123
|
-
|
|
124
|
-
## Ordered Event Log Server Pattern
|
|
125
|
-
|
|
126
|
-
If your service contract is "JSON Patch in / JSON Patch out", and your backend keeps CRDT metadata internally:
|
|
127
|
-
|
|
128
|
-
- Keep one authoritative CRDT head per document.
|
|
129
|
-
- Keep a version vector keyed by actor ID.
|
|
130
|
-
- On each incoming JSON Patch, call `applyPatchAsActor(headDoc, vv, actor, patch, { base })`.
|
|
131
|
-
- Append the accepted event to your ordered log.
|
|
132
|
-
- For downstream clients, emit `crdtToJsonPatch(clientBaseDoc, currentHeadDoc)`.
|
|
133
|
-
|
|
134
|
-
Minimal shape (advanced API via `json-patch-to-crdt/internals`):
|
|
135
|
-
|
|
136
|
-
```ts
|
|
137
|
-
import {
|
|
138
|
-
applyPatchAsActor,
|
|
139
|
-
PatchError,
|
|
140
|
-
crdtToJsonPatch,
|
|
141
|
-
createState,
|
|
142
|
-
type Doc,
|
|
143
|
-
type JsonPatchOp,
|
|
144
|
-
type VersionVector,
|
|
145
|
-
} from "json-patch-to-crdt/internals";
|
|
146
|
-
|
|
147
|
-
let head: Doc = createState({ list: [] }, { actor: "server" }).doc;
|
|
148
|
-
let vv: VersionVector = {};
|
|
149
|
-
|
|
150
|
-
function applyIncomingPatch(
|
|
151
|
-
actor: string,
|
|
152
|
-
base: Doc,
|
|
153
|
-
patch: JsonPatchOp[],
|
|
154
|
-
): { ok: true; outPatch: JsonPatchOp[] } | { ok: false; code: number; message: string } {
|
|
155
|
-
try {
|
|
156
|
-
const applied = applyPatchAsActor(head, vv, actor, patch, { base });
|
|
157
|
-
head = applied.state.doc;
|
|
158
|
-
vv = applied.vv;
|
|
159
|
-
|
|
160
|
-
// Persist incoming event and/or outPatch in your append-only ordered log.
|
|
161
|
-
const outPatch = crdtToJsonPatch(base, head);
|
|
162
|
-
return { ok: true, outPatch };
|
|
163
|
-
} catch (error) {
|
|
164
|
-
if (error instanceof PatchError) {
|
|
165
|
-
return { ok: false, code: error.code, message: error.message };
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
throw error;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
If you prefer a non-throwing low-level compile+apply path, use `jsonPatchToCrdtSafe` from `json-patch-to-crdt/internals`.
|
|
174
|
-
|
|
175
|
-
## Patch Semantics
|
|
176
|
-
|
|
177
|
-
- Patches are interpreted relative to a base snapshot.
|
|
178
|
-
- `applyPatch` defaults to RFC-style sequential patch execution.
|
|
179
|
-
- You can pass an explicit base state via `applyPatch(state, patch, { base })`.
|
|
180
|
-
- Patch semantics are configurable: `semantics: "sequential"` (default) or `"base"`.
|
|
181
|
-
- In `sequential` mode with an explicit `base`, operations are interpreted against a rolling base snapshot while being applied step-by-step to the evolving head.
|
|
182
|
-
- Array indexes are mapped to element IDs based on the base snapshot.
|
|
183
|
-
- `"-"` is treated as append for array inserts.
|
|
184
|
-
- `test` operations can be evaluated against `head` or `base` using the `testAgainst` option.
|
|
185
|
-
|
|
186
|
-
### Semantics Modes
|
|
187
|
-
|
|
188
|
-
- `semantics: "sequential"` (default): applies operations one-by-one against the evolving head (RFC-like execution).
|
|
189
|
-
- `semantics: "base"`: interprets the full patch relative to one fixed snapshot.
|
|
190
|
-
|
|
191
|
-
#### Which Mode Should You Use?
|
|
192
|
-
|
|
193
|
-
| If you need... | Use |
|
|
194
|
-
| ------------------------------------------------------------------------- | ------------------------- |
|
|
195
|
-
| Deterministic CRDT-style replay against a known snapshot | `semantics: "base"` |
|
|
196
|
-
| JSON Patch behavior that feels closest to RFC 6902 step-by-step execution | `semantics: "sequential"` |
|
|
197
|
-
| Step-by-step replay from an explicit historical base | `semantics: "sequential"` |
|
|
198
|
-
|
|
199
|
-
Example:
|
|
200
|
-
|
|
201
|
-
```ts
|
|
202
|
-
const baseMode = applyPatch(state, [{ op: "add", path: "/list/0", value: "x" }], {
|
|
203
|
-
semantics: "base",
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
const sequentialMode = applyPatch(state, [{ op: "add", path: "/list/0", value: "x" }], {
|
|
207
|
-
semantics: "sequential",
|
|
208
|
-
});
|
|
209
74
|
```
|
|
210
75
|
|
|
211
|
-
##
|
|
212
|
-
|
|
213
|
-
For most applications, diff JSON values directly:
|
|
76
|
+
## Generate JSON Patch Deltas
|
|
214
77
|
|
|
215
78
|
```ts
|
|
216
79
|
import { diffJsonPatch } from "json-patch-to-crdt";
|
|
217
80
|
|
|
218
|
-
const
|
|
219
|
-
|
|
81
|
+
const base = { profile: { name: "Sam" }, tags: ["a"] };
|
|
82
|
+
const next = { profile: { name: "Sam", active: true }, tags: ["a", "b"] };
|
|
220
83
|
|
|
221
|
-
|
|
84
|
+
const delta = diffJsonPatch(base, next);
|
|
222
85
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
If you need a full-state root `replace` patch (no delta), use internals:
|
|
230
|
-
|
|
231
|
-
```ts
|
|
232
|
-
import { crdtToFullReplace } from "json-patch-to-crdt/internals";
|
|
233
|
-
|
|
234
|
-
const fullPatch = crdtToFullReplace(doc);
|
|
235
|
-
// [{ op: "replace", path: "", value: { ... } }]
|
|
86
|
+
console.log(delta);
|
|
87
|
+
// [
|
|
88
|
+
// { op: "add", path: "/profile/active", value: true },
|
|
89
|
+
// { op: "add", path: "/tags/1", value: "b" }
|
|
90
|
+
// ]
|
|
236
91
|
```
|
|
237
92
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
By default, arrays are diffed with deterministic LCS edits.
|
|
241
|
-
To prevent pathological `O(n*m)` matrix growth on very large arrays, LCS falls back to atomic array replacement when matrix cells exceed `250_000` by default.
|
|
242
|
-
|
|
243
|
-
If you want atomic array replacement, pass `{ arrayStrategy: "atomic" }`:
|
|
244
|
-
|
|
245
|
-
```ts
|
|
246
|
-
const delta = diffJsonPatch(baseJson, nextJson, { arrayStrategy: "atomic" });
|
|
247
|
-
```
|
|
248
|
-
|
|
249
|
-
If you want to tune the LCS fallback threshold, pass `lcsMaxCells`:
|
|
250
|
-
|
|
251
|
-
```ts
|
|
252
|
-
const delta = diffJsonPatch(baseJson, nextJson, {
|
|
253
|
-
arrayStrategy: "lcs",
|
|
254
|
-
lcsMaxCells: 500_000,
|
|
255
|
-
});
|
|
256
|
-
```
|
|
257
|
-
|
|
258
|
-
Notes:
|
|
259
|
-
|
|
260
|
-
- LCS diffs are deterministic but not necessarily minimal.
|
|
261
|
-
- Reorders are expressed as remove/add pairs.
|
|
262
|
-
- LCS complexity is `O(n*m)` in time and memory.
|
|
263
|
-
- `lcsMaxCells` sets the matrix cap: `(base.length + 1) * (next.length + 1)`.
|
|
264
|
-
- Set `lcsMaxCells: Number.POSITIVE_INFINITY` to always allow LCS.
|
|
265
|
-
|
|
266
|
-
## Merging
|
|
267
|
-
|
|
268
|
-
Merge full states:
|
|
269
|
-
|
|
270
|
-
```ts
|
|
271
|
-
import { mergeState } from "json-patch-to-crdt";
|
|
272
|
-
|
|
273
|
-
// Merge full states (preserve local actor identity):
|
|
274
|
-
const mergedState = mergeState(stateA, stateB, { actor: "A" });
|
|
275
|
-
```
|
|
276
|
-
|
|
277
|
-
If you need low-level document-only merging, use `mergeDoc` from `json-patch-to-crdt/internals`.
|
|
278
|
-
|
|
279
|
-
By default, merge checks that non-empty arrays share lineage (common element IDs).
|
|
280
|
-
If you intentionally need best-effort merging of unrelated array histories, disable this guard:
|
|
281
|
-
|
|
282
|
-
```ts
|
|
283
|
-
import { mergeDoc } from "json-patch-to-crdt/internals";
|
|
284
|
-
|
|
285
|
-
const mergedDoc = mergeDoc(docA, docB, { requireSharedOrigin: false });
|
|
286
|
-
```
|
|
287
|
-
|
|
288
|
-
Resolution rules:
|
|
289
|
-
|
|
290
|
-
- **LWW registers**: the register with the higher dot wins.
|
|
291
|
-
- **Objects**: entries merge key-by-key; delete-wins semantics apply.
|
|
292
|
-
- **RGA arrays**: elements union by ID; tombstones propagate (delete wins).
|
|
293
|
-
- **Kind mismatch**: the node with the higher representative dot wins.
|
|
294
|
-
|
|
295
|
-
`mergeDoc` is commutative (`merge(a, b)` equals `merge(b, a)`) and idempotent.
|
|
296
|
-
For `mergeState`, pass the local actor explicitly (or as the first argument) so each peer keeps a stable actor ID.
|
|
297
|
-
|
|
298
|
-
## Tombstone Compaction
|
|
299
|
-
|
|
300
|
-
Long-lived documents can accumulate object/array tombstones.
|
|
301
|
-
You can compact causally-stable tombstones with:
|
|
302
|
-
|
|
303
|
-
```ts
|
|
304
|
-
import { compactStateTombstones } from "json-patch-to-crdt";
|
|
305
|
-
|
|
306
|
-
const { state: compacted, stats } = compactStateTombstones(state, {
|
|
307
|
-
stable: { A: 120, B: 98, C: 77 },
|
|
308
|
-
});
|
|
309
|
-
|
|
310
|
-
console.log(stats);
|
|
311
|
-
// { objectTombstonesRemoved: number, sequenceTombstonesRemoved: number }
|
|
312
|
-
```
|
|
313
|
-
|
|
314
|
-
For server-side workflows operating on raw docs, use internals:
|
|
315
|
-
|
|
316
|
-
```ts
|
|
317
|
-
import { compactDocTombstones } from "json-patch-to-crdt/internals";
|
|
318
|
-
|
|
319
|
-
compactDocTombstones(doc, {
|
|
320
|
-
stable: checkpointVv,
|
|
321
|
-
mutate: true, // optional in-place compaction
|
|
322
|
-
});
|
|
323
|
-
```
|
|
324
|
-
|
|
325
|
-
Safety conditions:
|
|
326
|
-
|
|
327
|
-
- Only compact at checkpoints that are causally stable across all peers you still merge with.
|
|
328
|
-
- Do not merge compacted replicas with peers that may be behind that checkpoint.
|
|
329
|
-
- Compaction preserves materialized JSON output for the compacted document/state.
|
|
330
|
-
|
|
331
|
-
## Serialization
|
|
93
|
+
## Serialize / Restore State
|
|
332
94
|
|
|
333
95
|
```ts
|
|
334
96
|
import {
|
|
97
|
+
applyPatch,
|
|
335
98
|
createState,
|
|
336
|
-
serializeState,
|
|
337
99
|
deserializeState,
|
|
338
|
-
|
|
100
|
+
serializeState,
|
|
339
101
|
toJson,
|
|
340
102
|
} from "json-patch-to-crdt";
|
|
341
103
|
|
|
342
|
-
const state = createState({
|
|
343
|
-
const
|
|
104
|
+
const state = createState({ counter: 1 }, { actor: "A" });
|
|
105
|
+
const saved = serializeState(state);
|
|
344
106
|
|
|
345
|
-
const restored = deserializeState(
|
|
346
|
-
const next = applyPatch(restored, [{ op: "replace", path: "/
|
|
107
|
+
const restored = deserializeState(saved);
|
|
108
|
+
const next = applyPatch(restored, [{ op: "replace", path: "/counter", value: 2 }]);
|
|
347
109
|
|
|
348
110
|
console.log(toJson(next));
|
|
111
|
+
// { counter: 2 }
|
|
349
112
|
```
|
|
350
113
|
|
|
351
|
-
## Supported JSON Patch Ops
|
|
352
|
-
|
|
353
|
-
- `add`, `remove`, `replace`, `move`, `copy`, `test`.
|
|
354
|
-
- `move` and `copy` are compiled to `add` + optional `remove` using the base snapshot.
|
|
355
|
-
- Object operations follow strict parent/target checks (no implicit object path creation).
|
|
356
|
-
|
|
357
114
|
## Error Handling
|
|
358
115
|
|
|
359
|
-
|
|
116
|
+
`applyPatch` throws `PatchError` when a patch cannot be applied.
|
|
360
117
|
|
|
361
118
|
```ts
|
|
362
|
-
import {
|
|
119
|
+
import { PatchError, applyPatch } from "json-patch-to-crdt";
|
|
363
120
|
|
|
364
121
|
try {
|
|
365
|
-
|
|
366
|
-
} catch (
|
|
367
|
-
if (
|
|
368
|
-
console.error(
|
|
122
|
+
applyPatch(state, patch);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof PatchError) {
|
|
125
|
+
console.error(error.code, error.reason, error.message);
|
|
369
126
|
}
|
|
370
127
|
}
|
|
371
128
|
```
|
|
372
129
|
|
|
373
|
-
|
|
374
|
-
Internals helpers like `jsonPatchToCrdtSafe` and `tryMergeDoc` return the same shape:
|
|
375
|
-
|
|
376
|
-
- `{ ok: false, code: 409, reason, message, path?, opIndex? }`
|
|
377
|
-
|
|
378
|
-
## API Summary
|
|
379
|
-
|
|
380
|
-
### State helpers
|
|
381
|
-
|
|
382
|
-
- `createState(initial, { actor, start? })` - Create a new CRDT state from JSON.
|
|
383
|
-
- `forkState(origin, actor, options?)` - Fork a shared-origin replica with a new local actor ID. Reusing `origin` actor IDs is rejected by default (`options.allowActorReuse: true` to opt in explicitly).
|
|
384
|
-
- `applyPatch(state, patch, options?)` - Apply a patch immutably, returning a new state (`semantics: "sequential"` by default).
|
|
385
|
-
- `applyPatchInPlace(state, patch, options?)` - Apply a patch by mutating state in place (`atomic: true` by default).
|
|
386
|
-
- `tryApplyPatch(state, patch, options?)` - Non-throwing immutable apply (`{ ok: true, state }` or `{ ok: false, error }`).
|
|
387
|
-
- `tryApplyPatchInPlace(state, patch, options?)` - Non-throwing in-place apply result.
|
|
388
|
-
- `validateJsonPatch(baseJson, patch, options?)` - Preflight patch validation (non-mutating).
|
|
389
|
-
- `toJson(docOrState)` - Materialize a JSON value from a doc or state.
|
|
390
|
-
- `applyPatch`/`tryApplyPatch` options: `base` expects a prior `CrdtState` snapshot (not a raw doc), plus `semantics` and `testAgainst`.
|
|
391
|
-
- `PatchError` - Error class thrown for failed patches (`code`, `reason`, `message`, optional `path`/`opIndex`).
|
|
392
|
-
|
|
393
|
-
### Merge helpers
|
|
394
|
-
|
|
395
|
-
- `mergeState(a, b, options?)` - Merge two CRDT states (doc + clock), preserving actor identity (`options.actor`) and optional shared-origin checks.
|
|
396
|
-
- `tryMergeState(a, b, options?)` - Non-throwing merge-state result.
|
|
397
|
-
- `MergeError` - Error class thrown by throwing merge helpers.
|
|
398
|
-
|
|
399
|
-
### Patch helpers
|
|
400
|
-
|
|
401
|
-
- `diffJsonPatch(baseJson, nextJson, options?)` - Compute a JSON Patch delta between two JSON values.
|
|
130
|
+
If you prefer non-throwing results, use `tryApplyPatch(...)` / `tryMergeState(...)`.
|
|
402
131
|
|
|
403
|
-
|
|
132
|
+
## API Overview
|
|
404
133
|
|
|
405
|
-
|
|
134
|
+
Main exports most apps need:
|
|
406
135
|
|
|
407
|
-
|
|
136
|
+
- `createState(initial, { actor })`
|
|
137
|
+
- `forkState(origin, actor)`
|
|
138
|
+
- `applyPatch(state, patch, options?)`
|
|
139
|
+
- `tryApplyPatch(state, patch, options?)`
|
|
140
|
+
- `mergeState(local, remote, { actor })`
|
|
141
|
+
- `tryMergeState(local, remote, options?)`
|
|
142
|
+
- `toJson(stateOrDoc)`
|
|
143
|
+
- `diffJsonPatch(baseJson, nextJson, options?)`
|
|
144
|
+
- `serializeState(state)` / `deserializeState(payload)`
|
|
145
|
+
- `validateJsonPatch(baseJson, patch, options?)`
|
|
408
146
|
|
|
409
|
-
Advanced helpers are available
|
|
147
|
+
Advanced/internal helpers are available from:
|
|
410
148
|
|
|
411
149
|
```ts
|
|
412
|
-
import {
|
|
413
|
-
applyPatchAsActor,
|
|
414
|
-
createClock,
|
|
415
|
-
docFromJson,
|
|
416
|
-
mergeDoc,
|
|
417
|
-
jsonPatchToCrdtSafe,
|
|
418
|
-
compareDot,
|
|
419
|
-
rgaInsertAfter,
|
|
420
|
-
HEAD,
|
|
421
|
-
} from "json-patch-to-crdt/internals";
|
|
150
|
+
import { crdtToJsonPatch, applyPatchAsActor } from "json-patch-to-crdt/internals";
|
|
422
151
|
```
|
|
423
152
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
- Actor/version-vector helpers: `applyPatchAsActor`, `createClock`, `cloneClock`, `nextDotForActor`, `observeDot`.
|
|
427
|
-
- Doc-level APIs: `docFromJson`, `docFromJsonWithDot`, `cloneDoc`, `materialize`, `mergeDoc`, `tryMergeDoc`.
|
|
428
|
-
- Intent compiler/apply pipeline: `compileJsonPatchToIntent`, `applyIntentsToCrdt`, `jsonPatchToCrdt`, `jsonPatchToCrdtSafe`, `tryJsonPatchToCrdt`.
|
|
429
|
-
- Doc delta/serialization helpers: `crdtToJsonPatch`, `crdtToFullReplace`, `serializeDoc`, `deserializeDoc`.
|
|
430
|
-
- CRDT primitives/utilities: `compareDot`, `vvHasDot`, `vvMerge`, `dotToElemId`, `newObj`, `newSeq`, `newReg`, `lwwSet`, `objSet`, `objRemove`, `HEAD`, `rgaInsertAfter`, `rgaDelete`, `rgaLinearizeIds`, `rgaPrevForInsertAtIndex`, `rgaIdAtIndex`.
|
|
431
|
-
|
|
432
|
-
## Determinism
|
|
433
|
-
|
|
434
|
-
- Object key ordering in deltas is stable (sorted keys).
|
|
435
|
-
- LCS array diffs are deterministic.
|
|
436
|
-
- Repeated runs for identical inputs yield identical patches.
|
|
437
|
-
|
|
438
|
-
## FAQ / Troubleshooting
|
|
439
|
-
|
|
440
|
-
**Why did I get `PatchError` with code `409`?**
|
|
441
|
-
This typically means the patch could not be applied against the base snapshot. Common causes:
|
|
442
|
-
|
|
443
|
-
- Array index out of bounds relative to the base snapshot.
|
|
444
|
-
- `test` op failed (value mismatch).
|
|
445
|
-
- Base array missing for a non-append insert.
|
|
446
|
-
|
|
447
|
-
**How do I avoid `409` for arrays?**
|
|
448
|
-
Always pass a base state snapshot that matches the array you are patching. If the array may be missing, create the parent path explicitly before inserting into it.
|
|
449
|
-
|
|
450
|
-
**How do I get a full-state patch instead of a delta?**
|
|
451
|
-
Use `crdtToFullReplace(doc)` from `json-patch-to-crdt/internals`, which emits a single root `replace` patch.
|
|
452
|
-
|
|
453
|
-
**Why do array deltas look bigger than expected?**
|
|
454
|
-
LCS diffs are deterministic, not minimal. If you prefer one-op array replacement, use `{ arrayStrategy: "atomic" }`.
|
|
455
|
-
|
|
456
|
-
**Why did my array delta become a full `replace` even with LCS?**
|
|
457
|
-
For scalability, LCS falls back to atomic replacement when arrays exceed the `lcsMaxCells` guardrail (default `250_000` matrix cells). Increase `lcsMaxCells` to allow larger LCS runs.
|
|
458
|
-
|
|
459
|
-
**Does LCS guarantee the smallest patch?**
|
|
460
|
-
No. It is deterministic and usually compact, but not guaranteed to be minimal.
|
|
461
|
-
|
|
462
|
-
**How do I merge states from two peers?**
|
|
463
|
-
Use `forkState(origin, actor)` to create each peer from the same origin, then `mergeState(local, remote, { actor: localActorId })`. Each peer should keep a stable unique actor ID across merges. See the [Multi-Peer Sync](#multi-peer-sync) example above.
|
|
464
|
-
|
|
465
|
-
**Why did `forkState` throw about actor uniqueness?**
|
|
466
|
-
By default, `forkState` blocks reusing `origin.clock.actor` because same-actor forks can mint duplicate dots and produce order-dependent merges. If you intentionally need same-actor cloning, pass `forkState(origin, actor, { allowActorReuse: true })`.
|
|
467
|
-
|
|
468
|
-
**Why can my local counter jump after a merge?**
|
|
469
|
-
Array inserts that target an existing predecessor may need to outrank sibling insert dots for deterministic ordering. The library can fast-forward the local counter in constant time to avoid expensive loops, but the resulting counter value may still jump upward when merging with peers that already have high counters.
|
|
153
|
+
## Notes
|
|
470
154
|
|
|
471
|
-
|
|
472
|
-
|
|
155
|
+
- Arrays use a CRDT sequence internally; concurrent inserts are preserved.
|
|
156
|
+
- Patches are interpreted relative to a snapshot (RFC-style sequential execution by default).
|
|
157
|
+
- Merge assumes replicas come from the same origin state (use `forkState`).
|
|
473
158
|
|
|
474
|
-
##
|
|
159
|
+
## License
|
|
475
160
|
|
|
476
|
-
|
|
477
|
-
- Under highly skewed peer counters, local counters may jump upward after merges to preserve deterministic insert ordering.
|
|
478
|
-
- Merge requires both peers to have started from the same origin document so that shared elements have matching IDs.
|
|
161
|
+
MIT
|