@loro-dev/json-patch 0.0.0-stage → 0.1.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/dist/loro.js ADDED
@@ -0,0 +1,2710 @@
1
+ import { D as validateAndNormalizeJsonValue, E as setOwnProp, S as isPlainObject, _ as assertNoLoneSurrogates, c as apply, h as MIN_SAFE_BIG, i as diffStringAt, k as valuesEqual, m as MAX_SAFE_BIG, o as lisMovePairs, r as diff, s as patternMatches, u as ApplyError, w as pathsEqual, x as hasOwn, y as assertValidUtf16Range } from "./diff.js";
2
+ import { LoroCounter, LoroList, LoroMap, LoroMovableList, LoroText, LoroTree } from "loro-crdt";
3
+
4
+ //#region src/loro.ts
5
+ /** Sentinel {@link LoroNodeKind} storing a subtree or string as an atomic `LoroValue` instead of a CRDT container. */
6
+ const LoroValueKind = { kind: "Value" };
7
+ /** Helper returning `{ kind: "Container", containerType }` for {@link LoroSchema} rules. */
8
+ function containerKind(containerType) {
9
+ return {
10
+ kind: "Container",
11
+ containerType
12
+ };
13
+ }
14
+ const VALID_CONTAINER_TYPES = new Set([
15
+ "Map",
16
+ "List",
17
+ "MovableList",
18
+ "Text",
19
+ "Tree",
20
+ "Counter"
21
+ ]);
22
+ function isContainerTypeStr(s) {
23
+ return VALID_CONTAINER_TYPES.has(s);
24
+ }
25
+ function parseContainerTypeFromCid(cid) {
26
+ const colonIdx = cid.lastIndexOf(":");
27
+ if (colonIdx === -1) return void 0;
28
+ const t = cid.slice(colonIdx + 1);
29
+ return isContainerTypeStr(t) ? t : void 0;
30
+ }
31
+ function rootContainerId(name, ctype) {
32
+ return `cid:root-${name}:${ctype}`;
33
+ }
34
+ function docHasExistingContainer(doc, cid, shallowCache) {
35
+ if (cid.startsWith("cid:root-") && !cid.startsWith("cid:root-🤝")) {
36
+ const colonIdx = cid.lastIndexOf(":");
37
+ const rootName = colonIdx !== -1 ? cid.slice(9, colonIdx) : cid.slice(9);
38
+ const shallow = shallowCache ?? doc.getShallowValue();
39
+ return hasOwn(shallow, rootName) && shallow[rootName] === cid;
40
+ }
41
+ return doc.hasContainer(cid);
42
+ }
43
+ /**
44
+ * Declarative schema controlling how JSON paths map to `LoroDoc` containers vs atomic `LoroValue`s
45
+ * during {@link applyJsonPatchToLoro}, {@link loroToJson}, and {@link diffLoroJson}.
46
+ */
47
+ var LoroSchema = class LoroSchema {
48
+ roots;
49
+ rules;
50
+ defaultObject;
51
+ defaultArray;
52
+ defaultString;
53
+ constructor(config = {}) {
54
+ const map = /* @__PURE__ */ new Map();
55
+ if (config.roots instanceof Map) for (const [k, v] of config.roots.entries()) map.set(k, v);
56
+ else if (config.roots) {
57
+ const rec = config.roots;
58
+ const keys = Object.keys(rec).sort();
59
+ for (let i = 0; i < keys.length; i++) map.set(keys[i], rec[keys[i]]);
60
+ }
61
+ this.roots = map;
62
+ this.rules = config.rules ? config.rules.slice() : [];
63
+ this.defaultObject = config.defaultObject ?? containerKind("Map");
64
+ this.defaultArray = config.defaultArray ?? containerKind("List");
65
+ this.defaultString = config.defaultString ?? LoroValueKind;
66
+ }
67
+ root(name, containerType) {
68
+ const nextRoots = new Map(this.roots);
69
+ nextRoots.set(name, containerType);
70
+ return new LoroSchema({
71
+ roots: nextRoots,
72
+ rules: this.rules,
73
+ defaultObject: this.defaultObject,
74
+ defaultArray: this.defaultArray,
75
+ defaultString: this.defaultString
76
+ });
77
+ }
78
+ rule(pattern, kind) {
79
+ return new LoroSchema({
80
+ roots: this.roots,
81
+ rules: [...this.rules, {
82
+ pattern,
83
+ kind
84
+ }],
85
+ defaultObject: this.defaultObject,
86
+ defaultArray: this.defaultArray,
87
+ defaultString: this.defaultString
88
+ });
89
+ }
90
+ withDefaultObject(kind) {
91
+ return new LoroSchema({
92
+ roots: this.roots,
93
+ rules: this.rules,
94
+ defaultObject: kind,
95
+ defaultArray: this.defaultArray,
96
+ defaultString: this.defaultString
97
+ });
98
+ }
99
+ withDefaultArray(kind) {
100
+ return new LoroSchema({
101
+ roots: this.roots,
102
+ rules: this.rules,
103
+ defaultObject: this.defaultObject,
104
+ defaultArray: kind,
105
+ defaultString: this.defaultString
106
+ });
107
+ }
108
+ withDefaultString(kind) {
109
+ return new LoroSchema({
110
+ roots: this.roots,
111
+ rules: this.rules,
112
+ defaultObject: this.defaultObject,
113
+ defaultArray: this.defaultArray,
114
+ defaultString: kind
115
+ });
116
+ }
117
+ static discover(doc) {
118
+ const shallow = doc.getShallowValue();
119
+ const roots = /* @__PURE__ */ new Map();
120
+ const names = Object.keys(shallow).sort();
121
+ for (let i = 0; i < names.length; i++) {
122
+ const name = names[i];
123
+ const cid = shallow[name];
124
+ if (typeof cid === "string") {
125
+ const maybeType = parseContainerTypeFromCid(cid);
126
+ if (maybeType) roots.set(name, maybeType);
127
+ }
128
+ }
129
+ return new LoroSchema({ roots });
130
+ }
131
+ explicitKindAt(path) {
132
+ for (let i = 0; i < this.rules.length; i++) if (patternMatches(this.rules[i].pattern, path)) return this.rules[i].kind;
133
+ }
134
+ kindForNewValue(path, val) {
135
+ const explicit = this.explicitKindAt(path);
136
+ if (explicit) return explicit;
137
+ if (isPlainObject(val)) return this.defaultObject;
138
+ if (Array.isArray(val)) return this.defaultArray;
139
+ if (typeof val === "string") return this.defaultString;
140
+ return LoroValueKind;
141
+ }
142
+ };
143
+ /** Error thrown when applying JSON patches to or projecting from a `LoroDoc`. */
144
+ var LoroApplyError = class extends Error {
145
+ kind;
146
+ opIndex;
147
+ constructor(kind, message, opIndex) {
148
+ super(opIndex !== void 0 ? `op #${opIndex}: ${message}` : message);
149
+ this.name = "LoroApplyError";
150
+ this.kind = kind;
151
+ this.opIndex = opIndex;
152
+ }
153
+ };
154
+ function isLoroContainer(v) {
155
+ return v instanceof LoroMap || v instanceof LoroList || v instanceof LoroMovableList || v instanceof LoroText || v instanceof LoroTree || v instanceof LoroCounter;
156
+ }
157
+ function emptyContainerJson(ctype) {
158
+ switch (ctype) {
159
+ case "Map": return {};
160
+ case "List":
161
+ case "MovableList":
162
+ case "Tree": return [];
163
+ case "Text": return "";
164
+ case "Counter": return 0;
165
+ }
166
+ }
167
+ /** Projects an atomic `loro-crdt` `Value` into a {@link JsonValue}. */
168
+ function projectLoroValue(val) {
169
+ if (val === null || val === void 0) return null;
170
+ if (typeof val === "boolean" || typeof val === "string") return val;
171
+ if (typeof val === "number") {
172
+ if (!Number.isFinite(val)) throw new LoroApplyError("Value", "non-finite float in LoroValue");
173
+ return Object.is(val, -0) ? 0 : val;
174
+ }
175
+ if (typeof val === "bigint") return val;
176
+ if (isLoroContainer(val)) return projectContainer(val);
177
+ if (val instanceof Uint8Array) return new Uint8Array(val);
178
+ if (Array.isArray(val)) return val.map((item) => projectLoroValue(item));
179
+ if (typeof val === "object") {
180
+ const obj = val;
181
+ const out = {};
182
+ const keys = Object.keys(obj).sort();
183
+ for (let i = 0; i < keys.length; i++) {
184
+ const k = keys[i];
185
+ setOwnProp(out, k, projectLoroValue(obj[k]));
186
+ }
187
+ return out;
188
+ }
189
+ throw new LoroApplyError("Value", `unsupported Loro value type: ${typeof val}`);
190
+ }
191
+ function projectMap(map) {
192
+ const entries = map.entries().sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
193
+ const out = {};
194
+ for (let i = 0; i < entries.length; i++) {
195
+ const [k, v] = entries[i];
196
+ setOwnProp(out, k, isLoroContainer(v) ? projectContainer(v) : projectLoroValue(v));
197
+ }
198
+ return out;
199
+ }
200
+ function projectTreeNode(node) {
201
+ const meta = projectMap(node.data);
202
+ const childrenNodes = node.children() ?? [];
203
+ const children = new Array(childrenNodes.length);
204
+ for (let i = 0; i < childrenNodes.length; i++) children[i] = projectTreeNode(childrenNodes[i]);
205
+ return {
206
+ children,
207
+ id: node.id,
208
+ meta
209
+ };
210
+ }
211
+ /** Recursively projects a `LoroDoc` container (`Map`, `List`, `MovableList`, `Text`, `Tree`, `Counter`) into JSON. */
212
+ function projectContainer(container) {
213
+ if (container instanceof LoroMap) return projectMap(container);
214
+ if (container instanceof LoroList || container instanceof LoroMovableList) {
215
+ const items = container.toArray();
216
+ const out = new Array(items.length);
217
+ for (let i = 0; i < items.length; i++) {
218
+ const item = items[i];
219
+ out[i] = isLoroContainer(item) ? projectContainer(item) : projectLoroValue(item);
220
+ }
221
+ return out;
222
+ }
223
+ if (container instanceof LoroText) return container.toString();
224
+ if (container instanceof LoroTree) return container.roots().map((node) => projectTreeNode(node));
225
+ if (container instanceof LoroCounter) {
226
+ const v = container.value;
227
+ if (!Number.isFinite(v)) throw new LoroApplyError("Value", "non-finite counter value");
228
+ return Object.is(v, -0) ? 0 : v;
229
+ }
230
+ throw new LoroApplyError("Loro", "unknown container instance");
231
+ }
232
+ /** Projects a container identified by `cid`, returning the empty default JSON shape if not yet materialized. */
233
+ function projectContainerById(doc, cid, fallbackType) {
234
+ if (!docHasExistingContainer(doc, cid)) {
235
+ if (fallbackType) return emptyContainerJson(fallbackType);
236
+ const t = parseContainerTypeFromCid(cid);
237
+ return t ? emptyContainerJson(t) : null;
238
+ }
239
+ const c = doc.getContainerById(cid);
240
+ if (!c) return fallbackType ? emptyContainerJson(fallbackType) : null;
241
+ return projectContainer(c);
242
+ }
243
+ /**
244
+ * Projects all roots in `doc` matching `schema` (or discovered shallow roots if omitted) into a plain {@link JsonObject}.
245
+ */
246
+ function loroToJson(doc, schema) {
247
+ const effective = schema ?? LoroSchema.discover(doc);
248
+ const rootNames = Array.from(effective.roots.keys()).sort();
249
+ const shallow = doc.getShallowValue();
250
+ const out = {};
251
+ for (let i = 0; i < rootNames.length; i++) {
252
+ const name = rootNames[i];
253
+ const ctype = effective.roots.get(name);
254
+ const cid = rootContainerId(name, ctype);
255
+ if (!docHasExistingContainer(doc, cid, shallow)) setOwnProp(out, name, emptyContainerJson(ctype));
256
+ else {
257
+ const container = doc.getContainerById(cid);
258
+ setOwnProp(out, name, container ? projectContainer(container) : emptyContainerJson(ctype));
259
+ }
260
+ }
261
+ return out;
262
+ }
263
+ /** Converts a {@link JsonValue} into a primitive/nested `loro-crdt` `Value`. */
264
+ function jsonToLoroValue(val) {
265
+ if (val === null) return null;
266
+ if (typeof val === "boolean" || typeof val === "string") return val;
267
+ if (typeof val === "number") {
268
+ if (!Number.isFinite(val)) throw new LoroApplyError("Value", "non-finite float is forbidden");
269
+ return Object.is(val, -0) ? 0 : val;
270
+ }
271
+ if (typeof val === "bigint") {
272
+ if (val < MIN_SAFE_BIG || val > MAX_SAFE_BIG) throw new LoroApplyError("Value", `integer ${val} out of safe range for lossless Loro bridging`);
273
+ return Number(val);
274
+ }
275
+ if (val instanceof Uint8Array) return new Uint8Array(val);
276
+ if (Array.isArray(val)) return val.map((item) => jsonToLoroValue(item));
277
+ if (isPlainObject(val)) {
278
+ const out = {};
279
+ const keys = Object.keys(val);
280
+ for (let i = 0; i < keys.length; i++) {
281
+ const k = keys[i];
282
+ setOwnProp(out, k, jsonToLoroValue(val[k]));
283
+ }
284
+ return out;
285
+ }
286
+ throw new LoroApplyError("Value", `unsupported JsonValue type: ${typeof val}`);
287
+ }
288
+ function frontiersEqual(a, b) {
289
+ if (a.length === 0 && b.length === 0) return true;
290
+ if (a.length === 1 && b.length === 1) return a[0].peer === b[0].peer && a[0].counter === b[0].counter;
291
+ const mapA = /* @__PURE__ */ new Map();
292
+ for (let i = 0; i < a.length; i++) mapA.set(a[i].peer, a[i].counter);
293
+ const mapB = /* @__PURE__ */ new Map();
294
+ for (let i = 0; i < b.length; i++) mapB.set(b[i].peer, b[i].counter);
295
+ if (mapA.size !== mapB.size) return false;
296
+ for (const [peer, counter] of mapA.entries()) if (mapB.get(peer) !== counter) return false;
297
+ return true;
298
+ }
299
+ function markAncestors(doc, cid, dirtyAncestors, shallowCache) {
300
+ if (!docHasExistingContainer(doc, cid, shallowCache)) return;
301
+ let cur = doc.getContainerById(cid);
302
+ while (cur) {
303
+ let parent;
304
+ try {
305
+ parent = cur.parent();
306
+ } catch {
307
+ parent = void 0;
308
+ }
309
+ if (!parent) break;
310
+ dirtyAncestors.add(parent.id);
311
+ cur = parent;
312
+ }
313
+ }
314
+ function prependOpPath(op, prefix) {
315
+ switch (op.op) {
316
+ case "set": return {
317
+ op: "set",
318
+ path: [...prefix, ...op.path],
319
+ value: op.value
320
+ };
321
+ case "unset": return {
322
+ op: "unset",
323
+ path: [...prefix, ...op.path]
324
+ };
325
+ case "arr_splice": return {
326
+ op: "arr_splice",
327
+ path: [...prefix, ...op.path],
328
+ at: op.at,
329
+ del: op.del,
330
+ items: op.items
331
+ };
332
+ case "move": return {
333
+ op: "move",
334
+ from: [...prefix, ...op.from],
335
+ to: [...prefix, ...op.to]
336
+ };
337
+ case "str_splice": return {
338
+ op: "str_splice",
339
+ path: [...prefix, ...op.path],
340
+ at: op.at,
341
+ del: op.del,
342
+ ins: op.ins
343
+ };
344
+ }
345
+ }
346
+ const f64HashBuf = /* @__PURE__ */ new ArrayBuffer(8);
347
+ const f64HashView = new DataView(f64HashBuf);
348
+ function hashJsonForAlign(val) {
349
+ let h1 = 2166136261;
350
+ let h2 = 16777619;
351
+ function hashStr(s) {
352
+ for (let i = 0; i < s.length; i++) {
353
+ h1 = Math.imul(h1 ^ s.charCodeAt(i), 16777619);
354
+ h2 = Math.imul(h2 ^ s.charCodeAt(i), 2246822519);
355
+ }
356
+ }
357
+ function visit(v) {
358
+ if (v === null) {
359
+ h1 = Math.imul(h1 ^ 1, 16777619);
360
+ return;
361
+ }
362
+ if (typeof v === "boolean") {
363
+ h1 = Math.imul(h1 ^ (v ? 2 : 3), 16777619);
364
+ return;
365
+ }
366
+ if (typeof v === "number" || typeof v === "bigint") {
367
+ if (typeof v === "bigint") hashStr(`n:${v}`);
368
+ else {
369
+ const norm = v === 0 ? 0 : v;
370
+ if (Number.isFinite(norm) && Number.isInteger(norm) && norm >= -0x8000000000000000 && norm < 0x10000000000000000) hashStr(`n:${BigInt(norm)}`);
371
+ else {
372
+ f64HashView.setFloat64(0, norm, false);
373
+ hashStr(`f:${f64HashView.getUint32(0, false).toString(16)}:${f64HashView.getUint32(4, false).toString(16)}`);
374
+ }
375
+ }
376
+ return;
377
+ }
378
+ if (typeof v === "string") {
379
+ h1 = Math.imul(h1 ^ 5, 16777619);
380
+ hashStr(v);
381
+ return;
382
+ }
383
+ if (v instanceof Uint8Array) {
384
+ h1 = Math.imul(h1 ^ 6 ^ v.byteLength, 16777619);
385
+ for (let i = 0; i < v.byteLength; i++) h1 = Math.imul(h1 ^ v[i], 16777619);
386
+ return;
387
+ }
388
+ if (Array.isArray(v)) {
389
+ h1 = Math.imul(h1 ^ 7 ^ v.length, 16777619);
390
+ for (let i = 0; i < v.length; i++) visit(v[i]);
391
+ return;
392
+ }
393
+ if (isPlainObject(v)) {
394
+ const ks = Object.keys(v).sort();
395
+ h1 = Math.imul(h1 ^ 8 ^ ks.length, 16777619);
396
+ for (let i = 0; i < ks.length; i++) {
397
+ hashStr(ks[i]);
398
+ visit(v[ks[i]]);
399
+ }
400
+ }
401
+ }
402
+ visit(val);
403
+ return `${h1 >>> 0}:${h2 >>> 0}`;
404
+ }
405
+ /**
406
+ * Computes minimal CRDT-aware {@link JsonOp}s describing state changes between `fromFrontiers` and `toFrontiers`.
407
+ */
408
+ function diffLoroJson(doc, fromFrontiers, toFrontiers, schema) {
409
+ const fromCopy = fromFrontiers.slice();
410
+ const toCopy = toFrontiers.slice();
411
+ if (frontiersEqual(fromCopy, toCopy)) return [];
412
+ const diffBatch = doc.diff(fromCopy, toCopy, false);
413
+ const oplogF = doc.oplogFrontiers();
414
+ const stateMatchesOplog = frontiersEqual(doc.frontiers(), oplogF);
415
+ const docFrom = stateMatchesOplog && frontiersEqual(fromCopy, oplogF) ? doc : doc.forkAt(fromCopy);
416
+ const docTo = stateMatchesOplog && frontiersEqual(toCopy, oplogF) ? doc : doc.forkAt(toCopy);
417
+ const shallowFrom = docFrom.getShallowValue();
418
+ const shallowTo = docTo.getShallowValue();
419
+ const diffMap = /* @__PURE__ */ new Map();
420
+ const changedCids = /* @__PURE__ */ new Set();
421
+ const dirtyAncestors = /* @__PURE__ */ new Set();
422
+ for (let i = 0; i < diffBatch.length; i++) {
423
+ const [cid, d] = diffBatch[i];
424
+ changedCids.add(cid);
425
+ diffMap.set(cid, d);
426
+ markAncestors(docTo, cid, dirtyAncestors, shallowTo);
427
+ markAncestors(docFrom, cid, dirtyAncestors, shallowFrom);
428
+ }
429
+ const ops = [];
430
+ const rootNames = Array.from(schema.roots.keys()).sort();
431
+ for (let i = 0; i < rootNames.length; i++) {
432
+ const name = rootNames[i];
433
+ const ctype = schema.roots.get(name);
434
+ const cid = rootContainerId(name, ctype);
435
+ const existsFrom = docHasExistingContainer(docFrom, cid, shallowFrom);
436
+ const existsTo = docHasExistingContainer(docTo, cid, shallowTo);
437
+ if (!changedCids.has(cid) && !dirtyAncestors.has(cid) && existsFrom === existsTo) continue;
438
+ diffContainerById(docFrom, docTo, shallowFrom, shallowTo, cid, ctype, [name], changedCids, dirtyAncestors, diffMap, ops);
439
+ }
440
+ return ops;
441
+ }
442
+ function diffContainerById(docFrom, docTo, shallowFrom, shallowTo, cid, expectedType, path, changedCids, dirtyAncestors, diffMap, ops) {
443
+ const hasFrom = docHasExistingContainer(docFrom, cid, shallowFrom);
444
+ const hasTo = docHasExistingContainer(docTo, cid, shallowTo);
445
+ if (!changedCids.has(cid) && !dirtyAncestors.has(cid) && hasFrom === hasTo) return;
446
+ const ctype = expectedType ?? parseContainerTypeFromCid(cid) ?? "Map";
447
+ if (!hasFrom && !hasTo) return;
448
+ if (hasFrom && !hasTo) {
449
+ const cFrom$1 = docFrom.getContainerById(cid);
450
+ const jFrom = cFrom$1 ? projectContainer(cFrom$1) : emptyContainerJson(ctype);
451
+ const jTo = emptyContainerJson(ctype);
452
+ if (!valuesEqual(jFrom, jTo)) {
453
+ const subOps = diff(jFrom, jTo);
454
+ for (let i = 0; i < subOps.length; i++) ops.push(prependOpPath(subOps[i], path));
455
+ }
456
+ return;
457
+ }
458
+ if (!hasFrom && hasTo) {
459
+ const jFrom = emptyContainerJson(ctype);
460
+ const cTo$1 = docTo.getContainerById(cid);
461
+ const jTo = cTo$1 ? projectContainer(cTo$1) : jFrom;
462
+ if (!valuesEqual(jFrom, jTo)) {
463
+ const subOps = diff(jFrom, jTo);
464
+ for (let i = 0; i < subOps.length; i++) ops.push(prependOpPath(subOps[i], path));
465
+ }
466
+ return;
467
+ }
468
+ const cFrom = docFrom.getContainerById(cid);
469
+ const cTo = docTo.getContainerById(cid);
470
+ if (!cFrom || !cTo) return;
471
+ diffContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
472
+ }
473
+ function diffContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops) {
474
+ if (cFrom instanceof LoroMap && cTo instanceof LoroMap) {
475
+ diffMapContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
476
+ return;
477
+ }
478
+ if (cFrom instanceof LoroList && cTo instanceof LoroList) {
479
+ diffListContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
480
+ return;
481
+ }
482
+ if (cFrom instanceof LoroMovableList && cTo instanceof LoroMovableList) {
483
+ diffMovableListContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
484
+ return;
485
+ }
486
+ if (cFrom instanceof LoroText && cTo instanceof LoroText) {
487
+ diffTextContainer(cFrom, cTo, path, diffMap, ops);
488
+ return;
489
+ }
490
+ if (cFrom instanceof LoroTree && cTo instanceof LoroTree) {
491
+ diffTreeContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
492
+ return;
493
+ }
494
+ if (cFrom instanceof LoroCounter && cTo instanceof LoroCounter) {
495
+ const v1 = Object.is(cFrom.value, -0) ? 0 : cFrom.value;
496
+ const v2 = Object.is(cTo.value, -0) ? 0 : cTo.value;
497
+ if (v1 !== v2) ops.push({
498
+ op: "set",
499
+ path: path.slice(),
500
+ value: v2
501
+ });
502
+ return;
503
+ }
504
+ const j1 = projectContainer(cFrom);
505
+ const j2 = projectContainer(cTo);
506
+ if (!valuesEqual(j1, j2)) ops.push({
507
+ op: "set",
508
+ path: path.slice(),
509
+ value: j2
510
+ });
511
+ }
512
+ function diffMapContainer(docFrom, docTo, mapFrom, mapTo, path, changedCids, dirtyAncestors, diffMap, ops) {
513
+ const fromMap = /* @__PURE__ */ new Map();
514
+ const fromEntries = mapFrom.entries();
515
+ for (let i = 0; i < fromEntries.length; i++) fromMap.set(fromEntries[i][0], fromEntries[i][1]);
516
+ const toMap = /* @__PURE__ */ new Map();
517
+ const toEntries = mapTo.entries();
518
+ for (let i = 0; i < toEntries.length; i++) toMap.set(toEntries[i][0], toEntries[i][1]);
519
+ const fromKeys = Array.from(fromMap.keys()).sort();
520
+ for (let i = 0; i < fromKeys.length; i++) {
521
+ const k = fromKeys[i];
522
+ if (!toMap.has(k)) ops.push({
523
+ op: "unset",
524
+ path: [...path, k]
525
+ });
526
+ }
527
+ const toKeys = Array.from(toMap.keys()).sort();
528
+ for (let i = 0; i < toKeys.length; i++) {
529
+ const k = toKeys[i];
530
+ const vocTo = toMap.get(k);
531
+ path.push(k);
532
+ if (!fromMap.has(k)) ops.push({
533
+ op: "set",
534
+ path: path.slice(),
535
+ value: isLoroContainer(vocTo) ? projectContainer(vocTo) : projectLoroValue(vocTo)
536
+ });
537
+ else diffVocPair(docFrom, docTo, fromMap.get(k), vocTo, path, changedCids, dirtyAncestors, diffMap, ops);
538
+ path.pop();
539
+ }
540
+ }
541
+ function diffVocPair(docFrom, docTo, vocFrom, vocTo, path, changedCids, dirtyAncestors, diffMap, ops) {
542
+ if (isLoroContainer(vocFrom) && isLoroContainer(vocTo) && vocFrom.id === vocTo.id) {
543
+ if (changedCids.has(vocFrom.id) || dirtyAncestors.has(vocFrom.id)) diffContainer(docFrom, docTo, vocFrom, vocTo, path, changedCids, dirtyAncestors, diffMap, ops);
544
+ return;
545
+ }
546
+ if (!isLoroContainer(vocFrom) && !isLoroContainer(vocTo)) {
547
+ const j1$1 = projectLoroValue(vocFrom);
548
+ const j2$1 = projectLoroValue(vocTo);
549
+ if (!valuesEqual(j1$1, j2$1)) {
550
+ const subOps = diffPureValue(j1$1, j2$1);
551
+ for (let i = 0; i < subOps.length; i++) ops.push(prependOpPath(subOps[i], path));
552
+ }
553
+ return;
554
+ }
555
+ const j1 = isLoroContainer(vocFrom) ? projectContainer(vocFrom) : projectLoroValue(vocFrom);
556
+ const j2 = isLoroContainer(vocTo) ? projectContainer(vocTo) : projectLoroValue(vocTo);
557
+ if (!valuesEqual(j1, j2)) ops.push({
558
+ op: "set",
559
+ path: path.slice(),
560
+ value: j2
561
+ });
562
+ }
563
+ function diffPureValue(oldVal, newVal) {
564
+ return diff(oldVal, newVal);
565
+ }
566
+ function diffTextContainer(textFrom, textTo, path, diffMap, ops) {
567
+ const sFrom = textFrom.toString();
568
+ const sTo = textTo.toString();
569
+ if (sFrom === sTo) return;
570
+ const diff$1 = diffMap.get(textTo.id);
571
+ if (diff$1 && diff$1.type === "text") {
572
+ let cur = sFrom;
573
+ let cursor = 0;
574
+ const localOps = [];
575
+ let ok = true;
576
+ for (let i = 0; i < diff$1.diff.length; i++) {
577
+ const d = diff$1.diff[i];
578
+ if (d.retain !== void 0) {
579
+ cursor += d.retain;
580
+ if (cursor > cur.length) {
581
+ ok = false;
582
+ break;
583
+ }
584
+ } else if (d.delete !== void 0) {
585
+ if (d.delete > 0) {
586
+ if (cursor + d.delete > cur.length) {
587
+ ok = false;
588
+ break;
589
+ }
590
+ try {
591
+ assertValidUtf16Range(cur, cursor, d.delete, 0);
592
+ } catch {
593
+ ok = false;
594
+ break;
595
+ }
596
+ cur = cur.slice(0, cursor) + cur.slice(cursor + d.delete);
597
+ const prev = localOps[localOps.length - 1];
598
+ if (prev && prev.op === "str_splice" && cursor === prev.at + prev.ins.length) localOps[localOps.length - 1] = {
599
+ ...prev,
600
+ del: prev.del + d.delete
601
+ };
602
+ else localOps.push({
603
+ op: "str_splice",
604
+ path: path.slice(),
605
+ at: cursor,
606
+ del: d.delete,
607
+ ins: ""
608
+ });
609
+ }
610
+ } else if (d.insert !== void 0) {
611
+ if (d.insert.length > 0) {
612
+ cur = cur.slice(0, cursor) + d.insert + cur.slice(cursor);
613
+ const prev = localOps[localOps.length - 1];
614
+ if (prev && prev.op === "str_splice" && cursor === prev.at + prev.ins.length) localOps[localOps.length - 1] = {
615
+ ...prev,
616
+ ins: prev.ins + d.insert
617
+ };
618
+ else localOps.push({
619
+ op: "str_splice",
620
+ path: path.slice(),
621
+ at: cursor,
622
+ del: 0,
623
+ ins: d.insert
624
+ });
625
+ cursor += d.insert.length;
626
+ }
627
+ }
628
+ }
629
+ if (ok && cur === sTo) {
630
+ for (let i = 0; i < localOps.length; i++) ops.push(localOps[i]);
631
+ return;
632
+ }
633
+ }
634
+ diffStringAt(path, sFrom, sTo, ops);
635
+ }
636
+ function diffListContainer(docFrom, docTo, listFrom, listTo, path, changedCids, dirtyAncestors, diffMap, ops) {
637
+ const fromItems = listFrom.toArray();
638
+ const toItems = listTo.toArray();
639
+ const retainedChildren = [];
640
+ const diff$1 = diffMap.get(listTo.id);
641
+ if (diff$1 && diff$1.type === "list") {
642
+ let oldIdx = 0;
643
+ let curIdx = 0;
644
+ for (let i = 0; i < diff$1.diff.length; i++) {
645
+ const delta = diff$1.diff[i];
646
+ if (delta.retain !== void 0) {
647
+ for (let k = 0; k < delta.retain; k++) {
648
+ const v1 = fromItems[oldIdx + k];
649
+ const v2 = toItems[curIdx + k];
650
+ if (isLoroContainer(v1) && isLoroContainer(v2) && v1.id === v2.id) retainedChildren.push({
651
+ fromC: v1,
652
+ toC: v2,
653
+ idx: curIdx + k
654
+ });
655
+ }
656
+ oldIdx += delta.retain;
657
+ curIdx += delta.retain;
658
+ } else if (delta.delete !== void 0) {
659
+ if (delta.delete > 0) {
660
+ ops.push({
661
+ op: "arr_splice",
662
+ path: path.slice(),
663
+ at: curIdx,
664
+ del: delta.delete,
665
+ items: []
666
+ });
667
+ oldIdx += delta.delete;
668
+ }
669
+ } else if (delta.insert !== void 0) {
670
+ const insLen = delta.insert.length;
671
+ if (insLen > 0) {
672
+ const projected = new Array(insLen);
673
+ for (let k = 0; k < insLen; k++) {
674
+ const v2 = toItems[curIdx + k];
675
+ projected[k] = isLoroContainer(v2) ? projectContainer(v2) : projectLoroValue(v2);
676
+ }
677
+ const prev = ops[ops.length - 1];
678
+ if (prev && prev.op === "arr_splice" && prev.items.length === 0 && prev.at === curIdx && pathsEqual(prev.path, path)) ops[ops.length - 1] = {
679
+ ...prev,
680
+ items: projected
681
+ };
682
+ else ops.push({
683
+ op: "arr_splice",
684
+ path: path.slice(),
685
+ at: curIdx,
686
+ del: 0,
687
+ items: projected
688
+ });
689
+ curIdx += insLen;
690
+ }
691
+ }
692
+ }
693
+ const tailLen = Math.min(fromItems.length - oldIdx, toItems.length - curIdx);
694
+ for (let k = 0; k < tailLen; k++) {
695
+ const v1 = fromItems[oldIdx + k];
696
+ const v2 = toItems[curIdx + k];
697
+ if (isLoroContainer(v1) && isLoroContainer(v2) && v1.id === v2.id) retainedChildren.push({
698
+ fromC: v1,
699
+ toC: v2,
700
+ idx: curIdx + k
701
+ });
702
+ }
703
+ } else for (let i = 0; i < toItems.length && i < fromItems.length; i++) {
704
+ const v1 = fromItems[i];
705
+ const v2 = toItems[i];
706
+ if (isLoroContainer(v1) && isLoroContainer(v2) && v1.id === v2.id) retainedChildren.push({
707
+ fromC: v1,
708
+ toC: v2,
709
+ idx: i
710
+ });
711
+ }
712
+ for (let i = 0; i < retainedChildren.length; i++) {
713
+ const { fromC, toC, idx } = retainedChildren[i];
714
+ if (changedCids.has(toC.id) || dirtyAncestors.has(toC.id)) {
715
+ path.push(idx);
716
+ diffContainer(docFrom, docTo, fromC, toC, path, changedCids, dirtyAncestors, diffMap, ops);
717
+ path.pop();
718
+ }
719
+ }
720
+ }
721
+ function diffMovableListContainer(docFrom, docTo, mlFrom, mlTo, path, changedCids, dirtyAncestors, diffMap, ops) {
722
+ const fromItems = mlFrom.toArray();
723
+ const toItems = mlTo.toArray();
724
+ const lenFrom = fromItems.length;
725
+ const lenTo = toItems.length;
726
+ const oldToNew = new Array(lenFrom).fill(-1);
727
+ const newToOld = new Array(lenTo).fill(-1);
728
+ const cidMap = /* @__PURE__ */ new Map();
729
+ for (let i$1 = 0; i$1 < lenFrom; i$1++) {
730
+ const item = fromItems[i$1];
731
+ if (isLoroContainer(item)) cidMap.set(item.id, i$1);
732
+ }
733
+ for (let j$1 = 0; j$1 < lenTo; j$1++) {
734
+ const item = toItems[j$1];
735
+ if (isLoroContainer(item)) {
736
+ const oi = cidMap.get(item.id);
737
+ if (oi !== void 0) {
738
+ oldToNew[oi] = j$1;
739
+ newToOld[j$1] = oi;
740
+ }
741
+ }
742
+ }
743
+ const cursorMap = /* @__PURE__ */ new Map();
744
+ for (let i$1 = 0; i$1 < lenFrom; i$1++) {
745
+ if (oldToNew[i$1] !== -1) continue;
746
+ const pos = mlFrom.getCursor(i$1, 0)?.pos();
747
+ if (pos) {
748
+ const k = `${pos.peer}:${pos.counter}`;
749
+ if (!cursorMap.has(k)) cursorMap.set(k, i$1);
750
+ }
751
+ }
752
+ for (let j$1 = 0; j$1 < lenTo; j$1++) {
753
+ if (newToOld[j$1] !== -1) continue;
754
+ const pos = mlTo.getCursor(j$1, 0)?.pos();
755
+ if (pos) {
756
+ const k = `${pos.peer}:${pos.counter}`;
757
+ const oi = cursorMap.get(k);
758
+ if (oi !== void 0 && oldToNew[oi] === -1) {
759
+ oldToNew[oi] = j$1;
760
+ newToOld[j$1] = oi;
761
+ }
762
+ }
763
+ }
764
+ const fromJsonCache = new Array(lenFrom);
765
+ const toJsonCache = new Array(lenTo);
766
+ const getFromJson = (i$1) => {
767
+ if (fromJsonCache[i$1] === void 0) {
768
+ const v = fromItems[i$1];
769
+ fromJsonCache[i$1] = isLoroContainer(v) ? projectContainer(v) : projectLoroValue(v);
770
+ }
771
+ return fromJsonCache[i$1];
772
+ };
773
+ const getToJson = (j$1) => {
774
+ if (toJsonCache[j$1] === void 0) {
775
+ const v = toItems[j$1];
776
+ toJsonCache[j$1] = isLoroContainer(v) ? projectContainer(v) : projectLoroValue(v);
777
+ }
778
+ return toJsonCache[j$1];
779
+ };
780
+ const buckets = /* @__PURE__ */ new Map();
781
+ for (let i$1 = lenFrom - 1; i$1 >= 0; i$1--) {
782
+ if (oldToNew[i$1] !== -1) continue;
783
+ const h = hashJsonForAlign(getFromJson(i$1));
784
+ let q = buckets.get(h);
785
+ if (!q) {
786
+ q = [];
787
+ buckets.set(h, q);
788
+ }
789
+ q.push(i$1);
790
+ }
791
+ for (let j$1 = 0; j$1 < lenTo; j$1++) {
792
+ if (newToOld[j$1] !== -1) continue;
793
+ const targetVal = getToJson(j$1);
794
+ const h = hashJsonForAlign(targetVal);
795
+ const q = buckets.get(h);
796
+ if (!q) continue;
797
+ for (let qi = q.length - 1; qi >= 0; qi--) {
798
+ const oi = q[qi];
799
+ if (valuesEqual(getFromJson(oi), targetVal)) {
800
+ if (qi === q.length - 1) q.pop();
801
+ else q.splice(qi, 1);
802
+ oldToNew[oi] = j$1;
803
+ newToOld[j$1] = oi;
804
+ break;
805
+ }
806
+ }
807
+ }
808
+ let i = lenFrom;
809
+ while (i > 0) {
810
+ i--;
811
+ if (oldToNew[i] === -1) {
812
+ let delCnt = 1;
813
+ while (i > 0 && oldToNew[i - 1] === -1) {
814
+ i--;
815
+ delCnt++;
816
+ }
817
+ ops.push({
818
+ op: "arr_splice",
819
+ path: path.slice(),
820
+ at: i,
821
+ del: delCnt,
822
+ items: []
823
+ });
824
+ }
825
+ }
826
+ const oldIdxToCompact = new Array(lenFrom).fill(-1);
827
+ let compactCnt = 0;
828
+ for (let oi = 0; oi < lenFrom; oi++) if (oldToNew[oi] !== -1) oldIdxToCompact[oi] = compactCnt++;
829
+ const targetSeq = [];
830
+ for (let nj = 0; nj < lenTo; nj++) {
831
+ const oi = newToOld[nj];
832
+ if (oi !== -1) targetSeq.push(oldIdxToCompact[oi]);
833
+ }
834
+ if (compactCnt > 1) {
835
+ const pairs = lisMovePairs(targetSeq);
836
+ for (let m = 0; m < pairs.length; m++) {
837
+ const [fromIdx, toIdx] = pairs[m];
838
+ ops.push({
839
+ op: "move",
840
+ from: [...path, fromIdx],
841
+ to: [...path, toIdx]
842
+ });
843
+ }
844
+ }
845
+ let j = 0;
846
+ while (j < lenTo) if (newToOld[j] === -1) {
847
+ const start = j;
848
+ const items = [];
849
+ while (j < lenTo && newToOld[j] === -1) {
850
+ items.push(getToJson(j));
851
+ j++;
852
+ }
853
+ ops.push({
854
+ op: "arr_splice",
855
+ path: path.slice(),
856
+ at: start,
857
+ del: 0,
858
+ items
859
+ });
860
+ } else j++;
861
+ for (let nj = 0; nj < lenTo; nj++) {
862
+ const oi = newToOld[nj];
863
+ if (oi === -1) continue;
864
+ path.push(nj);
865
+ diffVocPair(docFrom, docTo, fromItems[oi], toItems[nj], path, changedCids, dirtyAncestors, diffMap, ops);
866
+ path.pop();
867
+ }
868
+ }
869
+ function buildDiffSimTree(tree) {
870
+ function wrap(nodes) {
871
+ return nodes.map((n) => ({
872
+ id: n.id,
873
+ children: wrap(n.children() ?? [])
874
+ }));
875
+ }
876
+ return wrap(tree.roots());
877
+ }
878
+ function collectDiffTreeIds(nodes, out) {
879
+ for (let i = 0; i < nodes.length; i++) {
880
+ out.add(nodes[i].id);
881
+ collectDiffTreeIds(nodes[i].children, out);
882
+ }
883
+ }
884
+ function anyDiffTreeDescIn(node, set) {
885
+ for (let i = 0; i < node.children.length; i++) {
886
+ const c = node.children[i];
887
+ if (set.has(c.id) || anyDiffTreeDescIn(c, set)) return true;
888
+ }
889
+ return false;
890
+ }
891
+ function findDiffTreeNodePath(nodes, target, prefix) {
892
+ for (let i = 0; i < nodes.length; i++) {
893
+ if (nodes[i].id === target) return [...prefix, i];
894
+ const found = findDiffTreeNodePath(nodes[i].children, target, [
895
+ ...prefix,
896
+ i,
897
+ "children"
898
+ ]);
899
+ if (found) return found;
900
+ }
901
+ }
902
+ function takeDiffTreeNode(nodes, target) {
903
+ for (let i = 0; i < nodes.length; i++) {
904
+ if (nodes[i].id === target) return nodes.splice(i, 1)[0];
905
+ const found = takeDiffTreeNode(nodes[i].children, target);
906
+ if (found) return found;
907
+ }
908
+ }
909
+ function findDiffTreeChildren(roots, parentId) {
910
+ if (parentId === void 0) return roots;
911
+ function findNode(nodes) {
912
+ for (let i = 0; i < nodes.length; i++) {
913
+ if (nodes[i].id === parentId) return nodes[i];
914
+ const f = findNode(nodes[i].children);
915
+ if (f) return f;
916
+ }
917
+ }
918
+ return findNode(roots)?.children;
919
+ }
920
+ function diffTreeParentChildrenPath(roots, treePath, parentId) {
921
+ if (parentId === void 0) return {
922
+ path: treePath.slice(),
923
+ len: roots.length
924
+ };
925
+ const np = findDiffTreeNodePath(roots, parentId, treePath.slice());
926
+ if (!np) return void 0;
927
+ const list = findDiffTreeChildren(roots, parentId);
928
+ return {
929
+ path: [...np, "children"],
930
+ len: list ? list.length : 0
931
+ };
932
+ }
933
+ function diffTreeContainer(docFrom, docTo, treeFrom, treeTo, treePath, changedCids, dirtyAncestors, diffMap, ops) {
934
+ const curRoots = buildDiffSimTree(treeFrom);
935
+ const toRoots = buildDiffSimTree(treeTo);
936
+ const oldIds = /* @__PURE__ */ new Set();
937
+ collectDiffTreeIds(curRoots, oldIds);
938
+ const newIds = /* @__PURE__ */ new Set();
939
+ collectDiffTreeIds(toRoots, newIds);
940
+ const placedWhole = /* @__PURE__ */ new Set();
941
+ function placePreorder(parentId, targetNodes) {
942
+ for (let i = 0; i < targetNodes.length; i++) {
943
+ const tn = targetNodes[i];
944
+ if (placedWhole.has(tn.id)) continue;
945
+ if (!oldIds.has(tn.id)) {
946
+ const parentInfo = diffTreeParentChildrenPath(curRoots, treePath, parentId);
947
+ if (!anyDiffTreeDescIn(tn, oldIds)) {
948
+ const fullNode = treeTo.getNodeByID(tn.id);
949
+ ops.push({
950
+ op: "arr_splice",
951
+ path: parentInfo.path,
952
+ at: parentInfo.len,
953
+ del: 0,
954
+ items: [projectTreeNode(fullNode)]
955
+ });
956
+ findDiffTreeChildren(curRoots, parentId).push({
957
+ id: tn.id,
958
+ children: tn.children.slice()
959
+ });
960
+ collectDiffTreeIds([tn], placedWhole);
961
+ continue;
962
+ } else {
963
+ const nodeTo = treeTo.getNodeByID(tn.id);
964
+ const shell = {
965
+ children: [],
966
+ id: tn.id,
967
+ meta: projectMap(nodeTo.data)
968
+ };
969
+ ops.push({
970
+ op: "arr_splice",
971
+ path: parentInfo.path,
972
+ at: parentInfo.len,
973
+ del: 0,
974
+ items: [shell]
975
+ });
976
+ findDiffTreeChildren(curRoots, parentId).push({
977
+ id: tn.id,
978
+ children: []
979
+ });
980
+ }
981
+ } else if (!findDiffTreeChildren(curRoots, parentId).some((s) => s.id === tn.id)) {
982
+ const fromPath = findDiffTreeNodePath(curRoots, tn.id, treePath.slice());
983
+ const moved = takeDiffTreeNode(curRoots, tn.id);
984
+ const toInfo = diffTreeParentChildrenPath(curRoots, treePath, parentId);
985
+ ops.push({
986
+ op: "move",
987
+ from: fromPath,
988
+ to: [...toInfo.path, toInfo.len]
989
+ });
990
+ findDiffTreeChildren(curRoots, parentId).push(moved);
991
+ }
992
+ placePreorder(tn.id, tn.children);
993
+ }
994
+ }
995
+ placePreorder(void 0, toRoots);
996
+ function deleteDoomed(childrenPath, nodes) {
997
+ let idx = nodes.length;
998
+ while (idx > 0) {
999
+ idx--;
1000
+ if (!newIds.has(nodes[idx].id)) {
1001
+ let delCnt = 1;
1002
+ while (idx > 0 && !newIds.has(nodes[idx - 1].id)) {
1003
+ idx--;
1004
+ delCnt++;
1005
+ }
1006
+ ops.push({
1007
+ op: "arr_splice",
1008
+ path: childrenPath.slice(),
1009
+ at: idx,
1010
+ del: delCnt,
1011
+ items: []
1012
+ });
1013
+ nodes.splice(idx, delCnt);
1014
+ } else deleteDoomed([
1015
+ ...childrenPath,
1016
+ idx,
1017
+ "children"
1018
+ ], nodes[idx].children);
1019
+ }
1020
+ }
1021
+ deleteDoomed(treePath.slice(), curRoots);
1022
+ function reorderAndDiffMeta(childrenPath, curNodes, targetNodes) {
1023
+ if (targetNodes.length > 1) {
1024
+ const curIdxMap = /* @__PURE__ */ new Map();
1025
+ for (let i = 0; i < curNodes.length; i++) curIdxMap.set(curNodes[i].id, i);
1026
+ const targetSeq = targetNodes.map((tn) => curIdxMap.get(tn.id));
1027
+ const pairs = lisMovePairs(targetSeq);
1028
+ if (pairs.length > 0) {
1029
+ for (let m = 0; m < pairs.length; m++) {
1030
+ const [fromIdx, toIdx] = pairs[m];
1031
+ ops.push({
1032
+ op: "move",
1033
+ from: [...childrenPath, fromIdx],
1034
+ to: [...childrenPath, toIdx]
1035
+ });
1036
+ }
1037
+ const reordered = new Array(targetSeq.length);
1038
+ for (let i = 0; i < targetSeq.length; i++) reordered[i] = curNodes[targetSeq[i]];
1039
+ for (let i = 0; i < reordered.length; i++) curNodes[i] = reordered[i];
1040
+ }
1041
+ }
1042
+ for (let i = 0; i < targetNodes.length; i++) {
1043
+ const cn = curNodes[i];
1044
+ const tn = targetNodes[i];
1045
+ if (!placedWhole.has(tn.id)) {
1046
+ const nodePath = [...childrenPath, i];
1047
+ if (oldIds.has(tn.id)) {
1048
+ const metaFrom = treeFrom.getNodeByID(tn.id).data;
1049
+ const metaTo = treeTo.getNodeByID(tn.id).data;
1050
+ const metaId = metaTo.id;
1051
+ if (changedCids.has(metaId) || dirtyAncestors.has(metaId)) diffMapContainer(docFrom, docTo, metaFrom, metaTo, [...nodePath, "meta"], changedCids, dirtyAncestors, diffMap, ops);
1052
+ }
1053
+ reorderAndDiffMeta([...nodePath, "children"], cn.children, tn.children);
1054
+ }
1055
+ }
1056
+ }
1057
+ reorderAndDiffMeta(treePath.slice(), curRoots, toRoots);
1058
+ }
1059
+ function normZeroF64(v) {
1060
+ return v === 0 ? 0 : v;
1061
+ }
1062
+ function computeCounterSteps(cur, targetV) {
1063
+ const rawD1 = targetV - cur;
1064
+ const d1 = normZeroF64(Number.isFinite(rawD1) ? rawD1 : -cur);
1065
+ const mid = cur + d1;
1066
+ const d2 = normZeroF64(targetV - mid);
1067
+ if (Number.isFinite(d1) && Number.isFinite(d2) && mid + d2 === targetV) return {
1068
+ d1,
1069
+ d2
1070
+ };
1071
+ }
1072
+ function validateCounterTarget(value, cur, opIndex) {
1073
+ let rawTarget;
1074
+ if (typeof value === "number") rawTarget = value;
1075
+ else if (typeof value === "bigint") {
1076
+ if (value < MIN_SAFE_BIG || value > MAX_SAFE_BIG) throw new LoroApplyError("Value", `integer ${value} out of safe range for lossless Loro counter`, opIndex);
1077
+ rawTarget = Number(value);
1078
+ } else throw new LoroApplyError("SchemaViolation", "LoroCounter requires numeric value", opIndex);
1079
+ if (!Number.isFinite(rawTarget)) throw new LoroApplyError("Value", "non-finite float is forbidden", opIndex);
1080
+ const target = normZeroF64(rawTarget);
1081
+ const steps = computeCounterSteps(cur, target);
1082
+ if (!steps) throw new LoroApplyError("Value", "non-finite counter delta", opIndex);
1083
+ return {
1084
+ target,
1085
+ d1: steps.d1,
1086
+ d2: steps.d2
1087
+ };
1088
+ }
1089
+ function checkSafeSpliceBounds(at, del, len, opIndex) {
1090
+ if (!Number.isSafeInteger(at) || at < 0 || !Number.isSafeInteger(del) || del < 0) throw new ApplyError("IndexOutOfBounds", opIndex, "invalid splice bounds");
1091
+ const end = at + del;
1092
+ if (!Number.isSafeInteger(end) || at > len || end > len) throw new ApplyError("IndexOutOfBounds", opIndex, `arr_splice range ${at}..${end} out of bounds for length ${len}`);
1093
+ return end;
1094
+ }
1095
+ function spliceInPlace(arr, at, del, items) {
1096
+ if (items.length < 32768) {
1097
+ arr.splice(at, del, ...items);
1098
+ return;
1099
+ }
1100
+ const tail = arr.slice(at + del);
1101
+ arr.length = at;
1102
+ for (let i = 0; i < items.length; i++) arr.push(items[i]);
1103
+ for (let i = 0; i < tail.length; i++) arr.push(tail[i]);
1104
+ }
1105
+ function stepThroughTree(treeRoots, rest, opIndex) {
1106
+ let curList = treeRoots;
1107
+ let i = 0;
1108
+ while (true) {
1109
+ if (i >= rest.length) throw new LoroApplyError("SchemaViolation", "cannot address LoroTree children directly in this operation", opIndex);
1110
+ const nodeIdx = rest[i];
1111
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) throw new ApplyError("TypeMismatch", opIndex, "expected Array index");
1112
+ if (nodeIdx >= curList.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${nodeIdx} out of bounds for length ${curList.length}`);
1113
+ const node = curList[nodeIdx];
1114
+ i++;
1115
+ if (i >= rest.length) throw new LoroApplyError("SchemaViolation", "cannot address LoroTree node directly in this operation", opIndex);
1116
+ const field = rest[i];
1117
+ if (typeof field !== "string") throw new ApplyError("TypeMismatch", opIndex, "expected Object key");
1118
+ if (field === "children") {
1119
+ i++;
1120
+ curList = node.children;
1121
+ } else if (field === "meta") {
1122
+ i++;
1123
+ return {
1124
+ metaNode: node.meta,
1125
+ consumed: i
1126
+ };
1127
+ } else if (field === "id") throw new LoroApplyError("SchemaViolation", "cannot modify or traverse LoroTree node 'id'", opIndex);
1128
+ else throw new LoroApplyError("SchemaViolation", `unknown field '${field}' on LoroTree node`, opIndex);
1129
+ }
1130
+ }
1131
+ var SimDoc = class {
1132
+ doc;
1133
+ shallowRoots;
1134
+ roots = /* @__PURE__ */ new Map();
1135
+ constructor(doc, schema) {
1136
+ this.doc = doc;
1137
+ this.shallowRoots = doc.getShallowValue();
1138
+ for (const [name, ctype] of schema.roots.entries()) this.roots.set(name, {
1139
+ kind: "Lazy",
1140
+ cid: rootContainerId(name, ctype),
1141
+ ctype
1142
+ });
1143
+ }
1144
+ materialize(node) {
1145
+ if (node.kind !== "Lazy") return node;
1146
+ return this.loadContainer(node.cid, node.ctype);
1147
+ }
1148
+ emptySim(ctype) {
1149
+ switch (ctype) {
1150
+ case "Map": return {
1151
+ kind: "Map",
1152
+ entries: /* @__PURE__ */ new Map()
1153
+ };
1154
+ case "List": return {
1155
+ kind: "List",
1156
+ items: [],
1157
+ isMovable: false
1158
+ };
1159
+ case "MovableList": return {
1160
+ kind: "List",
1161
+ items: [],
1162
+ isMovable: true
1163
+ };
1164
+ case "Text": return {
1165
+ kind: "Text",
1166
+ text: ""
1167
+ };
1168
+ case "Tree": return {
1169
+ kind: "Tree",
1170
+ roots: []
1171
+ };
1172
+ case "Counter": return {
1173
+ kind: "Counter",
1174
+ value: 0
1175
+ };
1176
+ }
1177
+ }
1178
+ loadContainer(cid, ctype) {
1179
+ if (!docHasExistingContainer(this.doc, cid, this.shallowRoots)) return this.emptySim(ctype);
1180
+ const c = this.doc.getContainerById(cid);
1181
+ if (!c) return this.emptySim(ctype);
1182
+ if (c instanceof LoroMap) return {
1183
+ kind: "Map",
1184
+ entries: this.loadMap(c)
1185
+ };
1186
+ if (c instanceof LoroList) return {
1187
+ kind: "List",
1188
+ items: c.toArray().map((item) => this.vocToSim(item)),
1189
+ isMovable: false
1190
+ };
1191
+ if (c instanceof LoroMovableList) return {
1192
+ kind: "List",
1193
+ items: c.toArray().map((item) => this.vocToSim(item)),
1194
+ isMovable: true
1195
+ };
1196
+ if (c instanceof LoroText) return {
1197
+ kind: "Text",
1198
+ text: c.toString()
1199
+ };
1200
+ if (c instanceof LoroTree) {
1201
+ const wrapNodes = (nodes) => nodes.map((n) => ({
1202
+ id: n.id,
1203
+ meta: {
1204
+ kind: "Map",
1205
+ entries: this.loadMap(n.data)
1206
+ },
1207
+ children: wrapNodes(n.children() ?? [])
1208
+ }));
1209
+ return {
1210
+ kind: "Tree",
1211
+ roots: wrapNodes(c.roots())
1212
+ };
1213
+ }
1214
+ if (c instanceof LoroCounter) {
1215
+ const v = c.value;
1216
+ if (!Number.isFinite(v)) throw new LoroApplyError("Value", "non-finite counter value");
1217
+ return {
1218
+ kind: "Counter",
1219
+ value: Object.is(v, -0) ? 0 : v
1220
+ };
1221
+ }
1222
+ return this.emptySim(ctype);
1223
+ }
1224
+ loadMap(map) {
1225
+ const out = /* @__PURE__ */ new Map();
1226
+ const entries = map.entries();
1227
+ for (let i = 0; i < entries.length; i++) out.set(entries[i][0], this.vocToSim(entries[i][1]));
1228
+ return out;
1229
+ }
1230
+ vocToSim(voc) {
1231
+ if (isLoroContainer(voc)) return {
1232
+ kind: "Lazy",
1233
+ cid: voc.id,
1234
+ ctype: voc.kind()
1235
+ };
1236
+ return {
1237
+ kind: "Atomic",
1238
+ value: projectLoroValue(voc)
1239
+ };
1240
+ }
1241
+ simToJson(node) {
1242
+ const mat = this.materialize(node);
1243
+ switch (mat.kind) {
1244
+ case "Map": {
1245
+ const out = {};
1246
+ const keys = Array.from(mat.entries.keys()).sort();
1247
+ for (let i = 0; i < keys.length; i++) {
1248
+ const k = keys[i];
1249
+ setOwnProp(out, k, this.simToJson(mat.entries.get(k)));
1250
+ }
1251
+ return out;
1252
+ }
1253
+ case "List": return mat.items.map((item) => this.simToJson(item));
1254
+ case "Text": return mat.text;
1255
+ case "Tree": return mat.roots.map((n) => this.simTreeToJson(n));
1256
+ case "Counter": return mat.value;
1257
+ case "Atomic": return mat.value;
1258
+ }
1259
+ }
1260
+ simTreeToJson(node) {
1261
+ const meta = this.simToJson(node.meta);
1262
+ return {
1263
+ children: node.children.map((c) => this.simTreeToJson(c)),
1264
+ id: node.id ?? "",
1265
+ meta
1266
+ };
1267
+ }
1268
+ buildSimForNewValue(val, path, schema, opIndex) {
1269
+ const normVal = validateAndNormalizeJsonValue(val, opIndex);
1270
+ const kind = schema.kindForNewValue(path, normVal);
1271
+ if (kind.kind === "Value") {
1272
+ jsonToLoroValue(normVal);
1273
+ return {
1274
+ kind: "Atomic",
1275
+ value: normVal
1276
+ };
1277
+ }
1278
+ switch (kind.containerType) {
1279
+ case "Map": {
1280
+ if (!isPlainObject(normVal)) throw new LoroApplyError("SchemaViolation", "schema expects LoroMap (Object)", opIndex);
1281
+ const entries = /* @__PURE__ */ new Map();
1282
+ const keys = Object.keys(normVal);
1283
+ for (let i = 0; i < keys.length; i++) {
1284
+ const k = keys[i];
1285
+ entries.set(k, this.buildSimForNewValue(normVal[k], [...path, k], schema, opIndex));
1286
+ }
1287
+ return {
1288
+ kind: "Map",
1289
+ entries
1290
+ };
1291
+ }
1292
+ case "List":
1293
+ case "MovableList": {
1294
+ if (!Array.isArray(normVal)) throw new LoroApplyError("SchemaViolation", "schema expects LoroList/MovableList (Array)", opIndex);
1295
+ const items = new Array(normVal.length);
1296
+ for (let i = 0; i < normVal.length; i++) items[i] = this.buildSimForNewValue(normVal[i], [...path, i], schema, opIndex);
1297
+ return {
1298
+ kind: "List",
1299
+ items,
1300
+ isMovable: kind.containerType === "MovableList"
1301
+ };
1302
+ }
1303
+ case "Text":
1304
+ if (typeof normVal !== "string") throw new LoroApplyError("SchemaViolation", "schema expects LoroText (String)", opIndex);
1305
+ return {
1306
+ kind: "Text",
1307
+ text: normVal
1308
+ };
1309
+ case "Tree": {
1310
+ if (!Array.isArray(normVal)) throw new LoroApplyError("SchemaViolation", "schema expects LoroTree (Array)", opIndex);
1311
+ const roots = new Array(normVal.length);
1312
+ for (let i = 0; i < normVal.length; i++) roots[i] = this.buildSimTreeNode(normVal[i], [...path, i], schema, opIndex);
1313
+ return {
1314
+ kind: "Tree",
1315
+ roots
1316
+ };
1317
+ }
1318
+ case "Counter": {
1319
+ const { target } = validateCounterTarget(normVal, 0, opIndex);
1320
+ return {
1321
+ kind: "Counter",
1322
+ value: target
1323
+ };
1324
+ }
1325
+ }
1326
+ }
1327
+ buildSimTreeNode(val, nodePath, schema, opIndex) {
1328
+ if (!isPlainObject(val)) throw new LoroApplyError("SchemaViolation", "LoroTree node must be an Object", opIndex);
1329
+ const keys = Object.keys(val);
1330
+ for (let i = 0; i < keys.length; i++) {
1331
+ const k = keys[i];
1332
+ if (k !== "id" && k !== "meta" && k !== "children") throw new LoroApplyError("SchemaViolation", `unknown top-level field '${k}' on LoroTree node`, opIndex);
1333
+ }
1334
+ let id;
1335
+ if (hasOwn(val, "id")) {
1336
+ if (typeof val.id !== "string") throw new LoroApplyError("SchemaViolation", "LoroTree node 'id' must be a String", opIndex);
1337
+ id = val.id;
1338
+ }
1339
+ if (!hasOwn(val, "meta")) throw new LoroApplyError("SchemaViolation", "LoroTree node requires 'meta' Object", opIndex);
1340
+ const metaVal = val.meta;
1341
+ if (!isPlainObject(metaVal)) throw new LoroApplyError("SchemaViolation", "LoroTree node 'meta' must be an Object", opIndex);
1342
+ const metaEntries = /* @__PURE__ */ new Map();
1343
+ const mk = Object.keys(metaVal);
1344
+ for (let i = 0; i < mk.length; i++) {
1345
+ const k = mk[i];
1346
+ metaEntries.set(k, this.buildSimForNewValue(metaVal[k], [
1347
+ ...nodePath,
1348
+ "meta",
1349
+ k
1350
+ ], schema, opIndex));
1351
+ }
1352
+ if (!hasOwn(val, "children")) throw new LoroApplyError("SchemaViolation", "LoroTree node requires 'children' Array", opIndex);
1353
+ const childrenVal = val.children;
1354
+ if (!Array.isArray(childrenVal)) throw new LoroApplyError("SchemaViolation", "LoroTree node 'children' must be an Array", opIndex);
1355
+ const children = new Array(childrenVal.length);
1356
+ for (let i = 0; i < childrenVal.length; i++) children[i] = this.buildSimTreeNode(childrenVal[i], [
1357
+ ...nodePath,
1358
+ "children",
1359
+ i
1360
+ ], schema, opIndex);
1361
+ return {
1362
+ id,
1363
+ meta: {
1364
+ kind: "Map",
1365
+ entries: metaEntries
1366
+ },
1367
+ children
1368
+ };
1369
+ }
1370
+ resolveRoot(rootName, opIndex) {
1371
+ const raw = this.roots.get(rootName);
1372
+ if (!raw) throw new LoroApplyError("SchemaViolation", `unknown root container '${rootName}'`, opIndex);
1373
+ const mat = this.materialize(raw);
1374
+ if (mat !== raw) this.roots.set(rootName, mat);
1375
+ return mat;
1376
+ }
1377
+ resolveNode(path, opIndex) {
1378
+ if (path.length === 0) throw new LoroApplyError("SchemaViolation", "root path [] is protected", opIndex);
1379
+ const first = path[0];
1380
+ if (typeof first !== "string") throw new ApplyError("TypeMismatch", opIndex, "expected Object key at root");
1381
+ let cur = this.resolveRoot(first, opIndex);
1382
+ let i = 1;
1383
+ while (i < path.length) if (cur.kind === "Map") {
1384
+ const seg = path[i];
1385
+ if (typeof seg !== "string") throw new ApplyError("TypeMismatch", opIndex, "expected Object key");
1386
+ const child = cur.entries.get(seg);
1387
+ if (!child) throw new ApplyError("MissingPath", opIndex, `missing object key "${seg}"`);
1388
+ const mat = this.materialize(child);
1389
+ if (mat !== child) cur.entries.set(seg, mat);
1390
+ cur = mat;
1391
+ i++;
1392
+ } else if (cur.kind === "List") {
1393
+ const seg = path[i];
1394
+ if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) throw new ApplyError("TypeMismatch", opIndex, "expected non-negative Array index");
1395
+ if (seg >= cur.items.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${seg} out of bounds for length ${cur.items.length}`);
1396
+ const child = cur.items[seg];
1397
+ const mat = this.materialize(child);
1398
+ if (mat !== child) cur.items[seg] = mat;
1399
+ cur = mat;
1400
+ i++;
1401
+ } else if (cur.kind === "Tree") {
1402
+ const { metaNode, consumed } = stepThroughTree(cur.roots, path.slice(i), opIndex);
1403
+ cur = metaNode;
1404
+ i += consumed;
1405
+ } else throw new ApplyError("TypeMismatch", opIndex, "expected Object or Array container");
1406
+ return cur;
1407
+ }
1408
+ /**
1409
+ * Returns `{ treeLen, treePath }` only when `path` targets a structural element of a
1410
+ * `SimNode::Tree` (roots, node, children, id, unknown field, or whole `meta` with empty subpath).
1411
+ * If `path` continues past `"meta"`, it steps into `node.meta` and keeps scanning for nested trees.
1412
+ */
1413
+ findStructuralTreePrefix(path, opIndex, forArrSplice = false) {
1414
+ if (path.length === 0 || typeof path[0] !== "string") return void 0;
1415
+ const rootName = path[0];
1416
+ if (!this.roots.has(rootName)) throw new LoroApplyError("SchemaViolation", `unknown root container '${rootName}'`, opIndex);
1417
+ let cur = this.resolveRoot(rootName, opIndex);
1418
+ let i = 1;
1419
+ while (true) {
1420
+ if (cur.kind === "Tree") {
1421
+ const treePath = path.slice(0, i);
1422
+ const rest = path.slice(i);
1423
+ if (rest.length === 0) {
1424
+ if (!forArrSplice && i > 1) return;
1425
+ return {
1426
+ treeLen: i,
1427
+ treePath
1428
+ };
1429
+ }
1430
+ let curList = cur.roots;
1431
+ let j = 0;
1432
+ let steppedMeta;
1433
+ while (true) {
1434
+ if (j >= rest.length) return {
1435
+ treeLen: i,
1436
+ treePath
1437
+ };
1438
+ const nodeIdx = rest[j];
1439
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) return {
1440
+ treeLen: i,
1441
+ treePath
1442
+ };
1443
+ if (nodeIdx >= curList.length) return {
1444
+ treeLen: i,
1445
+ treePath
1446
+ };
1447
+ const node = curList[nodeIdx];
1448
+ j++;
1449
+ if (j >= rest.length) return {
1450
+ treeLen: i,
1451
+ treePath
1452
+ };
1453
+ const field = rest[j];
1454
+ if (typeof field !== "string") return {
1455
+ treeLen: i,
1456
+ treePath
1457
+ };
1458
+ if (field === "children") {
1459
+ j++;
1460
+ curList = node.children;
1461
+ } else if (field === "meta") {
1462
+ j++;
1463
+ if (j === rest.length) return {
1464
+ treeLen: i,
1465
+ treePath
1466
+ };
1467
+ steppedMeta = {
1468
+ metaNode: node.meta,
1469
+ consumed: j
1470
+ };
1471
+ break;
1472
+ } else return {
1473
+ treeLen: i,
1474
+ treePath
1475
+ };
1476
+ }
1477
+ cur = steppedMeta.metaNode;
1478
+ i += steppedMeta.consumed;
1479
+ continue;
1480
+ }
1481
+ if (i >= path.length) return;
1482
+ const seg = path[i];
1483
+ if (cur.kind === "Map") {
1484
+ if (typeof seg !== "string") return void 0;
1485
+ const child = cur.entries.get(seg);
1486
+ if (!child) return void 0;
1487
+ const mat = this.materialize(child);
1488
+ if (mat !== child) cur.entries.set(seg, mat);
1489
+ cur = mat;
1490
+ i++;
1491
+ } else if (cur.kind === "List") {
1492
+ if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) return void 0;
1493
+ if (seg >= cur.items.length) return void 0;
1494
+ const child = cur.items[seg];
1495
+ const mat = this.materialize(child);
1496
+ if (mat !== child) cur.items[seg] = mat;
1497
+ cur = mat;
1498
+ i++;
1499
+ } else return;
1500
+ }
1501
+ }
1502
+ /**
1503
+ * Returns slot index `slotIdx` where `path[..slotIdx]` is the enclosing container
1504
+ * and `path[slotIdx]` holds an `Atomic` value (including through `LoroTree` node `meta` maps).
1505
+ */
1506
+ findAtomicPrefix(path) {
1507
+ if (path.length < 2 || typeof path[0] !== "string") return void 0;
1508
+ if (!this.roots.has(path[0])) return void 0;
1509
+ let cur = this.resolveRoot(path[0], 0);
1510
+ let i = 1;
1511
+ while (i + 1 < path.length) if (cur.kind === "Map") {
1512
+ const seg = path[i];
1513
+ if (typeof seg !== "string") return void 0;
1514
+ const child = cur.entries.get(seg);
1515
+ if (!child) return void 0;
1516
+ const mat = this.materialize(child);
1517
+ if (mat !== child) cur.entries.set(seg, mat);
1518
+ cur = mat;
1519
+ if (cur.kind === "Atomic") return i;
1520
+ i++;
1521
+ } else if (cur.kind === "List") {
1522
+ const seg = path[i];
1523
+ if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) return void 0;
1524
+ if (seg >= cur.items.length) return void 0;
1525
+ const child = cur.items[seg];
1526
+ const mat = this.materialize(child);
1527
+ if (mat !== child) cur.items[seg] = mat;
1528
+ cur = mat;
1529
+ if (cur.kind === "Atomic") return i;
1530
+ i++;
1531
+ } else if (cur.kind === "Tree") {
1532
+ let curList = cur.roots;
1533
+ let j = i;
1534
+ let stepped;
1535
+ while (true) {
1536
+ if (j >= path.length) return void 0;
1537
+ const nodeIdx = path[j];
1538
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) return;
1539
+ if (nodeIdx >= curList.length) return void 0;
1540
+ const node = curList[nodeIdx];
1541
+ j++;
1542
+ if (j >= path.length) return void 0;
1543
+ const field = path[j];
1544
+ if (typeof field !== "string") return void 0;
1545
+ if (field === "children") {
1546
+ j++;
1547
+ curList = node.children;
1548
+ } else if (field === "meta") {
1549
+ j++;
1550
+ stepped = node.meta;
1551
+ break;
1552
+ } else return;
1553
+ }
1554
+ cur = stepped;
1555
+ i = j;
1556
+ } else return;
1557
+ }
1558
+ };
1559
+ function resolveTreeTarget(treeRoots, rest, opIndex) {
1560
+ if (rest.length === 0) return {
1561
+ type: "Children",
1562
+ parentIndices: [],
1563
+ children: treeRoots
1564
+ };
1565
+ let curList = treeRoots;
1566
+ const indices = [];
1567
+ let i = 0;
1568
+ while (true) {
1569
+ if (i >= rest.length) return {
1570
+ type: "Children",
1571
+ parentIndices: indices,
1572
+ children: curList
1573
+ };
1574
+ const nodeIdx = rest[i];
1575
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) throw new ApplyError("TypeMismatch", opIndex, "expected Array index in tree path");
1576
+ if (nodeIdx >= curList.length) throw new ApplyError("IndexOutOfBounds", opIndex, `tree index ${nodeIdx} out of bounds for length ${curList.length}`);
1577
+ indices.push(nodeIdx);
1578
+ const node = curList[nodeIdx];
1579
+ i++;
1580
+ if (i === rest.length) return {
1581
+ type: "Node",
1582
+ nodeIndices: indices
1583
+ };
1584
+ const field = rest[i];
1585
+ if (typeof field !== "string") throw new ApplyError("TypeMismatch", opIndex, "expected Object key on tree node");
1586
+ if (field === "children") {
1587
+ i++;
1588
+ if (i === rest.length) return {
1589
+ type: "Children",
1590
+ parentIndices: indices,
1591
+ children: node.children
1592
+ };
1593
+ curList = node.children;
1594
+ } else if (field === "meta") {
1595
+ i++;
1596
+ return {
1597
+ type: "Meta",
1598
+ nodeIndices: indices,
1599
+ node,
1600
+ subPath: rest.slice(i)
1601
+ };
1602
+ } else if (field === "id") throw new LoroApplyError("SchemaViolation", "cannot modify or traverse LoroTree node 'id'", opIndex);
1603
+ else throw new LoroApplyError("SchemaViolation", `unknown field '${field}' on LoroTree node`, opIndex);
1604
+ }
1605
+ }
1606
+ function treeMetaPath(treePath, nodeIndices) {
1607
+ const out = treePath.slice();
1608
+ for (let i = 0; i < nodeIndices.length; i++) {
1609
+ if (i > 0) out.push("children");
1610
+ out.push(nodeIndices[i]);
1611
+ }
1612
+ out.push("meta");
1613
+ return out;
1614
+ }
1615
+ function takeSimTreeNode(roots, indices) {
1616
+ if (indices.length === 1) return roots.splice(indices[0], 1)[0];
1617
+ let cur = roots[indices[0]];
1618
+ for (let i = 1; i < indices.length - 1; i++) cur = cur.children[indices[i]];
1619
+ return cur.children.splice(indices[indices.length - 1], 1)[0];
1620
+ }
1621
+ function insertSimTreeNode(roots, indices, node) {
1622
+ if (indices.length === 1) {
1623
+ roots.splice(indices[0], 0, node);
1624
+ return;
1625
+ }
1626
+ let cur = roots[indices[0]];
1627
+ for (let i = 1; i < indices.length - 1; i++) cur = cur.children[indices[i]];
1628
+ cur.children.splice(indices[indices.length - 1], 0, node);
1629
+ }
1630
+ function readAtSubPath(root, subPath, opIndex) {
1631
+ let cur = root;
1632
+ for (let i = 0; i < subPath.length; i++) {
1633
+ const seg = subPath[i];
1634
+ if (typeof seg === "string") {
1635
+ if (!isPlainObject(cur)) throw new ApplyError("TypeMismatch", opIndex, "expected Object");
1636
+ if (!hasOwn(cur, seg)) throw new ApplyError("MissingPath", opIndex, `missing object key "${seg}"`);
1637
+ cur = cur[seg];
1638
+ } else {
1639
+ if (!Array.isArray(cur)) throw new ApplyError("TypeMismatch", opIndex, "expected Array");
1640
+ if (!Number.isSafeInteger(seg) || seg < 0 || seg >= cur.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${seg} out of bounds for length ${cur.length}`);
1641
+ cur = cur[seg];
1642
+ }
1643
+ }
1644
+ return cur;
1645
+ }
1646
+ function takeFromAtomicValue(atomicVal, subPath, opIndex) {
1647
+ if (subPath.length === 0) throw new ApplyError("InvalidPath", opIndex, "expected non-empty subpath inside atomic value");
1648
+ const extracted = readAtSubPath(atomicVal, subPath, opIndex);
1649
+ const last = subPath[subPath.length - 1];
1650
+ return {
1651
+ extracted,
1652
+ updated: apply(atomicVal, [typeof last === "string" ? {
1653
+ op: "unset",
1654
+ path: subPath
1655
+ } : {
1656
+ op: "arr_splice",
1657
+ path: subPath.slice(0, -1),
1658
+ at: last,
1659
+ del: 1,
1660
+ items: []
1661
+ }])
1662
+ };
1663
+ }
1664
+ function assertValidPathSegments(path, opIndex) {
1665
+ for (let i = 0; i < path.length; i++) {
1666
+ const s = path[i];
1667
+ if (typeof s === "string") {
1668
+ assertNoLoneSurrogates(s, opIndex);
1669
+ continue;
1670
+ }
1671
+ if (typeof s === "number" && Number.isSafeInteger(s) && s >= 0) continue;
1672
+ throw new ApplyError("InvalidPath", opIndex, `invalid path segment: ${String(s)}`);
1673
+ }
1674
+ }
1675
+ function planPatch(doc, patch, options) {
1676
+ const mode = options.mode ?? "strict";
1677
+ const schema = options.schema;
1678
+ const sim = new SimDoc(doc, schema);
1679
+ const planned = [];
1680
+ for (let opIndex = 0; opIndex < patch.length; opIndex++) {
1681
+ const op = patch[opIndex];
1682
+ try {
1683
+ planSingleOp(sim, op, opIndex, schema, mode, planned);
1684
+ } catch (err) {
1685
+ if (err instanceof LoroApplyError) {
1686
+ if (err.opIndex === void 0) throw new LoroApplyError(err.kind, err.message, opIndex);
1687
+ throw err;
1688
+ }
1689
+ if (err instanceof ApplyError) throw new LoroApplyError("Patch", err.message, opIndex);
1690
+ throw new LoroApplyError("Loro", String(err), opIndex);
1691
+ }
1692
+ }
1693
+ return planned;
1694
+ }
1695
+ function planSingleOp(sim, op, opIndex, schema, mode, planned) {
1696
+ switch (op.op) {
1697
+ case "set": {
1698
+ assertValidPathSegments(op.path, opIndex);
1699
+ const val = validateAndNormalizeJsonValue(op.value, opIndex);
1700
+ if (op.path.length === 0) throw new LoroApplyError("SchemaViolation", "cannot replace entire document root (path = [])", opIndex);
1701
+ if (op.path.length === 1) {
1702
+ const rootName = op.path[0];
1703
+ if (typeof rootName !== "string") throw new ApplyError("TypeMismatch", opIndex, "expected Object key at root");
1704
+ const ctype = schema.roots.get(rootName);
1705
+ if (!ctype) throw new LoroApplyError("SchemaViolation", `unknown root container '${rootName}'`, opIndex);
1706
+ if (ctype === "Counter") {
1707
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot directly set LoroCounter in strict mode", opIndex);
1708
+ const node = sim.resolveNode(op.path, opIndex);
1709
+ if (node.kind !== "Counter") throw new LoroApplyError("Loro", "expected counter node", opIndex);
1710
+ const { target, d1, d2 } = validateCounterTarget(val, node.value, opIndex);
1711
+ if (node.value !== target) {
1712
+ node.value = target;
1713
+ planned.push({
1714
+ type: "CounterSet",
1715
+ counterPath: op.path,
1716
+ d1,
1717
+ d2,
1718
+ target
1719
+ });
1720
+ }
1721
+ return;
1722
+ }
1723
+ const rootSchema = new LoroSchema({
1724
+ roots: schema.roots,
1725
+ rules: [{
1726
+ pattern: [rootName],
1727
+ kind: containerKind(ctype)
1728
+ }, ...schema.rules],
1729
+ defaultObject: schema.defaultObject,
1730
+ defaultArray: schema.defaultArray,
1731
+ defaultString: schema.defaultString
1732
+ });
1733
+ const newSim = sim.buildSimForNewValue(val, op.path, rootSchema, opIndex);
1734
+ sim.roots.set(rootName, newSim);
1735
+ planned.push({
1736
+ type: "ReplaceRoot",
1737
+ root: rootName,
1738
+ value: val
1739
+ });
1740
+ return;
1741
+ }
1742
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex);
1743
+ if (treePrefix) {
1744
+ const { treeLen, treePath } = treePrefix;
1745
+ const rest = op.path.slice(treeLen);
1746
+ const treeNode = sim.resolveNode(treePath, opIndex);
1747
+ if (treeNode.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
1748
+ const target = resolveTreeTarget(treeNode.roots, rest, opIndex);
1749
+ if (target.type === "Children") throw new LoroApplyError("SchemaViolation", "use arr_splice or move on LoroTree children, not set", opIndex);
1750
+ if (target.type === "Node") throw new LoroApplyError("SchemaViolation", "cannot overwrite LoroTree node directly with set", opIndex);
1751
+ if (target.subPath.length !== 0) throw new LoroApplyError("SchemaViolation", "unexpected non-empty meta subpath in structural tree target", opIndex);
1752
+ if (!isPlainObject(val)) throw new LoroApplyError("SchemaViolation", "LoroTree node 'meta' must be an Object", opIndex);
1753
+ const newMetaEntries = /* @__PURE__ */ new Map();
1754
+ const keys = Object.keys(val);
1755
+ for (let i = 0; i < keys.length; i++) {
1756
+ const k = keys[i];
1757
+ newMetaEntries.set(k, sim.buildSimForNewValue(val[k], [...op.path, k], schema, opIndex));
1758
+ }
1759
+ target.node.meta = {
1760
+ kind: "Map",
1761
+ entries: newMetaEntries
1762
+ };
1763
+ planned.push({
1764
+ type: "TreeMetaReplace",
1765
+ treePath,
1766
+ nodeIndices: target.nodeIndices,
1767
+ value: val
1768
+ });
1769
+ return;
1770
+ }
1771
+ const atomicEnd = sim.findAtomicPrefix(op.path);
1772
+ if (atomicEnd !== void 0) {
1773
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot partially mutate inside atomic LoroValue in strict mode", opIndex);
1774
+ const containerPath = op.path.slice(0, atomicEnd);
1775
+ const seg = op.path[atomicEnd];
1776
+ const subPath = op.path.slice(atomicEnd + 1);
1777
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
1778
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
1779
+ const trial = apply(node.value, [{
1780
+ op: "set",
1781
+ path: subPath,
1782
+ value: val
1783
+ }]);
1784
+ jsonToLoroValue(trial);
1785
+ node.value = trial;
1786
+ planned.push({
1787
+ type: "WriteAtomic",
1788
+ containerPath,
1789
+ seg,
1790
+ value: trial
1791
+ });
1792
+ return;
1793
+ }
1794
+ const parentPath = op.path.slice(0, -1);
1795
+ const last = op.path[op.path.length - 1];
1796
+ const parent = sim.resolveNode(parentPath, opIndex);
1797
+ if (parent.kind === "Map") {
1798
+ if (typeof last !== "string") throw new ApplyError("TypeMismatch", opIndex, "expected Object key");
1799
+ const existingRaw = parent.entries.get(last);
1800
+ if (existingRaw) {
1801
+ const existing = sim.materialize(existingRaw);
1802
+ if (existing !== existingRaw) parent.entries.set(last, existing);
1803
+ if (existing.kind === "Counter") {
1804
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot directly set LoroCounter in strict mode", opIndex);
1805
+ const { target, d1, d2 } = validateCounterTarget(val, existing.value, opIndex);
1806
+ if (existing.value !== target) {
1807
+ existing.value = target;
1808
+ planned.push({
1809
+ type: "CounterSet",
1810
+ counterPath: op.path,
1811
+ d1,
1812
+ d2,
1813
+ target
1814
+ });
1815
+ }
1816
+ return;
1817
+ }
1818
+ }
1819
+ parent.entries.set(last, sim.buildSimForNewValue(val, op.path, schema, opIndex));
1820
+ planned.push({
1821
+ type: "MapSet",
1822
+ mapPath: parentPath,
1823
+ key: last,
1824
+ value: val
1825
+ });
1826
+ } else if (parent.kind === "List") {
1827
+ if (typeof last !== "number" || !Number.isSafeInteger(last) || last < 0) throw new ApplyError("TypeMismatch", opIndex, "expected Array index");
1828
+ if (last >= parent.items.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${last} out of bounds for length ${parent.items.length}`);
1829
+ const existingRaw = parent.items[last];
1830
+ const existing = sim.materialize(existingRaw);
1831
+ if (existing.kind === "Counter") {
1832
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot directly set LoroCounter in strict mode", opIndex);
1833
+ const { target, d1, d2 } = validateCounterTarget(val, existing.value, opIndex);
1834
+ if (existing.value !== target) {
1835
+ existing.value = target;
1836
+ planned.push({
1837
+ type: "CounterSet",
1838
+ counterPath: op.path,
1839
+ d1,
1840
+ d2,
1841
+ target
1842
+ });
1843
+ }
1844
+ return;
1845
+ }
1846
+ parent.items[last] = sim.buildSimForNewValue(val, op.path, schema, opIndex);
1847
+ planned.push({
1848
+ type: "ListSet",
1849
+ listPath: parentPath,
1850
+ index: last,
1851
+ value: val,
1852
+ isMovable: parent.isMovable
1853
+ });
1854
+ } else throw new ApplyError("TypeMismatch", opIndex, "expected Object or Array");
1855
+ return;
1856
+ }
1857
+ case "unset": {
1858
+ assertValidPathSegments(op.path, opIndex);
1859
+ if (op.path.length === 0) throw new ApplyError("InvalidPath", opIndex, "unset requires non-empty path");
1860
+ if (op.path.length === 1) throw new LoroApplyError("SchemaViolation", "cannot unset root container", opIndex);
1861
+ const last = op.path[op.path.length - 1];
1862
+ if (typeof last !== "string") throw new ApplyError("TypeMismatch", opIndex, "unset last segment must be Object key");
1863
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex);
1864
+ if (treePrefix) {
1865
+ const { treeLen, treePath } = treePrefix;
1866
+ const rest = op.path.slice(treeLen);
1867
+ const treeNode = sim.resolveNode(treePath, opIndex);
1868
+ if (treeNode.kind === "Tree") resolveTreeTarget(treeNode.roots, rest, opIndex);
1869
+ throw new LoroApplyError("SchemaViolation", "cannot unset LoroTree node, structural field, or 'meta'", opIndex);
1870
+ }
1871
+ const atomicEnd = sim.findAtomicPrefix(op.path);
1872
+ if (atomicEnd !== void 0) {
1873
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot unset inside atomic LoroValue in strict mode", opIndex);
1874
+ const containerPath = op.path.slice(0, atomicEnd);
1875
+ const seg = op.path[atomicEnd];
1876
+ const subPath = op.path.slice(atomicEnd + 1);
1877
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
1878
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
1879
+ const trial = apply(node.value, [{
1880
+ op: "unset",
1881
+ path: subPath
1882
+ }]);
1883
+ jsonToLoroValue(trial);
1884
+ node.value = trial;
1885
+ planned.push({
1886
+ type: "WriteAtomic",
1887
+ containerPath,
1888
+ seg,
1889
+ value: trial
1890
+ });
1891
+ return;
1892
+ }
1893
+ const parentPath = op.path.slice(0, -1);
1894
+ const parent = sim.resolveNode(parentPath, opIndex);
1895
+ if (parent.kind !== "Map") throw new ApplyError("TypeMismatch", opIndex, "expected Object");
1896
+ if (parent.entries.delete(last)) planned.push({
1897
+ type: "MapUnset",
1898
+ mapPath: parentPath,
1899
+ key: last
1900
+ });
1901
+ return;
1902
+ }
1903
+ case "arr_splice": {
1904
+ assertValidPathSegments(op.path, opIndex);
1905
+ const normItems = new Array(op.items.length);
1906
+ for (let i = 0; i < op.items.length; i++) normItems[i] = validateAndNormalizeJsonValue(op.items[i], opIndex);
1907
+ if (op.path.length === 0) throw new LoroApplyError("SchemaViolation", "arr_splice cannot target document root []", opIndex);
1908
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex, true);
1909
+ if (treePrefix) {
1910
+ const { treeLen, treePath } = treePrefix;
1911
+ const rest = op.path.slice(treeLen);
1912
+ const treeNode = sim.resolveNode(treePath, opIndex);
1913
+ if (treeNode.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
1914
+ const target$1 = resolveTreeTarget(treeNode.roots, rest, opIndex);
1915
+ if (target$1.type === "Children") {
1916
+ checkSafeSpliceBounds(op.at, op.del, target$1.children.length, opIndex);
1917
+ const newNodes$1 = new Array(normItems.length);
1918
+ for (let i = 0; i < normItems.length; i++) newNodes$1[i] = sim.buildSimTreeNode(normItems[i], [...op.path, op.at + i], schema, opIndex);
1919
+ spliceInPlace(target$1.children, op.at, op.del, newNodes$1);
1920
+ if (op.del > 0 || normItems.length > 0) planned.push({
1921
+ type: "TreeSplice",
1922
+ treePath,
1923
+ parentIndices: target$1.parentIndices,
1924
+ at: op.at,
1925
+ del: op.del,
1926
+ items: normItems
1927
+ });
1928
+ return;
1929
+ }
1930
+ throw new ApplyError("TypeMismatch", opIndex, "expected Array");
1931
+ }
1932
+ const atomicEnd = sim.findAtomicPrefix(op.path);
1933
+ if (atomicEnd !== void 0) {
1934
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot arr_splice atomic LoroValue::List in strict mode", opIndex);
1935
+ const containerPath = op.path.slice(0, atomicEnd);
1936
+ const seg = op.path[atomicEnd];
1937
+ const subPath = op.path.slice(atomicEnd + 1);
1938
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
1939
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
1940
+ const trial = apply(node.value, [{
1941
+ op: "arr_splice",
1942
+ path: subPath,
1943
+ at: op.at,
1944
+ del: op.del,
1945
+ items: normItems
1946
+ }]);
1947
+ jsonToLoroValue(trial);
1948
+ node.value = trial;
1949
+ planned.push({
1950
+ type: "WriteAtomic",
1951
+ containerPath,
1952
+ seg,
1953
+ value: trial
1954
+ });
1955
+ return;
1956
+ }
1957
+ const target = sim.resolveNode(op.path, opIndex);
1958
+ if (target.kind === "Atomic" && Array.isArray(target.value)) {
1959
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot arr_splice atomic LoroValue::List in strict mode; use LoroList or LoroMovableList", opIndex);
1960
+ const trial = apply(target.value, [{
1961
+ op: "arr_splice",
1962
+ path: [],
1963
+ at: op.at,
1964
+ del: op.del,
1965
+ items: normItems
1966
+ }]);
1967
+ jsonToLoroValue(trial);
1968
+ target.value = trial;
1969
+ planned.push({
1970
+ type: "WriteAtomic",
1971
+ containerPath: op.path.slice(0, -1),
1972
+ seg: op.path[op.path.length - 1],
1973
+ value: trial
1974
+ });
1975
+ return;
1976
+ }
1977
+ if (target.kind !== "List") throw new ApplyError("TypeMismatch", opIndex, "expected Array");
1978
+ checkSafeSpliceBounds(op.at, op.del, target.items.length, opIndex);
1979
+ const newNodes = new Array(normItems.length);
1980
+ for (let i = 0; i < normItems.length; i++) newNodes[i] = sim.buildSimForNewValue(normItems[i], [...op.path, op.at + i], schema, opIndex);
1981
+ spliceInPlace(target.items, op.at, op.del, newNodes);
1982
+ if (op.del > 0 || normItems.length > 0) planned.push({
1983
+ type: "ListSplice",
1984
+ listPath: op.path,
1985
+ at: op.at,
1986
+ del: op.del,
1987
+ items: normItems,
1988
+ isMovable: target.isMovable
1989
+ });
1990
+ return;
1991
+ }
1992
+ case "move": {
1993
+ assertValidPathSegments(op.from, opIndex);
1994
+ assertValidPathSegments(op.to, opIndex);
1995
+ if (op.from.length === 0 || op.to.length === 0) throw new ApplyError("InvalidPath", opIndex, "move requires non-empty from and to paths");
1996
+ if (op.from.length === 1 || op.to.length === 1) throw new LoroApplyError("SchemaViolation", "cannot move root container", opIndex);
1997
+ const fromTree = sim.findStructuralTreePrefix(op.from, opIndex, false);
1998
+ if (pathsEqual(op.from, op.to)) {
1999
+ if (fromTree) {
2000
+ const tn = sim.resolveNode(fromTree.treePath, opIndex);
2001
+ if (tn.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
2002
+ if (resolveTreeTarget(tn.roots, op.from.slice(fromTree.treeLen), opIndex).type !== "Node") throw new LoroApplyError("SchemaViolation", "LoroTree move 'from' must address a tree node", opIndex);
2003
+ return;
2004
+ }
2005
+ const atomicEnd = sim.findAtomicPrefix(op.from);
2006
+ if (atomicEnd !== void 0) {
2007
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move inside atomic LoroValue in strict mode", opIndex);
2008
+ const subPath = op.from.slice(atomicEnd + 1);
2009
+ const node = sim.resolveNode(op.from.slice(0, atomicEnd + 1), opIndex);
2010
+ if (node.kind !== "Atomic") throw new ApplyError("TypeMismatch", opIndex, "expected Object or Array");
2011
+ apply(node.value, [{
2012
+ op: "move",
2013
+ from: subPath,
2014
+ to: subPath
2015
+ }]);
2016
+ return;
2017
+ }
2018
+ sim.resolveNode(op.from, opIndex);
2019
+ return;
2020
+ }
2021
+ if (fromTree) {
2022
+ const fRest = op.from.slice(fromTree.treeLen);
2023
+ const treeNode = sim.resolveNode(fromTree.treePath, opIndex);
2024
+ if (treeNode.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
2025
+ const fromTarget = resolveTreeTarget(treeNode.roots, fRest, opIndex);
2026
+ if (fromTarget.type !== "Node") throw new LoroApplyError("SchemaViolation", "LoroTree move 'from' must address a tree node", opIndex);
2027
+ const fromIndices = fromTarget.nodeIndices;
2028
+ const taken = takeSimTreeNode(treeNode.roots, fromIndices);
2029
+ let toTree;
2030
+ try {
2031
+ toTree = sim.findStructuralTreePrefix(op.to, opIndex, false);
2032
+ } catch (err) {
2033
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2034
+ throw err;
2035
+ }
2036
+ if (!toTree) {
2037
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2038
+ throw new LoroApplyError("SchemaViolation", "cannot move between LoroTree structure and non-tree container", opIndex);
2039
+ }
2040
+ if (!pathsEqual(fromTree.treePath, toTree.treePath)) {
2041
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2042
+ throw new LoroApplyError("SchemaViolation", "cannot move tree node across different LoroTree containers", opIndex);
2043
+ }
2044
+ const tRest = op.to.slice(toTree.treeLen);
2045
+ const toLast = tRest[tRest.length - 1];
2046
+ if (typeof toLast !== "number" || !Number.isSafeInteger(toLast) || toLast < 0) {
2047
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2048
+ throw new LoroApplyError("SchemaViolation", "LoroTree move 'to' must end with child index", opIndex);
2049
+ }
2050
+ const tParentRest = tRest.slice(0, -1);
2051
+ let toTarget;
2052
+ try {
2053
+ toTarget = resolveTreeTarget(treeNode.roots, tParentRest, opIndex);
2054
+ } catch (err) {
2055
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2056
+ throw err;
2057
+ }
2058
+ if (toTarget.type !== "Children") {
2059
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2060
+ throw new LoroApplyError("SchemaViolation", "LoroTree move 'to' parent must be tree root or node children", opIndex);
2061
+ }
2062
+ if (toLast > toTarget.children.length) {
2063
+ const len = toTarget.children.length;
2064
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2065
+ throw new ApplyError("IndexOutOfBounds", opIndex, `index ${toLast} out of bounds for length ${len}`);
2066
+ }
2067
+ toTarget.children.splice(toLast, 0, taken);
2068
+ planned.push({
2069
+ type: "TreeMove",
2070
+ treePath: fromTree.treePath,
2071
+ fromIndices,
2072
+ newParentIndices: toTarget.parentIndices,
2073
+ toIndex: toLast
2074
+ });
2075
+ return;
2076
+ }
2077
+ const fAtomic = sim.findAtomicPrefix(op.from);
2078
+ const fLast = op.from[op.from.length - 1];
2079
+ const fParent = op.from.slice(0, -1);
2080
+ const tLast = op.to[op.to.length - 1];
2081
+ const tParent = op.to.slice(0, -1);
2082
+ if (fAtomic === void 0 && pathsEqual(fParent, tParent) && typeof fLast === "number" && typeof tLast === "number") {
2083
+ const parentNode = sim.resolveNode(fParent, opIndex);
2084
+ if (parentNode.kind === "List") {
2085
+ if (!parentNode.isMovable && mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move within plain LoroList in strict mode; use MovableList", opIndex);
2086
+ const len = parentNode.items.length;
2087
+ if (fLast >= len) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${fLast} out of bounds for length ${len}`);
2088
+ const [val] = parentNode.items.splice(fLast, 1);
2089
+ if (tLast > parentNode.items.length) {
2090
+ const midLen = parentNode.items.length;
2091
+ parentNode.items.splice(fLast, 0, val);
2092
+ throw new ApplyError("IndexOutOfBounds", opIndex, `index ${tLast} out of bounds for length ${midLen}`);
2093
+ }
2094
+ if (parentNode.isMovable) {
2095
+ parentNode.items.splice(tLast, 0, val);
2096
+ planned.push({
2097
+ type: "MovableListMove",
2098
+ listPath: fParent,
2099
+ from: fLast,
2100
+ to: tLast
2101
+ });
2102
+ } else {
2103
+ const movedJson$1 = sim.simToJson(val);
2104
+ const newSim$1 = sim.buildSimForNewValue(movedJson$1, op.to, schema, opIndex);
2105
+ parentNode.items.splice(tLast, 0, newSim$1);
2106
+ planned.push({
2107
+ type: "ListPermissiveMove",
2108
+ listPath: fParent,
2109
+ from: fLast,
2110
+ to: tLast,
2111
+ movedValue: movedJson$1
2112
+ });
2113
+ }
2114
+ return;
2115
+ }
2116
+ }
2117
+ let movedJson;
2118
+ let srcAtomic;
2119
+ let srcDel;
2120
+ if (fAtomic !== void 0) {
2121
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move inside atomic LoroValue in strict mode", opIndex);
2122
+ const containerPath = op.from.slice(0, fAtomic);
2123
+ const seg = op.from[fAtomic];
2124
+ const subFrom = op.from.slice(fAtomic + 1);
2125
+ const node = sim.resolveNode(op.from.slice(0, fAtomic + 1), opIndex);
2126
+ if (node.kind !== "Atomic") throw new ApplyError("TypeMismatch", opIndex, "expected Object or Array");
2127
+ const { extracted, updated } = takeFromAtomicValue(node.value, subFrom, opIndex);
2128
+ jsonToLoroValue(updated);
2129
+ node.value = updated;
2130
+ srcAtomic = {
2131
+ containerPath,
2132
+ seg,
2133
+ value: updated
2134
+ };
2135
+ movedJson = extracted;
2136
+ } else {
2137
+ const { node: taken, isMovable } = takeSimGeneric(sim, op.from, opIndex);
2138
+ if (taken.kind !== "Atomic" && mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move CRDT subcontainer across containers in strict mode", opIndex);
2139
+ srcDel = typeof fLast === "string" ? {
2140
+ type: "MapUnset",
2141
+ mapPath: fParent,
2142
+ key: fLast
2143
+ } : {
2144
+ type: "ListSplice",
2145
+ listPath: fParent,
2146
+ at: fLast,
2147
+ del: 1,
2148
+ items: [],
2149
+ isMovable
2150
+ };
2151
+ movedJson = sim.simToJson(taken);
2152
+ }
2153
+ if (sim.findStructuralTreePrefix(op.to, opIndex, false)) throw new LoroApplyError("SchemaViolation", "cannot move between LoroTree structure and non-tree container", opIndex);
2154
+ const tAtomic = sim.findAtomicPrefix(op.to);
2155
+ if (tAtomic !== void 0) {
2156
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move inside atomic LoroValue in strict mode", opIndex);
2157
+ const containerPath = op.to.slice(0, tAtomic);
2158
+ const seg = op.to[tAtomic];
2159
+ const subTo = op.to.slice(tAtomic + 1);
2160
+ const node = sim.resolveNode(op.to.slice(0, tAtomic + 1), opIndex);
2161
+ if (node.kind !== "Atomic") throw new ApplyError("TypeMismatch", opIndex, "expected Object or Array");
2162
+ const subLast = subTo[subTo.length - 1];
2163
+ const insertOp = typeof subLast === "string" ? {
2164
+ op: "set",
2165
+ path: subTo,
2166
+ value: movedJson
2167
+ } : {
2168
+ op: "arr_splice",
2169
+ path: subTo.slice(0, -1),
2170
+ at: subLast,
2171
+ del: 0,
2172
+ items: [movedJson]
2173
+ };
2174
+ const trial = apply(node.value, [insertOp]);
2175
+ jsonToLoroValue(trial);
2176
+ node.value = trial;
2177
+ if (srcAtomic) {
2178
+ if (!pathsEqual(srcAtomic.containerPath, containerPath) || srcAtomic.seg !== seg) planned.push({
2179
+ type: "WriteAtomic",
2180
+ containerPath: srcAtomic.containerPath,
2181
+ seg: srcAtomic.seg,
2182
+ value: srcAtomic.value
2183
+ });
2184
+ } else if (srcDel) planned.push(srcDel);
2185
+ planned.push({
2186
+ type: "WriteAtomic",
2187
+ containerPath,
2188
+ seg,
2189
+ value: trial
2190
+ });
2191
+ return;
2192
+ }
2193
+ if (srcAtomic) {
2194
+ planned.push({
2195
+ type: "WriteAtomic",
2196
+ containerPath: srcAtomic.containerPath,
2197
+ seg: srcAtomic.seg,
2198
+ value: srcAtomic.value
2199
+ });
2200
+ const parent = sim.resolveNode(tParent, opIndex);
2201
+ if (parent.kind === "Map" && typeof tLast === "string") {
2202
+ const existingRaw = parent.entries.get(tLast);
2203
+ if (existingRaw) {
2204
+ const existing = sim.materialize(existingRaw);
2205
+ if (existing !== existingRaw) parent.entries.set(tLast, existing);
2206
+ if (existing.kind === "Counter") throw new LoroApplyError("SchemaViolation", "cannot overwrite LoroCounter via cross-container move", opIndex);
2207
+ }
2208
+ parent.entries.set(tLast, sim.buildSimForNewValue(movedJson, op.to, schema, opIndex));
2209
+ planned.push({
2210
+ type: "MapSet",
2211
+ mapPath: tParent,
2212
+ key: tLast,
2213
+ value: movedJson
2214
+ });
2215
+ return;
2216
+ }
2217
+ if (parent.kind === "List" && typeof tLast === "number") {
2218
+ if (tLast > parent.items.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${tLast} out of bounds for length ${parent.items.length}`);
2219
+ parent.items.splice(tLast, 0, sim.buildSimForNewValue(movedJson, op.to, schema, opIndex));
2220
+ planned.push({
2221
+ type: "ListSplice",
2222
+ listPath: tParent,
2223
+ at: tLast,
2224
+ del: 0,
2225
+ items: [movedJson],
2226
+ isMovable: parent.isMovable
2227
+ });
2228
+ return;
2229
+ }
2230
+ throw new ApplyError("TypeMismatch", opIndex, "expected compatible container");
2231
+ }
2232
+ const newSim = sim.buildSimForNewValue(movedJson, op.to, schema, opIndex);
2233
+ insertSimGeneric(sim, op.to, newSim, opIndex, mode);
2234
+ planned.push({
2235
+ type: "CrossMove",
2236
+ fromContainer: fParent,
2237
+ fromSeg: fLast,
2238
+ toContainer: tParent,
2239
+ toSeg: tLast,
2240
+ movedValue: movedJson
2241
+ });
2242
+ return;
2243
+ }
2244
+ case "str_splice": {
2245
+ assertValidPathSegments(op.path, opIndex);
2246
+ assertNoLoneSurrogates(op.ins, opIndex);
2247
+ if (op.path.length === 0) throw new LoroApplyError("SchemaViolation", "str_splice cannot target document root []", opIndex);
2248
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex);
2249
+ if (treePrefix) {
2250
+ const { treeLen, treePath } = treePrefix;
2251
+ const rest = op.path.slice(treeLen);
2252
+ const treeNode = sim.resolveNode(treePath, opIndex);
2253
+ if (treeNode.kind === "Tree") resolveTreeTarget(treeNode.roots, rest, opIndex);
2254
+ throw new LoroApplyError("SchemaViolation", "str_splice cannot target LoroTree structure, 'meta', or 'id'", opIndex);
2255
+ }
2256
+ const atomicEnd = sim.findAtomicPrefix(op.path);
2257
+ if (atomicEnd !== void 0) {
2258
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot str_splice inside atomic LoroValue in strict mode", opIndex);
2259
+ const containerPath = op.path.slice(0, atomicEnd);
2260
+ const seg = op.path[atomicEnd];
2261
+ const subPath = op.path.slice(atomicEnd + 1);
2262
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
2263
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
2264
+ const trial = apply(node.value, [{
2265
+ op: "str_splice",
2266
+ path: subPath,
2267
+ at: op.at,
2268
+ del: op.del,
2269
+ ins: op.ins
2270
+ }]);
2271
+ jsonToLoroValue(trial);
2272
+ node.value = trial;
2273
+ planned.push({
2274
+ type: "WriteAtomic",
2275
+ containerPath,
2276
+ seg,
2277
+ value: trial
2278
+ });
2279
+ return;
2280
+ }
2281
+ const target = sim.resolveNode(op.path, opIndex);
2282
+ if (target.kind === "Text") {
2283
+ const end = assertValidUtf16Range(target.text, op.at, op.del, opIndex);
2284
+ target.text = target.text.slice(0, op.at) + op.ins + target.text.slice(end);
2285
+ if (op.del > 0 || op.ins.length > 0) planned.push({
2286
+ type: "TextSplice",
2287
+ textPath: op.path,
2288
+ at: op.at,
2289
+ del: op.del,
2290
+ ins: op.ins
2291
+ });
2292
+ return;
2293
+ }
2294
+ if (target.kind === "Atomic" && typeof target.value === "string") {
2295
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot str_splice atomic LoroValue::String in strict mode; use LoroText container", opIndex);
2296
+ const end = assertValidUtf16Range(target.value, op.at, op.del, opIndex);
2297
+ target.value = target.value.slice(0, op.at) + op.ins + target.value.slice(end);
2298
+ planned.push({
2299
+ type: "WriteAtomic",
2300
+ containerPath: op.path.slice(0, -1),
2301
+ seg: op.path[op.path.length - 1],
2302
+ value: target.value
2303
+ });
2304
+ return;
2305
+ }
2306
+ throw new ApplyError("TypeMismatch", opIndex, "expected String");
2307
+ }
2308
+ }
2309
+ }
2310
+ function takeSimGeneric(sim, path, opIndex) {
2311
+ const last = path[path.length - 1];
2312
+ const parent = sim.resolveNode(path.slice(0, -1), opIndex);
2313
+ if (parent.kind === "Map" && typeof last === "string") {
2314
+ const child = parent.entries.get(last);
2315
+ if (!child) throw new ApplyError("MissingPath", opIndex, `missing object key "${last}"`);
2316
+ parent.entries.delete(last);
2317
+ return {
2318
+ node: sim.materialize(child),
2319
+ isMovable: false
2320
+ };
2321
+ }
2322
+ if (parent.kind === "List" && typeof last === "number") {
2323
+ if (last >= parent.items.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${last} out of bounds`);
2324
+ const [child] = parent.items.splice(last, 1);
2325
+ return {
2326
+ node: sim.materialize(child),
2327
+ isMovable: parent.isMovable
2328
+ };
2329
+ }
2330
+ throw new ApplyError("TypeMismatch", opIndex, "expected compatible container");
2331
+ }
2332
+ function insertSimGeneric(sim, path, node, opIndex, mode) {
2333
+ const last = path[path.length - 1];
2334
+ const parent = sim.resolveNode(path.slice(0, -1), opIndex);
2335
+ if (parent.kind === "Map" && typeof last === "string") {
2336
+ if (mode === "strict") {
2337
+ const existingRaw = parent.entries.get(last);
2338
+ if (existingRaw) {
2339
+ const existing = sim.materialize(existingRaw);
2340
+ if (existing !== existingRaw) parent.entries.set(last, existing);
2341
+ if (existing.kind === "Counter") throw new LoroApplyError("SchemaViolation", "cannot overwrite LoroCounter in strict mode", opIndex);
2342
+ }
2343
+ }
2344
+ parent.entries.set(last, node);
2345
+ return;
2346
+ }
2347
+ if (parent.kind === "List" && typeof last === "number") {
2348
+ if (last > parent.items.length) throw new ApplyError("IndexOutOfBounds", opIndex, `index ${last} out of bounds`);
2349
+ parent.items.splice(last, 0, node);
2350
+ return;
2351
+ }
2352
+ throw new ApplyError("TypeMismatch", opIndex, "expected compatible container");
2353
+ }
2354
+ function getRootContainer(doc, name, ctype) {
2355
+ switch (ctype) {
2356
+ case "Map": return doc.getMap(name);
2357
+ case "List": return doc.getList(name);
2358
+ case "MovableList": return doc.getMovableList(name);
2359
+ case "Text": return doc.getText(name);
2360
+ case "Tree": return doc.getTree(name);
2361
+ case "Counter": return doc.getCounter(name);
2362
+ }
2363
+ }
2364
+ function newDetachedContainer(ctype) {
2365
+ switch (ctype) {
2366
+ case "Map": return new LoroMap();
2367
+ case "List": return new LoroList();
2368
+ case "MovableList": return new LoroMovableList();
2369
+ case "Text": return new LoroText();
2370
+ case "Tree": return new LoroTree();
2371
+ case "Counter": return new LoroCounter();
2372
+ }
2373
+ }
2374
+ function resolveDocContainer(doc, schema, path) {
2375
+ const rootName = path[0];
2376
+ let cur = getRootContainer(doc, rootName, schema.roots.get(rootName));
2377
+ let i = 1;
2378
+ while (i < path.length) if (cur instanceof LoroMap) {
2379
+ const k = path[i];
2380
+ cur = cur.get(k);
2381
+ i++;
2382
+ } else if (cur instanceof LoroList || cur instanceof LoroMovableList) {
2383
+ const idx = path[i];
2384
+ cur = cur.get(idx);
2385
+ i++;
2386
+ } else if (cur instanceof LoroTree) {
2387
+ let curNode;
2388
+ while (i < path.length) {
2389
+ const seg = path[i];
2390
+ if (typeof seg === "number") {
2391
+ curNode = curNode === void 0 ? cur.roots()[seg] : (curNode.children() ?? [])[seg];
2392
+ i++;
2393
+ } else if (seg === "children") i++;
2394
+ else if (seg === "meta") {
2395
+ i++;
2396
+ cur = curNode.data;
2397
+ break;
2398
+ }
2399
+ }
2400
+ } else throw new LoroApplyError("Loro", "unexpected non-branch container during execute");
2401
+ return cur;
2402
+ }
2403
+ function treeNodeAtIndices(tree, indices) {
2404
+ let node = tree.roots()[indices[0]];
2405
+ for (let i = 1; i < indices.length; i++) node = (node.children() ?? [])[indices[i]];
2406
+ return node;
2407
+ }
2408
+ function treeParentIdAtMidIndices(tree, takenId, indices) {
2409
+ if (indices.length === 0) return void 0;
2410
+ let cur = tree.roots().filter((n) => n.id !== takenId)[indices[0]];
2411
+ for (let i = 1; i < indices.length; i++) cur = (cur.children() ?? []).filter((n) => n.id !== takenId)[indices[i]];
2412
+ return cur.id;
2413
+ }
2414
+ function populateContainerFromJson(container, fullPath, value, schema, createdTreeIds) {
2415
+ if (container instanceof LoroMap) {
2416
+ const obj = value;
2417
+ const existingKeys = container.keys();
2418
+ for (let i = 0; i < existingKeys.length; i++) {
2419
+ const k = existingKeys[i];
2420
+ if (!hasOwn(obj, k)) container.delete(k);
2421
+ }
2422
+ const keys = Object.keys(obj).sort();
2423
+ for (let i = 0; i < keys.length; i++) {
2424
+ const k = keys[i];
2425
+ setMapEntry(container, k, [...fullPath, k], obj[k], schema, createdTreeIds);
2426
+ }
2427
+ return;
2428
+ }
2429
+ if (container instanceof LoroList) {
2430
+ const arr = value;
2431
+ if (container.length > 0) container.delete(0, container.length);
2432
+ for (let i = 0; i < arr.length; i++) insertListEntry(container, i, [...fullPath, i], arr[i], schema, createdTreeIds);
2433
+ return;
2434
+ }
2435
+ if (container instanceof LoroMovableList) {
2436
+ const arr = value;
2437
+ if (container.length > 0) container.delete(0, container.length);
2438
+ for (let i = 0; i < arr.length; i++) insertMovableListEntry(container, i, [...fullPath, i], arr[i], schema, createdTreeIds);
2439
+ return;
2440
+ }
2441
+ if (container instanceof LoroText) {
2442
+ const s = value;
2443
+ container.splice(0, container.length, s);
2444
+ return;
2445
+ }
2446
+ if (container instanceof LoroTree) {
2447
+ if (!container.isFractionalIndexEnabled()) container.enableFractionalIndex(0);
2448
+ const roots = container.roots();
2449
+ for (let i = 0; i < roots.length; i++) container.delete(roots[i].id);
2450
+ const arr = value;
2451
+ for (let i = 0; i < arr.length; i++) createTreeNodeFromJson(container, void 0, i, [...fullPath, i], arr[i], schema, createdTreeIds);
2452
+ return;
2453
+ }
2454
+ if (container instanceof LoroCounter) {
2455
+ const cur = container.value;
2456
+ const { target, d1, d2 } = validateCounterTarget(value, cur, 0);
2457
+ if (cur !== target) {
2458
+ if (d1 !== 0) container.increment(d1);
2459
+ if (d2 !== 0) container.increment(d2);
2460
+ const rem = normZeroF64(target - container.value);
2461
+ if (rem !== 0 && Number.isFinite(rem)) container.increment(rem);
2462
+ }
2463
+ }
2464
+ }
2465
+ function setMapEntry(map, key, fullPath, value, schema, createdTreeIds) {
2466
+ const kind = schema.kindForNewValue(fullPath, value);
2467
+ if (kind.kind === "Value") map.set(key, jsonToLoroValue(value));
2468
+ else populateContainerFromJson(map.setContainer(key, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2469
+ }
2470
+ function insertListEntry(list, index, fullPath, value, schema, createdTreeIds) {
2471
+ const kind = schema.kindForNewValue(fullPath, value);
2472
+ if (kind.kind === "Value") list.insert(index, jsonToLoroValue(value));
2473
+ else populateContainerFromJson(list.insertContainer(index, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2474
+ }
2475
+ function insertMovableListEntry(ml, index, fullPath, value, schema, createdTreeIds) {
2476
+ const kind = schema.kindForNewValue(fullPath, value);
2477
+ if (kind.kind === "Value") ml.insert(index, jsonToLoroValue(value));
2478
+ else populateContainerFromJson(ml.insertContainer(index, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2479
+ }
2480
+ function setMovableListEntry(ml, index, fullPath, value, schema, createdTreeIds) {
2481
+ const kind = schema.kindForNewValue(fullPath, value);
2482
+ if (kind.kind === "Value") ml.set(index, jsonToLoroValue(value));
2483
+ else populateContainerFromJson(ml.setContainer(index, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2484
+ }
2485
+ function createTreeNodeFromJson(tree, parentId, index, nodePath, value, schema, createdTreeIds) {
2486
+ if (!tree.isFractionalIndexEnabled()) tree.enableFractionalIndex(0);
2487
+ const obj = value;
2488
+ const specifiedId = hasOwn(obj, "id") && typeof obj.id === "string" ? obj.id : void 0;
2489
+ const newNode = tree.createNode(parentId, index);
2490
+ createdTreeIds.push({
2491
+ specifiedId,
2492
+ assignedId: newNode.id
2493
+ });
2494
+ if (hasOwn(obj, "meta") && obj.meta !== void 0) populateContainerFromJson(newNode.data, [...nodePath, "meta"], obj.meta, schema, createdTreeIds);
2495
+ if (hasOwn(obj, "children") && Array.isArray(obj.children)) for (let i = 0; i < obj.children.length; i++) createTreeNodeFromJson(tree, newNode.id, i, [
2496
+ ...nodePath,
2497
+ "children",
2498
+ i
2499
+ ], obj.children[i], schema, createdTreeIds);
2500
+ }
2501
+ function executePlan(doc, plan, schema) {
2502
+ if (plan.length === 0) return {
2503
+ changed: false,
2504
+ createdTreeIds: []
2505
+ };
2506
+ doc.commit();
2507
+ const vvBefore = doc.oplogVersion();
2508
+ const createdTreeIds = [];
2509
+ for (let sIdx = 0; sIdx < plan.length; sIdx++) {
2510
+ const step = plan[sIdx];
2511
+ switch (step.type) {
2512
+ case "ReplaceRoot": {
2513
+ const path = [step.root];
2514
+ populateContainerFromJson(resolveDocContainer(doc, schema, path), path, step.value, schema, createdTreeIds);
2515
+ break;
2516
+ }
2517
+ case "MapSet":
2518
+ setMapEntry(resolveDocContainer(doc, schema, step.mapPath), step.key, [...step.mapPath, step.key], step.value, schema, createdTreeIds);
2519
+ break;
2520
+ case "MapUnset":
2521
+ resolveDocContainer(doc, schema, step.mapPath).delete(step.key);
2522
+ break;
2523
+ case "ListSet": {
2524
+ const fp = [...step.listPath, step.index];
2525
+ if (step.isMovable) setMovableListEntry(resolveDocContainer(doc, schema, step.listPath), step.index, fp, step.value, schema, createdTreeIds);
2526
+ else {
2527
+ const l = resolveDocContainer(doc, schema, step.listPath);
2528
+ l.delete(step.index, 1);
2529
+ insertListEntry(l, step.index, fp, step.value, schema, createdTreeIds);
2530
+ }
2531
+ break;
2532
+ }
2533
+ case "ListSplice":
2534
+ if (step.isMovable) {
2535
+ const ml = resolveDocContainer(doc, schema, step.listPath);
2536
+ if (step.del > 0) ml.delete(step.at, step.del);
2537
+ for (let i = 0; i < step.items.length; i++) insertMovableListEntry(ml, step.at + i, [...step.listPath, step.at + i], step.items[i], schema, createdTreeIds);
2538
+ } else {
2539
+ const l = resolveDocContainer(doc, schema, step.listPath);
2540
+ if (step.del > 0) l.delete(step.at, step.del);
2541
+ for (let i = 0; i < step.items.length; i++) insertListEntry(l, step.at + i, [...step.listPath, step.at + i], step.items[i], schema, createdTreeIds);
2542
+ }
2543
+ break;
2544
+ case "MovableListMove":
2545
+ resolveDocContainer(doc, schema, step.listPath).move(step.from, step.to);
2546
+ break;
2547
+ case "ListPermissiveMove": {
2548
+ const l = resolveDocContainer(doc, schema, step.listPath);
2549
+ l.delete(step.from, 1);
2550
+ insertListEntry(l, step.to, [...step.listPath, step.to], step.movedValue, schema, createdTreeIds);
2551
+ break;
2552
+ }
2553
+ case "TextSplice":
2554
+ resolveDocContainer(doc, schema, step.textPath).splice(step.at, step.del, step.ins);
2555
+ break;
2556
+ case "TreeSplice": {
2557
+ const tree = resolveDocContainer(doc, schema, step.treePath);
2558
+ if (!tree.isFractionalIndexEnabled()) tree.enableFractionalIndex(0);
2559
+ const parentNode = step.parentIndices.length === 0 ? void 0 : treeNodeAtIndices(tree, step.parentIndices);
2560
+ if (step.del > 0) {
2561
+ const children = parentNode ? parentNode.children() ?? [] : tree.roots();
2562
+ for (let i = 0; i < step.del; i++) tree.delete(children[step.at + i].id);
2563
+ }
2564
+ const basePath = treeMetaPath(step.treePath, step.parentIndices);
2565
+ basePath.pop();
2566
+ if (step.parentIndices.length > 0) basePath.push("children");
2567
+ for (let i = 0; i < step.items.length; i++) createTreeNodeFromJson(tree, parentNode?.id, step.at + i, [...basePath, step.at + i], step.items[i], schema, createdTreeIds);
2568
+ break;
2569
+ }
2570
+ case "TreeMove": {
2571
+ const tree = resolveDocContainer(doc, schema, step.treePath);
2572
+ if (!tree.isFractionalIndexEnabled()) tree.enableFractionalIndex(0);
2573
+ const targetNode = treeNodeAtIndices(tree, step.fromIndices);
2574
+ const newParentId = treeParentIdAtMidIndices(tree, targetNode.id, step.newParentIndices);
2575
+ tree.move(targetNode.id, newParentId, step.toIndex);
2576
+ break;
2577
+ }
2578
+ case "TreeMetaReplace": {
2579
+ const targetNode = treeNodeAtIndices(resolveDocContainer(doc, schema, step.treePath), step.nodeIndices);
2580
+ const mp = treeMetaPath(step.treePath, step.nodeIndices);
2581
+ populateContainerFromJson(targetNode.data, mp, step.value, schema, createdTreeIds);
2582
+ break;
2583
+ }
2584
+ case "CounterSet": {
2585
+ const c = resolveDocContainer(doc, schema, step.counterPath);
2586
+ if (step.d1 !== 0) c.increment(step.d1);
2587
+ if (step.d2 !== 0) c.increment(step.d2);
2588
+ const rem = normZeroF64(step.target - c.value);
2589
+ if (rem !== 0 && Number.isFinite(rem)) c.increment(rem);
2590
+ break;
2591
+ }
2592
+ case "WriteAtomic": {
2593
+ const c = resolveDocContainer(doc, schema, step.containerPath);
2594
+ const lv = jsonToLoroValue(step.value);
2595
+ if (c instanceof LoroMap && typeof step.seg === "string") c.set(step.seg, lv);
2596
+ else if (c instanceof LoroList && typeof step.seg === "number") {
2597
+ c.delete(step.seg, 1);
2598
+ c.insert(step.seg, lv);
2599
+ } else if (c instanceof LoroMovableList && typeof step.seg === "number") c.set(step.seg, lv);
2600
+ break;
2601
+ }
2602
+ case "CrossMove": {
2603
+ const src = resolveDocContainer(doc, schema, step.fromContainer);
2604
+ if (src instanceof LoroMap && typeof step.fromSeg === "string") src.delete(step.fromSeg);
2605
+ else if ((src instanceof LoroList || src instanceof LoroMovableList) && typeof step.fromSeg === "number") src.delete(step.fromSeg, 1);
2606
+ const dst = resolveDocContainer(doc, schema, step.toContainer);
2607
+ const fp = [...step.toContainer, step.toSeg];
2608
+ if (dst instanceof LoroMap && typeof step.toSeg === "string") setMapEntry(dst, step.toSeg, fp, step.movedValue, schema, createdTreeIds);
2609
+ else if (dst instanceof LoroList && typeof step.toSeg === "number") insertListEntry(dst, step.toSeg, fp, step.movedValue, schema, createdTreeIds);
2610
+ else if (dst instanceof LoroMovableList && typeof step.toSeg === "number") insertMovableListEntry(dst, step.toSeg, fp, step.movedValue, schema, createdTreeIds);
2611
+ break;
2612
+ }
2613
+ }
2614
+ }
2615
+ doc.commit();
2616
+ return {
2617
+ changed: doc.oplogVersion().compare(vvBefore) !== 0,
2618
+ createdTreeIds
2619
+ };
2620
+ }
2621
+ function wrapLoroOp(fn) {
2622
+ try {
2623
+ return fn();
2624
+ } catch (err) {
2625
+ if (err instanceof LoroApplyError) throw err;
2626
+ throw new LoroApplyError("Loro", err instanceof Error ? err.message : String(err));
2627
+ }
2628
+ }
2629
+ const U64_MAX_PEER = 18446744073709551615n;
2630
+ /**
2631
+ * Validates `patch` against `doc` and `options.schema`, then applies all CRDT mutations atomically.
2632
+ * @throws {@link LoroApplyError} on schema violations, invalid patches, or detached `LoroDoc`.
2633
+ */
2634
+ function applyJsonPatchToLoro(doc, patch, options) {
2635
+ if (doc.isDetached()) throw new LoroApplyError("SchemaViolation", "cannot apply patch to a detached LoroDoc", 0);
2636
+ if (patch.length === 0) return {
2637
+ changed: false,
2638
+ createdTreeIds: []
2639
+ };
2640
+ const plan = planPatch(doc, patch, options);
2641
+ return wrapLoroOp(() => executePlan(doc, plan, options.schema));
2642
+ }
2643
+ /**
2644
+ * Rebases/applies `patch` starting from `baseFrontiers` on `doc`, committing CRDT ops under optional `peerId`.
2645
+ * @throws {@link LoroApplyError} on conflicts, schema violations, or peer ID conflict.
2646
+ */
2647
+ function applyJsonPatchAt(doc, baseFrontiers, patch, options, peerId) {
2648
+ if (doc.isDetached()) throw new LoroApplyError("SchemaViolation", "cannot apply patch to a detached LoroDoc", 0);
2649
+ doc.commit();
2650
+ if (frontiersEqual(doc.oplogFrontiers(), baseFrontiers)) {
2651
+ const plan = planPatch(doc, patch, options);
2652
+ if (plan.length === 0) return {
2653
+ changed: false,
2654
+ createdTreeIds: []
2655
+ };
2656
+ const prevPeer = doc.peerIdStr;
2657
+ if (peerId !== void 0) wrapLoroOp(() => doc.setPeerId(peerId));
2658
+ try {
2659
+ return wrapLoroOp(() => executePlan(doc, plan, options.schema));
2660
+ } finally {
2661
+ if (peerId !== void 0) try {
2662
+ doc.setPeerId(prevPeer);
2663
+ } catch {}
2664
+ }
2665
+ }
2666
+ return wrapLoroOp(() => {
2667
+ const forked = doc.forkAt(baseFrontiers.slice());
2668
+ const docVv = doc.oplogVersion();
2669
+ const forkVv = forked.oplogVersion();
2670
+ const docVvMap = docVv.toJSON();
2671
+ const forkVvMap = forkVv.toJSON();
2672
+ let chosenPeer;
2673
+ if (peerId !== void 0) {
2674
+ if ((docVv.get(peerId) ?? 0) > (forkVv.get(peerId) ?? 0)) throw new LoroApplyError("PeerIdConflict", `peerId ${String(peerId)} already has newer operations in target doc`);
2675
+ chosenPeer = peerId;
2676
+ } else {
2677
+ let maxPeer = 0n;
2678
+ for (const p of docVvMap.keys()) {
2679
+ const b = BigInt(p);
2680
+ if (b > maxPeer && b !== U64_MAX_PEER) maxPeer = b;
2681
+ }
2682
+ for (const p of forkVvMap.keys()) {
2683
+ const b = BigInt(p);
2684
+ if (b > maxPeer && b !== U64_MAX_PEER) maxPeer = b;
2685
+ }
2686
+ let candidate = maxPeer + 1n & U64_MAX_PEER;
2687
+ while (candidate === U64_MAX_PEER || candidate === 0n || docVvMap.has(String(candidate)) || forkVvMap.has(String(candidate))) candidate = candidate + 1n & U64_MAX_PEER;
2688
+ chosenPeer = String(candidate);
2689
+ }
2690
+ forked.setPeerId(chosenPeer);
2691
+ const vvBefore = forked.oplogVersion();
2692
+ const applied = applyJsonPatchToLoro(forked, patch, options);
2693
+ if (forked.oplogVersion().compare(vvBefore) === 0) return {
2694
+ changed: false,
2695
+ createdTreeIds: applied.createdTreeIds
2696
+ };
2697
+ const updates = forked.export({
2698
+ mode: "update",
2699
+ from: vvBefore
2700
+ });
2701
+ doc.import(updates);
2702
+ return {
2703
+ changed: doc.oplogVersion().compare(docVv) !== 0,
2704
+ createdTreeIds: applied.createdTreeIds
2705
+ };
2706
+ });
2707
+ }
2708
+
2709
+ //#endregion
2710
+ export { LoroApplyError, LoroSchema, LoroValueKind, applyJsonPatchAt, applyJsonPatchToLoro, containerKind, diffLoroJson, jsonToLoroValue, loroToJson, projectContainer, projectContainerById, projectLoroValue };