plitejs 0.0.1 → 54.0.0-beta.3

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.
Files changed (61) hide show
  1. package/LICENSE +4 -1
  2. package/README.md +83 -0
  3. package/dist/annotation-store-metrics-Ccjkef45.js +12 -0
  4. package/dist/annotations/index.d.ts +2 -0
  5. package/dist/annotations/index.js +2 -0
  6. package/dist/authored/index.d.ts +596 -0
  7. package/dist/authored/index.js +18558 -0
  8. package/dist/authored-veto-DSnQcHGR.js +6 -0
  9. package/dist/browser-protocol-pvt4HFF7.js +5 -0
  10. package/dist/comparison-plan-CEQL0ooW.js +1338 -0
  11. package/dist/comparison-types-Dt-unJZY.d.ts +179 -0
  12. package/dist/create-editor-CkHtPWXV.js +1107 -0
  13. package/dist/diff/index.d.ts +32 -0
  14. package/dist/diff/index.js +1748 -0
  15. package/dist/dom/index.d.ts +2 -0
  16. package/dist/dom/index.js +2 -0
  17. package/dist/dom-Cgfscvnm.js +9220 -0
  18. package/dist/editor-owner-IUmkTeXz.js +171 -0
  19. package/dist/editor-view-lifetime-GJKa_QGh.js +23 -0
  20. package/dist/history/index.d.ts +170 -0
  21. package/dist/history/index.js +6718 -0
  22. package/dist/hyperscript/index.d.ts +2 -0
  23. package/dist/hyperscript/index.js +2 -0
  24. package/dist/hyperscript-FPuoArEi.js +299 -0
  25. package/dist/index-BpQx2UG4.d.ts +1093 -0
  26. package/dist/index-Cw-oC2ps.d.ts +190 -0
  27. package/dist/index-DPWyk3lG.d.ts +65 -0
  28. package/dist/index-DpltOCot.d.ts +9753 -0
  29. package/dist/index-HPYawTae.d.ts +119 -0
  30. package/dist/index-K0Za9YXc.d.ts +1246 -0
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +5 -0
  33. package/dist/internal/index.d.ts +2 -0
  34. package/dist/internal/index.js +156 -0
  35. package/dist/mapped-view-store-ld-6uxEU.js +120 -0
  36. package/dist/native-grouping-input-DMNcsIaW.js +8 -0
  37. package/dist/pagination/index.d.ts +169 -0
  38. package/dist/pagination/index.js +2 -0
  39. package/dist/pagination/react.d.ts +33 -0
  40. package/dist/pagination/react.js +1509 -0
  41. package/dist/pagination-D_A8iPJP.js +1021 -0
  42. package/dist/plugin-DWzkJbnJ.js +50999 -0
  43. package/dist/range-geometry-BLAHRE11.d.ts +38 -0
  44. package/dist/range-geometry-BjeLHOnl.js +486 -0
  45. package/dist/react/index.d.ts +5 -0
  46. package/dist/react/index.js +7 -0
  47. package/dist/react/virtualized.d.ts +13 -0
  48. package/dist/react/virtualized.js +209 -0
  49. package/dist/react-DZ15gmz2.js +1018 -0
  50. package/dist/retraction-BMem8Rfk.js +109 -0
  51. package/dist/src-cT1OTKP_.js +1386 -0
  52. package/dist/store-Cz2mXyDe.js +704 -0
  53. package/dist/testing/index.d.ts +183 -0
  54. package/dist/testing/index.js +96 -0
  55. package/dist/use-editor-dom-scope-BbMDSCpW.js +28354 -0
  56. package/dist/yjs/index.d.ts +2 -0
  57. package/dist/yjs/index.js +2 -0
  58. package/dist/yjs/react/index.d.ts +26 -0
  59. package/dist/yjs/react/index.js +85 -0
  60. package/dist/yjs-DOK-m7kl.js +13413 -0
  61. package/package.json +191 -43
@@ -0,0 +1,1338 @@
1
+ import { $f as cloneFrozen, Fd as DocumentIndex, Ff as snapshotEditorJsonValue, Sd as RootChange, Vd as canonicalJsonKey, Xd as isTextNode, Yd as isElementNode, Yu as DocumentChange, Zd as nodeProps, nc as lawCheckEnabled, np as jsonEqual, tp as isRecord } from "./plugin-DWzkJbnJ.js";
2
+ //#region src/core/json-fingerprint.ts
3
+ /** Deterministic fingerprint for already validated JSON-compatible data. */
4
+ const fingerprintEditorJson = (value) => {
5
+ const canonical = canonicalJsonKey(value);
6
+ let first = 2166136261;
7
+ let second = 2654435769;
8
+ for (let index = 0; index < canonical.length; index += 1) {
9
+ const unit = canonical.charCodeAt(index);
10
+ first = Math.imul(first ^ unit, 16777619) >>> 0;
11
+ second = Math.imul(second ^ unit + index, 2246822507) >>> 0;
12
+ }
13
+ return `${first.toString(36)}${second.toString(36)}`;
14
+ };
15
+ //#endregion
16
+ //#region src/diff/lib/comparison-internal.ts
17
+ const COMPARISON_POLICY = Object.freeze({
18
+ id: "structural-diff",
19
+ version: 1
20
+ });
21
+ const COMPARISON_WORD = /[\p{L}\p{M}\p{N}]+(?:['’][\p{L}\p{M}\p{N}]+)*/gu;
22
+ const stableStringify = (value) => {
23
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "undefined";
24
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
25
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
26
+ };
27
+ const comparisonHash = (value) => fingerprintEditorJson(value);
28
+ const detachComparisonEnvelope = (input) => {
29
+ if (Array.isArray(input) || typeof input !== "object" || input === null) return null;
30
+ const { meta } = input;
31
+ if (meta === void 0) return null;
32
+ return fingerprintEditorJson(snapshotEditorJsonValue(meta, "Comparison document metadata"));
33
+ };
34
+ const detachComparisonDocument = (input, schema) => {
35
+ const candidate = Array.isArray(input) ? { children: input } : input;
36
+ schema.assertDocument(candidate);
37
+ return snapshotEditorJsonValue({
38
+ children: candidate.children,
39
+ ...candidate.roots ? { roots: candidate.roots } : {}
40
+ }, "Comparison document");
41
+ };
42
+ const createComparisonSnapshot = (document, schema, projection, envelopeFingerprint) => {
43
+ const identity = schema.identity();
44
+ const fingerprint = fingerprintEditorJson({
45
+ document,
46
+ envelopeFingerprint,
47
+ projection,
48
+ schema: identity
49
+ });
50
+ return Object.freeze({
51
+ document,
52
+ envelopeFingerprint,
53
+ fingerprint,
54
+ projection,
55
+ schema: identity
56
+ });
57
+ };
58
+ const comparisonDocumentsEqual = (left, right) => jsonEqual(left, right);
59
+ const disjointSets = (count) => {
60
+ const parent = Array.from({ length: count }, (_value, index) => index);
61
+ const find = (index) => {
62
+ let root = index;
63
+ while (parent[root] !== root) {
64
+ parent[root] = parent[parent[root]];
65
+ root = parent[root];
66
+ }
67
+ return root;
68
+ };
69
+ return {
70
+ find,
71
+ join: (left, right) => {
72
+ const from = find(left);
73
+ const to = find(right);
74
+ if (from === to) return false;
75
+ parent[from] = to;
76
+ return true;
77
+ }
78
+ };
79
+ };
80
+ const spanKey$1 = ({ from, root, to }) => `${root === null ? "primary" : `named:${root}`}:${from}:${to}`;
81
+ const uniqueSpans = (spans) => Object.freeze([...new Map(spans.map((value) => [spanKey$1(value), value])).values()]);
82
+ const mergeGroups = (changes, merges) => {
83
+ const placed = /* @__PURE__ */ new Map();
84
+ const absorbed = /* @__PURE__ */ new Set();
85
+ for (const merge of merges) {
86
+ placed.set(Math.min(...merge.members), merge);
87
+ for (const member of merge.members) absorbed.add(member);
88
+ }
89
+ return changes.flatMap((change, index) => {
90
+ const merge = placed.get(index);
91
+ if (!merge) return absorbed.has(index) ? [] : [change];
92
+ const merged = merge.members.map((member) => changes[member]);
93
+ const { evidence, id } = changes[merge.owner];
94
+ return [Object.freeze({
95
+ after: uniqueSpans(merged.flatMap(({ after: spans }) => spans)),
96
+ before: uniqueSpans(merged.flatMap(({ before: spans }) => spans)),
97
+ correspondence: Object.freeze(merged.flatMap(({ correspondence }) => correspondence)),
98
+ effects: Object.freeze(merged.flatMap(({ effects }) => effects)),
99
+ evidence,
100
+ id,
101
+ requiredChangeIds: Object.freeze([...new Set(merged.flatMap(({ requiredChangeIds }) => requiredChangeIds))])
102
+ })];
103
+ });
104
+ };
105
+ const createAbortError = () => {
106
+ const error = /* @__PURE__ */ new Error("The comparison was aborted.");
107
+ error.name = "AbortError";
108
+ return error;
109
+ };
110
+ const assertComparisonActive = (signal) => {
111
+ if (signal?.aborted) throw createAbortError();
112
+ };
113
+ const yieldComparisonWork = async (signal) => {
114
+ assertComparisonActive(signal);
115
+ await new Promise((resolve) => {
116
+ setTimeout(resolve, 0);
117
+ });
118
+ assertComparisonActive(signal);
119
+ };
120
+ //#endregion
121
+ //#region src/diff/lib/comparison-align.ts
122
+ const SIDES = ["before", "after"];
123
+ const unitsOf = (index, childIndexes) => {
124
+ const units = [];
125
+ let stretch = [];
126
+ const flush = () => {
127
+ const first = stretch[0];
128
+ const last = stretch.at(-1);
129
+ if (first && last) units.push({
130
+ element: null,
131
+ from: first.from,
132
+ nodes: stretch,
133
+ to: last.to
134
+ });
135
+ stretch = [];
136
+ };
137
+ for (const childIndex of childIndexes) {
138
+ const node = index.nodes[childIndex];
139
+ if (node.kind === "text") {
140
+ stretch.push(node);
141
+ continue;
142
+ }
143
+ flush();
144
+ units.push({
145
+ element: node,
146
+ from: node.from,
147
+ nodes: [node],
148
+ to: node.to
149
+ });
150
+ }
151
+ flush();
152
+ return units;
153
+ };
154
+ const unitAt = (units, position, field) => {
155
+ let low = 0;
156
+ let high = units.length - 1;
157
+ while (low <= high) {
158
+ const middle = low + high >> 1;
159
+ const value = units[middle][field];
160
+ if (value === position) return middle;
161
+ if (value < position) low = middle + 1;
162
+ else high = middle - 1;
163
+ }
164
+ return -1;
165
+ };
166
+ const unitContaining = (units, from, to) => {
167
+ let low = 0;
168
+ let high = units.length - 1;
169
+ while (low <= high) {
170
+ const middle = low + high >> 1;
171
+ const unit = units[middle];
172
+ if (unit.to <= from) low = middle + 1;
173
+ else if (unit.from > from) high = middle - 1;
174
+ else return unit.from <= from && to <= unit.to ? middle : -1;
175
+ }
176
+ return -1;
177
+ };
178
+ const classify = (units, footprints) => {
179
+ const wholes = [];
180
+ const inside = /* @__PURE__ */ new Map();
181
+ for (const footprint of footprints) {
182
+ if (footprint.from === footprint.to) {
183
+ const at = unitContaining(units, footprint.from, footprint.to);
184
+ const unit = units[at];
185
+ if (unit && unit.from < footprint.from && footprint.from < unit.to) inside.set(at, [...inside.get(at) ?? [], footprint]);
186
+ continue;
187
+ }
188
+ const start = unitAt(units, footprint.from, "from");
189
+ const end = unitAt(units, footprint.to, "to");
190
+ if (start !== -1 && end !== -1 && start <= end) {
191
+ wholes.push({
192
+ effects: /* @__PURE__ */ new Set([footprint.effect.id]),
193
+ end,
194
+ footprints: [footprint],
195
+ start
196
+ });
197
+ continue;
198
+ }
199
+ const at = unitContaining(units, footprint.from, footprint.to);
200
+ if (at === -1) return null;
201
+ inside.set(at, [...inside.get(at) ?? [], footprint]);
202
+ }
203
+ const ranges = [];
204
+ for (const whole of wholes.toSorted((left, right) => left.start - right.start)) {
205
+ const last = ranges.at(-1);
206
+ if (last && whole.start <= last.end) {
207
+ last.end = Math.max(last.end, whole.end);
208
+ for (const effect of whole.effects) last.effects.add(effect);
209
+ last.footprints.push(...whole.footprints);
210
+ } else ranges.push(whole);
211
+ }
212
+ for (const range of ranges) for (let unit = range.start; unit <= range.end; unit += 1) {
213
+ range.footprints.push(...inside.get(unit) ?? []);
214
+ inside.delete(unit);
215
+ }
216
+ return {
217
+ inside,
218
+ ranges
219
+ };
220
+ };
221
+ const spanKey = (root, from, to) => `${root === null ? "" : `${root}#`}${from}:${to}`;
222
+ const describedPairsOf = (groups) => {
223
+ const pairs = /* @__PURE__ */ new Map();
224
+ for (const { correspondence } of groups) for (const { after, before, kind } of correspondence) {
225
+ const [from] = before;
226
+ const [to] = after;
227
+ if (kind === "primary" && before.length === 1 && after.length === 1 && from.root === to.root) pairs.set(spanKey(from.root, from.from, from.to), to);
228
+ }
229
+ return pairs;
230
+ };
231
+ const describedPair = (described, root, before, after) => {
232
+ const pair = described.get(spanKey(root, before.from, before.to));
233
+ return before.element !== null && after.element !== null && pair?.from === after.from && pair.to === after.to;
234
+ };
235
+ const places = (range, unit) => range.footprints.some(({ effect, from, to }) => effect.kind === "placement" && from === unit.from && to === unit.to);
236
+ const longestIncreasingByAfter = (candidates) => {
237
+ const tails = [];
238
+ const previous = candidates.map(() => -1);
239
+ candidates.forEach((candidate, index) => {
240
+ let low = 0;
241
+ let high = tails.length;
242
+ while (low < high) {
243
+ const middle = low + high >> 1;
244
+ if (candidates[tails[middle]].after < candidate.after) low = middle + 1;
245
+ else high = middle;
246
+ }
247
+ if (low > 0) previous[index] = tails[low - 1];
248
+ tails[low] = index;
249
+ });
250
+ const kept = [];
251
+ for (let at = tails.at(-1) ?? -1; at !== -1; at = previous[at]) kept.push(candidates[at]);
252
+ return kept.reverse();
253
+ };
254
+ const anchorsOf = ({ classified, described, root, units }) => {
255
+ const loose = (side) => {
256
+ const covered = new Uint8Array(units[side].length);
257
+ for (const range of classified[side].ranges) covered.fill(1, range.start, range.end + 1);
258
+ return units[side].flatMap((_unit, index) => covered[index] ? [] : index);
259
+ };
260
+ const looseBefore = loose("before");
261
+ const looseAfter = loose("after");
262
+ if (looseBefore.length !== looseAfter.length) return null;
263
+ const candidates = looseBefore.map((before, index) => ({
264
+ after: looseAfter[index],
265
+ before,
266
+ ranges: null
267
+ }));
268
+ const holders = /* @__PURE__ */ new Map();
269
+ for (const side of SIDES) for (const range of classified[side].ranges) for (const id of range.effects) holders.set(id, (holders.get(id) ?? 0) + 1);
270
+ const single = new Map(classified.after.ranges.filter(({ end, start }) => start === end).map((range) => [range.start, range]));
271
+ for (const range of classified.before.ranges) {
272
+ if (range.start !== range.end) continue;
273
+ const before = units.before[range.start];
274
+ const pair = described.get(spanKey(root, before.from, before.to));
275
+ const at = pair ? unitAt(units.after, pair.from, "from") : -1;
276
+ const partner = single.get(at);
277
+ if (!partner || !describedPair(described, root, before, units.after[at]) || ![...range.effects].some((id) => partner.effects.has(id)) || places(range, before) || places(partner, units.after[at])) continue;
278
+ if ([...range.effects, ...partner.effects].every((id) => holders.get(id) === Number(range.effects.has(id)) + Number(partner.effects.has(id)))) candidates.push({
279
+ after: at,
280
+ before: range.start,
281
+ ranges: {
282
+ after: partner,
283
+ before: range
284
+ }
285
+ });
286
+ }
287
+ const kept = longestIncreasingByAfter(candidates.toSorted((left, right) => left.before - right.before));
288
+ return kept.filter(({ ranges }) => ranges === null).length === looseBefore.length ? kept : null;
289
+ };
290
+ const isPaired = (component) => component.after !== null && component.before !== null;
291
+ const startOf = (span) => span ? span.start : Number.POSITIVE_INFINITY;
292
+ const gapComponents = (all) => {
293
+ const sets = disjointSets(all.length);
294
+ const holding = /* @__PURE__ */ new Map();
295
+ all.forEach(({ range }, at) => {
296
+ for (const id of range.effects) {
297
+ const members = holding.get(id);
298
+ if (members) members.push(at);
299
+ else holding.set(id, [at]);
300
+ }
301
+ });
302
+ for (const members of holding.values()) {
303
+ const first = members.find((at) => all[at].side === "after");
304
+ if (first !== void 0 && all[members[0]].side === "before") sets.join(members[0], first);
305
+ for (let at = 1; at < members.length; at += 1) {
306
+ const [previous, run] = [all[members[at - 1]], all[members[at]]];
307
+ if (previous.side === run.side && previous.range.end + 1 === run.range.start) sets.join(members[at - 1], members[at]);
308
+ }
309
+ }
310
+ const components = () => {
311
+ const byRoot = /* @__PURE__ */ new Map();
312
+ all.forEach(({ index, side }, at) => {
313
+ const key = sets.find(at);
314
+ const component = byRoot.get(key) ?? {
315
+ after: null,
316
+ before: null,
317
+ members: []
318
+ };
319
+ const span = component[side];
320
+ component.members.push(at);
321
+ component[side] = {
322
+ end: Math.max(span?.end ?? index, index),
323
+ start: Math.min(span?.start ?? index, index)
324
+ };
325
+ byRoot.set(key, component);
326
+ });
327
+ return [...byRoot.values()];
328
+ };
329
+ const join = (left, right) => sets.join(left.members[0], right.members[0]);
330
+ for (let merged = true; merged;) {
331
+ merged = false;
332
+ for (const side of SIDES) {
333
+ const spanning = components().filter((component) => component[side] !== null).toSorted((left, right) => startOf(left[side]) - startOf(right[side]));
334
+ for (let at = 1; at < spanning.length; at += 1) {
335
+ const [previous, component] = [spanning[at - 1], spanning[at]];
336
+ if (startOf(component[side]) <= (previous[side]?.end ?? -1)) merged = join(previous, component) || merged;
337
+ }
338
+ }
339
+ const paired = components().filter(isPaired).toSorted((left, right) => left.before.start - right.before.start);
340
+ for (let at = 1; at < paired.length; at += 1) if (paired[at].after.start < paired[at - 1].after.start) merged = join(paired[at - 1], paired[at]) || merged;
341
+ }
342
+ return components();
343
+ };
344
+ const orderGap = (runs, units, root) => {
345
+ const all = SIDES.flatMap((side) => runs[side].map((range, index) => ({
346
+ index,
347
+ range,
348
+ side
349
+ })));
350
+ const final = gapComponents(all);
351
+ const step = (component) => {
352
+ const footprints = {
353
+ after: [],
354
+ before: []
355
+ };
356
+ const unitSpan = (side) => {
357
+ const span = component[side];
358
+ return span ? {
359
+ end: runs[side][span.end].end,
360
+ start: runs[side][span.start].start
361
+ } : null;
362
+ };
363
+ for (const member of component.members) footprints[all[member].side].push(...all[member].range.footprints);
364
+ return {
365
+ after: unitSpan("after"),
366
+ before: unitSpan("before"),
367
+ footprints,
368
+ kind: "run"
369
+ };
370
+ };
371
+ const firstWrite = /* @__PURE__ */ new Map();
372
+ for (const { range } of all) for (const { effect, owner } of range.footprints) for (const span of effect.after) if (span.root === root && span.from < (firstWrite.get(owner) ?? Number.POSITIVE_INFINITY)) firstWrite.set(owner, span.from);
373
+ const firstWriteOf = (component) => {
374
+ let first = Number.POSITIVE_INFINITY;
375
+ for (const member of component.members) for (const { owner } of all[member].range.footprints) first = Math.min(first, firstWrite.get(owner) ?? Number.POSITIVE_INFINITY);
376
+ return Number.isFinite(first) ? first : -1;
377
+ };
378
+ const removed = final.filter(({ after }) => after === null).toSorted((left, right) => startOf(left.before) - startOf(right.before));
379
+ const added = final.filter(({ before }) => before === null).toSorted((left, right) => startOf(left.after) - startOf(right.after));
380
+ const addedFrom = (component) => units.after[runs.after[startOf(component.after)].start].from;
381
+ const steps = [];
382
+ let removedAt = 0;
383
+ let addedAt = 0;
384
+ const flush = (beforeLimit, afterLimit) => {
385
+ let removal = removed[removedAt];
386
+ let addition = added[addedAt];
387
+ while (removal && startOf(removal.before) < beforeLimit || addition && startOf(addition.after) < afterLimit) {
388
+ if (removal && startOf(removal.before) < beforeLimit && !(addition && startOf(addition.after) < afterLimit && firstWriteOf(removal) >= addedFrom(addition))) {
389
+ steps.push(step(removal));
390
+ removedAt += 1;
391
+ } else if (addition) {
392
+ steps.push(step(addition));
393
+ addedAt += 1;
394
+ } else return;
395
+ removal = removed[removedAt];
396
+ addition = added[addedAt];
397
+ }
398
+ };
399
+ for (const component of final.filter(isPaired).toSorted((left, right) => left.before.start - right.before.start)) {
400
+ flush(component.before.start, component.after.start);
401
+ steps.push(step(component));
402
+ }
403
+ flush(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
404
+ return steps;
405
+ };
406
+ const alignLevel = (input) => {
407
+ const anchors = anchorsOf(input);
408
+ if (!anchors) return null;
409
+ const { classified, root, units } = input;
410
+ const steps = [];
411
+ const next = {
412
+ after: 0,
413
+ before: 0
414
+ };
415
+ for (let at = 0; at <= anchors.length; at += 1) {
416
+ const anchor = anchors.at(at);
417
+ const runs = {
418
+ after: [],
419
+ before: []
420
+ };
421
+ for (const side of SIDES) {
422
+ const limit = anchor ? anchor[side] : units[side].length;
423
+ const { ranges } = classified[side];
424
+ while ((ranges[next[side]]?.start ?? limit) < limit) {
425
+ if (ranges[next[side]].end >= limit) return null;
426
+ runs[side].push(ranges[next[side]]);
427
+ next[side] += 1;
428
+ }
429
+ if (anchor?.ranges) {
430
+ if (ranges[next[side]] !== anchor.ranges[side]) return null;
431
+ next[side] += 1;
432
+ }
433
+ }
434
+ steps.push(...orderGap(runs, units, root));
435
+ if (anchor) steps.push({
436
+ anchor,
437
+ kind: "anchor"
438
+ });
439
+ }
440
+ return steps;
441
+ };
442
+ //#endregion
443
+ //#region src/diff/lib/comparison-index.ts
444
+ const rootChildren$1 = (document, root) => root === null ? document.children : document.roots?.[root] ?? [];
445
+ const span = (root, from, to) => Object.freeze({
446
+ from,
447
+ root,
448
+ to
449
+ });
450
+ const elementType = (node) => isElementNode(node) && typeof node.type === "string" ? node.type : null;
451
+ const createComparisonIndex = (document, schema) => {
452
+ const nodes = [];
453
+ const rootIndexes = [];
454
+ const rootStructures = /* @__PURE__ */ new Map();
455
+ const rootNames = [null, ...Object.keys(document.roots ?? {}).sort()];
456
+ let textUnits = 0;
457
+ for (const root of rootNames) {
458
+ let position = 0;
459
+ const rootNodeIndexes = [];
460
+ const topLevelIndexes = [];
461
+ const visit = (node, path, parentIndex) => {
462
+ const index = nodes.length;
463
+ const from = position;
464
+ position += 1;
465
+ nodes.push(void 0);
466
+ const contentFrom = position;
467
+ const childIndexes = [];
468
+ let text;
469
+ let textSegments;
470
+ if (isTextNode(node)) {
471
+ const { text: nodeText } = node;
472
+ text = nodeText;
473
+ textUnits += nodeText.length;
474
+ position += nodeText.length;
475
+ textSegments = [Object.freeze({
476
+ from: contentFrom,
477
+ offsetFrom: 0,
478
+ offsetTo: nodeText.length,
479
+ properties: nodeProps(node),
480
+ text: nodeText,
481
+ to: contentFrom + nodeText.length
482
+ })];
483
+ } else {
484
+ for (const [childIndex, child] of node.children.entries()) childIndexes.push(visit(child, [...path, childIndex], index));
485
+ let offset = 0;
486
+ textSegments = childIndexes.flatMap((childIndex) => nodes[childIndex].textSegments.map((segment) => {
487
+ const length = segment.offsetTo - segment.offsetFrom;
488
+ const result = Object.freeze({
489
+ ...segment,
490
+ offsetFrom: offset,
491
+ offsetTo: offset + length
492
+ });
493
+ offset += length;
494
+ return result;
495
+ }));
496
+ text = childIndexes.map((childIndex) => nodes[childIndex].text).join("");
497
+ }
498
+ const contentTo = position;
499
+ position += 1;
500
+ const to = position;
501
+ const canonical = stableStringify(node);
502
+ const properties = nodeProps(node);
503
+ const type = elementType(node);
504
+ const element = type === null ? null : schema.element(type);
505
+ const record = Object.freeze({
506
+ blockContainer: childIndexes.some((childIndex) => nodes[childIndex].kind === "element" && !nodes[childIndex].inline),
507
+ canonical,
508
+ childIndexes: Object.freeze(childIndexes),
509
+ contentFrom,
510
+ contentHash: comparisonHash(stableStringify({
511
+ kind: isElementNode(node) ? "element" : "text",
512
+ properties,
513
+ text,
514
+ type
515
+ })),
516
+ contentTo,
517
+ exactHash: comparisonHash(canonical),
518
+ from,
519
+ index,
520
+ inline: element?.behavior.inline ?? false,
521
+ kind: isElementNode(node) ? "element" : "text",
522
+ node,
523
+ parentIndex,
524
+ path: Object.freeze([...path]),
525
+ properties,
526
+ root,
527
+ span: span(root, from, to),
528
+ structure: element?.structure ?? null,
529
+ text,
530
+ textSegments: Object.freeze(textSegments),
531
+ to,
532
+ type
533
+ });
534
+ nodes[index] = record;
535
+ rootNodeIndexes.push(index);
536
+ const { childRoots } = node;
537
+ if (element && isRecord(childRoots)) for (const [slot, contentRoot] of Object.entries(element.contentRoots)) {
538
+ const childRoot = childRoots[slot];
539
+ if (contentRoot.structure && typeof childRoot === "string") rootStructures.set(childRoot, contentRoot.structure);
540
+ }
541
+ return index;
542
+ };
543
+ rootChildren$1(document, root).forEach((node, index) => {
544
+ topLevelIndexes.push(visit(node, [index], null));
545
+ });
546
+ rootIndexes.push({
547
+ length: position,
548
+ name: root,
549
+ nodeIndexes: Object.freeze(rootNodeIndexes),
550
+ topLevelIndexes: Object.freeze(topLevelIndexes)
551
+ });
552
+ }
553
+ return Object.freeze({
554
+ nodes: Object.freeze(nodes),
555
+ roots: new Map(rootIndexes.map((rootIndex) => [rootIndex.name, Object.freeze({
556
+ ...rootIndex,
557
+ structure: rootIndex.name === null ? null : rootStructures.get(rootIndex.name) ?? null
558
+ })])),
559
+ textUnits
560
+ });
561
+ };
562
+ const comparisonTextSpans = (node, from, to) => {
563
+ if (from === to) return Object.freeze([]);
564
+ return Object.freeze(node.textSegments.flatMap((segment) => {
565
+ const overlapFrom = Math.max(from, segment.offsetFrom);
566
+ const overlapTo = Math.min(to, segment.offsetTo);
567
+ return overlapFrom < overlapTo ? [span(node.root, segment.from + overlapFrom - segment.offsetFrom, segment.from + overlapTo - segment.offsetFrom)] : [];
568
+ }));
569
+ };
570
+ const comparisonTextPoint = (node, offset) => {
571
+ const bounded = Math.max(0, Math.min(offset, node.text.length));
572
+ const segment = node.textSegments.find((candidate) => candidate.offsetFrom <= bounded && bounded <= candidate.offsetTo) ?? node.textSegments.at(-1);
573
+ const position = segment ? segment.from + Math.max(0, Math.min(bounded - segment.offsetFrom, segment.text.length)) : node.contentFrom;
574
+ return span(node.root, position, position);
575
+ };
576
+ const comparisonTextRuns = (node) => {
577
+ const runs = [];
578
+ for (const segment of node.textSegments) {
579
+ const previous = runs.at(-1);
580
+ if (previous && stableStringify(previous.properties) === stableStringify(segment.properties)) {
581
+ runs[runs.length - 1] = Object.freeze({
582
+ from: previous.from,
583
+ properties: previous.properties,
584
+ text: previous.text + segment.text,
585
+ to: segment.to
586
+ });
587
+ continue;
588
+ }
589
+ runs.push(Object.freeze({
590
+ from: segment.from,
591
+ properties: segment.properties,
592
+ text: segment.text,
593
+ to: segment.to
594
+ }));
595
+ }
596
+ return Object.freeze(runs);
597
+ };
598
+ //#endregion
599
+ //#region src/diff/lib/comparison-moves.ts
600
+ const LETTER = /\p{L}/u;
601
+ const NO_WINDOW = -1;
602
+ const MIN_RUN_LENGTH = 3;
603
+ const changesCovered = ({ kind }, side) => {
604
+ switch (kind) {
605
+ case "delete":
606
+ case "root-delete": return side === "before";
607
+ case "insert":
608
+ case "root-create": return side === "after";
609
+ case "text": return true;
610
+ default: return false;
611
+ }
612
+ };
613
+ const clearCopiedText = (changed, groups) => {
614
+ for (const { correspondence } of groups) for (const { after, kind } of correspondence) {
615
+ if (kind !== "copy") continue;
616
+ for (const { from, root, to } of after) changed.get(root)?.fill(0, from, to);
617
+ }
618
+ };
619
+ const changedText = (groups, index, side) => {
620
+ const changed = /* @__PURE__ */ new Map();
621
+ for (const [root, { length }] of index.roots) changed.set(root, new Uint8Array(length));
622
+ for (const { effects } of groups) for (const effect of effects) {
623
+ if (!changesCovered(effect, side)) continue;
624
+ for (const { from, root, to } of effect[side]) changed.get(root)?.fill(1, from, to);
625
+ }
626
+ if (side === "after") clearCopiedText(changed, groups);
627
+ return changed;
628
+ };
629
+ const sideWords = (windows, groups, index, side) => {
630
+ const within = /* @__PURE__ */ new Map();
631
+ for (const [root, { length }] of index.roots) within.set(root, new Int32Array(length).fill(NO_WINDOW));
632
+ windows.forEach((window, at) => {
633
+ within.get(window.root)?.fill(at, window[side].from, window[side].to);
634
+ });
635
+ const changed = changedText(groups, index, side);
636
+ const blocks = /* @__PURE__ */ new Map();
637
+ for (const node of index.nodes) {
638
+ if (node.kind !== "text") continue;
639
+ const holds = within.get(node.root);
640
+ const changes = changed.get(node.root);
641
+ if (!holds || !changes) continue;
642
+ let block = node.parentIndex;
643
+ while (block !== null && index.nodes[block].inline) block = index.nodes[block].parentIndex;
644
+ const key = block ?? -1 - node.index;
645
+ const entry = blocks.get(key) ?? {
646
+ held: [],
647
+ text: "",
648
+ writers: []
649
+ };
650
+ for (const segment of node.textSegments) {
651
+ entry.text += segment.text;
652
+ for (let at = segment.from; at < segment.to; at++) {
653
+ entry.held.push(holds[at]);
654
+ entry.writers.push(changes[at] ? holds[at] : NO_WINDOW);
655
+ }
656
+ }
657
+ blocks.set(key, entry);
658
+ }
659
+ const runWriters = /* @__PURE__ */ new Map();
660
+ const wholeWords = /* @__PURE__ */ new Set();
661
+ const counts = /* @__PURE__ */ new Map();
662
+ const holders = /* @__PURE__ */ new Map();
663
+ const addRun = (run, writer) => {
664
+ if (!LETTER.test(run)) return;
665
+ const set = runWriters.get(run) ?? /* @__PURE__ */ new Set();
666
+ set.add(writer);
667
+ runWriters.set(run, set);
668
+ };
669
+ for (const { held, text, writers } of blocks.values()) for (const match of text.matchAll(COMPARISON_WORD)) {
670
+ const word = match[0];
671
+ if (!LETTER.test(word)) continue;
672
+ counts.set(word, (counts.get(word) ?? 0) + 1);
673
+ const end = match.index + word.length;
674
+ const own = writers.slice(match.index, end);
675
+ for (let at = 0, next = 1; at < own.length; at = next, next += 1) {
676
+ while (next < own.length && own[next] === own[at]) next += 1;
677
+ if (own[at] === NO_WINDOW) continue;
678
+ addRun(word.slice(at, next), own[at]);
679
+ if (at === 0 && next === own.length) wholeWords.add(word);
680
+ }
681
+ holders.set(word, new Set(held.slice(match.index, end).filter((at) => at !== NO_WINDOW)));
682
+ }
683
+ const uniqueHolders = /* @__PURE__ */ new Map();
684
+ for (const [word, count] of counts) {
685
+ const held = holders.get(word);
686
+ if (count === 1 && held) uniqueHolders.set(word, held);
687
+ }
688
+ return {
689
+ runWriters,
690
+ uniqueHolders,
691
+ wholeWords
692
+ };
693
+ };
694
+ const mutuallyRequired = (groups, indexOf) => {
695
+ const together = disjointSets(groups.length);
696
+ groups.forEach(({ id, requiredChangeIds }, index) => {
697
+ for (const required of requiredChangeIds) {
698
+ const other = indexOf.get(required);
699
+ if (other !== void 0 && groups[other].requiredChangeIds.includes(id)) together.join(index, other);
700
+ }
701
+ });
702
+ return together;
703
+ };
704
+ const movedWordTies = (windows, groups, before, after) => {
705
+ const indexOf = new Map(groups.map(({ id }, index) => [id, index]));
706
+ const together = mutuallyRequired(groups, indexOf);
707
+ const { find, join } = disjointSets(windows.length);
708
+ const firstTogether = /* @__PURE__ */ new Map();
709
+ windows.forEach(({ owners }, at) => {
710
+ for (const owner of owners) {
711
+ const group = indexOf.get(owner);
712
+ if (group === void 0) continue;
713
+ const root = together.find(group);
714
+ const first = firstTogether.get(root);
715
+ if (first === void 0) firstTogether.set(root, at);
716
+ else join(first, at);
717
+ }
718
+ });
719
+ const ties = [];
720
+ const tie = (members) => {
721
+ if (new Set(members.map(find)).size < 2) return;
722
+ ties.push([...members]);
723
+ for (const member of members) join(members[0], member);
724
+ };
725
+ const removed = sideWords(windows, groups, before, "before");
726
+ const added = sideWords(windows, groups, after, "after");
727
+ const oneGroup = (writers) => new Set([...writers].map(find)).size === 1;
728
+ const runsGluedOntoKeptWords = (glued, other) => {
729
+ const runs = [];
730
+ for (const [word, writers] of glued.runWriters) {
731
+ if (!glued.wholeWords.has(word) || !oneGroup(writers)) continue;
732
+ const [writer] = writers;
733
+ for (let at = 1; at < word.length; at += 1) for (const [part, rest] of [[word.slice(0, at), word.slice(at)], [word.slice(at), word.slice(0, at)]]) if (part.length >= MIN_RUN_LENGTH && other.wholeWords.has(part) && other.wholeWords.has(rest) && [...other.runWriters.get(rest) ?? []].some((keeper) => find(keeper) === find(writer))) runs.push([part, writer]);
734
+ }
735
+ return runs;
736
+ };
737
+ const addRuns = (side, runs) => {
738
+ for (const [run, writer] of runs) {
739
+ const writers = side.runWriters.get(run) ?? /* @__PURE__ */ new Set();
740
+ writers.add(writer);
741
+ side.runWriters.set(run, writers);
742
+ }
743
+ };
744
+ const wordsKeptInLongerWords = (side, other) => {
745
+ const longer = /* @__PURE__ */ new Map();
746
+ for (const [word, writers] of other.runWriters) {
747
+ if (!other.wholeWords.has(word)) continue;
748
+ for (const writer of writers) longer.set(find(writer), [...longer.get(find(writer)) ?? [], word]);
749
+ }
750
+ const kept = [];
751
+ for (const [word, writers] of side.runWriters) {
752
+ if (!side.wholeWords.has(word)) continue;
753
+ for (const writer of writers) if (longer.get(find(writer))?.some((grown) => grown.length > word.length && (grown.startsWith(word) || grown.endsWith(word)))) kept.push([word, writer]);
754
+ }
755
+ return kept;
756
+ };
757
+ const dropRuns = (side, runs) => {
758
+ for (const [run, writer] of runs) {
759
+ const writers = side.runWriters.get(run);
760
+ writers?.delete(writer);
761
+ if (writers?.size === 0) side.runWriters.delete(run);
762
+ }
763
+ };
764
+ const addedGlue = runsGluedOntoKeptWords(added, removed);
765
+ const removedGlue = runsGluedOntoKeptWords(removed, added);
766
+ const addedKept = wordsKeptInLongerWords(added, removed);
767
+ const removedKept = wordsKeptInLongerWords(removed, added);
768
+ addRuns(added, addedGlue);
769
+ addRuns(removed, removedGlue);
770
+ dropRuns(added, addedKept);
771
+ dropRuns(removed, removedKept);
772
+ for (const [word, holders] of removed.uniqueHolders) {
773
+ const adders = added.uniqueHolders.get(word);
774
+ if (adders) tie([...holders, ...adders]);
775
+ }
776
+ for (const [run, removers] of removed.runWriters) {
777
+ const adders = added.runWriters.get(run);
778
+ if (adders && run.length >= MIN_RUN_LENGTH && (removed.wholeWords.has(run) || added.wholeWords.has(run)) && oneGroup(removers) && oneGroup(adders)) tie([...removers, ...adders]);
779
+ }
780
+ return ties.map((members) => {
781
+ const lowest = /* @__PURE__ */ new Map();
782
+ for (const owner of members.flatMap((at) => windows[at].owners)) {
783
+ const group = indexOf.get(owner);
784
+ if (group === void 0) continue;
785
+ const root = together.find(group);
786
+ lowest.set(root, Math.min(lowest.get(root) ?? group, group));
787
+ }
788
+ return [...lowest.values()].map((group) => groups[group].id);
789
+ }).filter((owners) => owners.length > 1);
790
+ };
791
+ //#endregion
792
+ //#region src/diff/lib/comparison-plan.ts
793
+ const RECURSIVE_KINDS = /* @__PURE__ */ new Set([
794
+ "node-type",
795
+ "property",
796
+ "structure",
797
+ "text"
798
+ ]);
799
+ const NO_MARKS = stableStringify({});
800
+ const PLANS = /* @__PURE__ */ new WeakMap();
801
+ const changesOwnProps = (effect) => effect.kind === "node-type" || effect.kind === "property" && !jsonEqual(effect.beforeProperties[0], effect.afterProperties[0]);
802
+ const changesRuns = (effect) => effect.kind === "property" && !jsonEqual(effect.beforeProperties.slice(1), effect.afterProperties.slice(1));
803
+ const readingOf = (nodes) => {
804
+ let text = "";
805
+ const marks = [];
806
+ for (const node of nodes) for (const segment of node.textSegments) {
807
+ const key = stableStringify(segment.properties);
808
+ const start = marks.length;
809
+ text += segment.text;
810
+ marks.length += segment.text.length;
811
+ marks.fill(key, start);
812
+ }
813
+ return {
814
+ marks,
815
+ text
816
+ };
817
+ };
818
+ /** True when a kept character around the change changes marks, or a changed character carries one. */
819
+ const changesMarks = (before, after) => {
820
+ const shorter = Math.min(before.text.length, after.text.length);
821
+ let prefix = 0;
822
+ while (prefix < shorter && before.text[prefix] === after.text[prefix]) prefix += 1;
823
+ let suffix = 0;
824
+ while (suffix < shorter - prefix && before.text[before.text.length - 1 - suffix] === after.text[after.text.length - 1 - suffix]) suffix += 1;
825
+ for (let index = 0; index < prefix; index += 1) if (before.marks[index] !== after.marks[index]) return true;
826
+ for (let index = 1; index <= suffix; index += 1) if (before.marks.at(-index) !== after.marks.at(-index)) return true;
827
+ return [before.marks.slice(prefix, before.marks.length - suffix), after.marks.slice(prefix, after.marks.length - suffix)].some((marks) => marks.some((mark) => mark !== NO_MARKS));
828
+ };
829
+ const ownersOf = (state, ids) => [...new Set(ids)].toSorted((left, right) => (state.groupOrder.get(left) ?? Number.MAX_SAFE_INTEGER) - (state.groupOrder.get(right) ?? Number.MAX_SAFE_INTEGER) || left.localeCompare(right));
830
+ const nodesOf = (units) => units.flatMap(({ nodes }) => nodes);
831
+ const sectionsBetween = (before, after) => RootChange.betweenWhole(DocumentIndex.fromValue(before), DocumentIndex.fromValue(after)).toJSON();
832
+ const isTextBlock = (node) => node.children?.some((child) => child.text !== void 0) ?? false;
833
+ const replaceAll = (length, after) => {
834
+ const replacement = sectionsBetween([], after)[0]?.replacement ?? [];
835
+ return length === 0 && replacement.length === 0 ? [] : [{
836
+ length,
837
+ replacement
838
+ }];
839
+ };
840
+ const recordableSections = (before, after) => {
841
+ const sections = sectionsBetween(before, after);
842
+ const blocks = replaceAll(sections.reduce((sum, { length }) => sum + length, 0), after);
843
+ const [first, ...rest] = before;
844
+ const [next] = after;
845
+ if (!first?.children || !next?.children || !sections[0]?.replacement?.length || sections[0].length === 0) return {
846
+ blocks,
847
+ sections
848
+ };
849
+ if (![...before, ...after].every(isTextBlock)) return {
850
+ blocks,
851
+ sections: blocks
852
+ };
853
+ const reprops = {
854
+ ...next,
855
+ children: first.children
856
+ };
857
+ const [open] = sectionsBetween([first], [reprops]);
858
+ const [kept, ...tail] = sectionsBetween([reprops, ...rest], after);
859
+ if (open?.length !== 1 || !open.properties || !kept || kept.replacement || kept.properties) return {
860
+ blocks,
861
+ sections: blocks
862
+ };
863
+ return {
864
+ blocks,
865
+ sections: [
866
+ open,
867
+ ...kept.length > 1 ? [{ length: kept.length - 1 }] : [],
868
+ ...tail
869
+ ]
870
+ };
871
+ };
872
+ const pushWindow = (state, window, reading) => {
873
+ const owners = ownersOf(state, window.owners);
874
+ if (window.sections.reduce((sum, { length: size }) => sum + size, 0) !== window.before.to - window.before.from) throw new Error("A comparison plan window does not cover its range.");
875
+ if (owners.length === 0 && reading && (reading.before.text !== reading.after.text || changesMarks(reading.before, reading.after))) {
876
+ state.partitioned = false;
877
+ state.failures.push(`a residual window at ${window.root ?? "primary"}:${window.before.from} reads differently`);
878
+ }
879
+ state.windows.push(Object.freeze({
880
+ ...window,
881
+ owners
882
+ }));
883
+ };
884
+ const contentWindow = (state, input) => {
885
+ const beforeNodes = nodesOf(input.before);
886
+ const afterNodes = nodesOf(input.after);
887
+ const reading = {
888
+ after: readingOf(afterNodes),
889
+ before: readingOf(beforeNodes)
890
+ };
891
+ const addsOrRemoves = input.before.length !== input.after.length;
892
+ pushWindow(state, {
893
+ addsOrRemoves,
894
+ after: {
895
+ from: input.after[0]?.from ?? input.afterAt,
896
+ to: input.after.at(-1)?.to ?? input.afterAt
897
+ },
898
+ before: {
899
+ from: input.before[0]?.from ?? input.beforeAt,
900
+ to: input.before.at(-1)?.to ?? input.beforeAt
901
+ },
902
+ level: input.level,
903
+ marks: changesMarks(reading.before, reading.after),
904
+ owners: input.owners,
905
+ root: input.root,
906
+ ...recordableSections(beforeNodes.map(({ node }) => node), afterNodes.map(({ node }) => node)),
907
+ structural: addsOrRemoves || input.effects.some(({ kind }) => kind === "placement" || kind === "wrapper"),
908
+ text: reading.before.text !== reading.after.text
909
+ }, reading);
910
+ };
911
+ const unitsEqual = (before, after) => before.nodes.length === after.nodes.length && before.nodes.every((node, index) => node.canonical === after.nodes[index]?.canonical);
912
+ /** The pair's own groups whose effects explain a change no footprint claims. */
913
+ const explain = (pair, before, after) => {
914
+ if (!pair) return [];
915
+ const beforeReading = readingOf(before.nodes);
916
+ const afterReading = readingOf(after.nodes);
917
+ const text = beforeReading.text !== afterReading.text;
918
+ const marks = changesMarks(beforeReading, afterReading);
919
+ if (!text && !marks || text && pair.text.size === 0 || marks && pair.runs.size === 0) return [];
920
+ return [...text ? pair.text : [], ...marks ? pair.runs : []];
921
+ };
922
+ const truncate = (state, mark) => {
923
+ state.windows.length = mark[0];
924
+ state.requirements.length = mark[1];
925
+ state.failures.length = mark[2];
926
+ };
927
+ const markOf = (state) => [
928
+ state.windows.length,
929
+ state.requirements.length,
930
+ state.failures.length
931
+ ];
932
+ const elementPair = (state, root, level, before, after, footprints) => {
933
+ const isOwn = (footprint, node) => footprint.from === node.from && footprint.to === node.to;
934
+ const ownGroups = /* @__PURE__ */ new Set([...footprints.before.filter((footprint) => isOwn(footprint, before)).map(({ owner }) => owner), ...footprints.after.filter((footprint) => isOwn(footprint, after)).map(({ owner }) => owner)]);
935
+ const all = [...footprints.before, ...footprints.after];
936
+ const ownEffects = [...new Map(all.filter(({ owner }) => ownGroups.has(owner)).map(({ effect, owner }) => [effect.id, {
937
+ effect,
938
+ owner
939
+ }])).values()];
940
+ const inner = {
941
+ after: footprints.after.filter(({ owner }) => !ownGroups.has(owner)),
942
+ before: footprints.before.filter(({ owner }) => !ownGroups.has(owner))
943
+ };
944
+ const pairUnit = (node) => ({
945
+ element: node,
946
+ from: node.from,
947
+ nodes: [node],
948
+ to: node.to
949
+ });
950
+ const whole = () => contentWindow(state, {
951
+ after: [pairUnit(after)],
952
+ afterAt: after.from,
953
+ before: [pairUnit(before)],
954
+ beforeAt: before.from,
955
+ effects: all.map(({ effect }) => effect),
956
+ level,
957
+ owners: all.map(({ owner }) => owner),
958
+ root
959
+ });
960
+ if (!(ownEffects.every(({ effect }) => RECURSIVE_KINDS.has(effect.kind)) && (inner.before.length + inner.after.length > 0 || ownEffects.some(({ effect }) => changesOwnProps(effect))))) {
961
+ whole();
962
+ return;
963
+ }
964
+ const beforeUnits = unitsOf(state.index.before, before.childIndexes);
965
+ const afterUnits = unitsOf(state.index.after, after.childIndexes);
966
+ const textBlock = [before, after].some((node, side) => node.childIndexes.some((childIndex) => (side === 0 ? state.index.before : state.index.after).nodes[childIndex].kind === "text"));
967
+ const mark = markOf(state);
968
+ const fallback = (failure) => {
969
+ truncate(state, mark);
970
+ whole();
971
+ if (failure) state.failures.push(failure);
972
+ };
973
+ if (textBlock && beforeUnits.length !== afterUnits.length) {
974
+ whole();
975
+ return;
976
+ }
977
+ if (!jsonEqual(before.properties, after.properties)) {
978
+ const [open] = sectionsBetween([before.node], [{
979
+ ...after.node,
980
+ children: before.node.children
981
+ }]);
982
+ if (open?.length !== 1 || open.properties === void 0) {
983
+ fallback(`the open token at ${root ?? "primary"}:${before.from} is not one property section`);
984
+ return;
985
+ }
986
+ pushWindow(state, {
987
+ addsOrRemoves: false,
988
+ after: {
989
+ from: after.from,
990
+ to: after.from + 1
991
+ },
992
+ before: {
993
+ from: before.from,
994
+ to: before.from + 1
995
+ },
996
+ blocks: [open],
997
+ level,
998
+ marks: false,
999
+ owners: ownEffects.filter(({ effect }) => changesOwnProps(effect)).map(({ owner }) => owner),
1000
+ root,
1001
+ sections: [open],
1002
+ structural: false,
1003
+ text: false
1004
+ });
1005
+ }
1006
+ const descendantsFrom = state.windows.length;
1007
+ const childLevel = state.levels;
1008
+ state.levels += 1;
1009
+ if (!walkLevel(state, root, childLevel, {
1010
+ after: afterUnits,
1011
+ before: beforeUnits
1012
+ }, inner, {
1013
+ after: after.contentFrom,
1014
+ before: before.contentFrom
1015
+ }, {
1016
+ runs: new Set(ownEffects.filter(({ effect }) => changesRuns(effect)).map(({ owner }) => owner)),
1017
+ text: new Set(ownEffects.filter(({ effect }) => effect.kind === "text").map(({ owner }) => owner))
1018
+ })) {
1019
+ fallback(textBlock ? null : `the children of ${root ?? "primary"}:${before.from} do not tile`);
1020
+ return;
1021
+ }
1022
+ const descendants = state.windows.slice(descendantsFrom);
1023
+ const atLevel = descendants.filter((window) => window.level === childLevel);
1024
+ for (const { effect, owner } of ownEffects) {
1025
+ let targets;
1026
+ if (changesRuns(effect)) targets = descendants.filter(({ marks }) => marks);
1027
+ else if (effect.kind === "structure") targets = atLevel.filter(({ structural }) => structural);
1028
+ else if (effect.kind === "text") targets = descendants.filter(({ text }) => text);
1029
+ else continue;
1030
+ if (targets.length === 0) targets = atLevel.filter(({ addsOrRemoves }) => addsOrRemoves);
1031
+ if (targets.length === 0) targets = descendants;
1032
+ state.requirements.push([owner, targets.flatMap(({ owners }) => owners).filter((id) => id !== owner)]);
1033
+ }
1034
+ };
1035
+ const pairUnits = (state, root, level, before, after, footprints, pair) => {
1036
+ if (footprints.before.length + footprints.after.length === 0) {
1037
+ if (unitsEqual(before, after)) return;
1038
+ contentWindow(state, {
1039
+ after: [after],
1040
+ afterAt: after.from,
1041
+ before: [before],
1042
+ beforeAt: before.from,
1043
+ effects: [],
1044
+ level,
1045
+ owners: explain(pair, before, after),
1046
+ root
1047
+ });
1048
+ return;
1049
+ }
1050
+ if (before.element && after.element) {
1051
+ elementPair(state, root, level, before.element, after.element, footprints);
1052
+ return;
1053
+ }
1054
+ contentWindow(state, {
1055
+ after: [after],
1056
+ afterAt: after.from,
1057
+ before: [before],
1058
+ beforeAt: before.from,
1059
+ effects: [...footprints.before, ...footprints.after].map(({ effect }) => effect),
1060
+ level,
1061
+ owners: [...footprints.before, ...footprints.after].map(({ owner }) => owner),
1062
+ root
1063
+ });
1064
+ };
1065
+ const walkLevel = (state, root, level, units, footprints, at, pair) => {
1066
+ const before = classify(units.before, footprints.before);
1067
+ const after = classify(units.after, footprints.after);
1068
+ if (!before || !after) return false;
1069
+ const steps = alignLevel({
1070
+ classified: {
1071
+ after,
1072
+ before
1073
+ },
1074
+ described: state.described,
1075
+ root,
1076
+ units
1077
+ });
1078
+ if (!steps) return false;
1079
+ const position = (side, cursor) => units[side][cursor]?.from ?? units[side].at(-1)?.to ?? at[side];
1080
+ let beforeCursor = 0;
1081
+ let afterCursor = 0;
1082
+ for (const step of steps) {
1083
+ if (step.kind === "anchor") {
1084
+ const { anchor } = step;
1085
+ pairUnits(state, root, level, units.before[anchor.before], units.after[anchor.after], anchor.ranges ? {
1086
+ after: anchor.ranges.after.footprints,
1087
+ before: anchor.ranges.before.footprints
1088
+ } : {
1089
+ after: after.inside.get(anchor.after) ?? [],
1090
+ before: before.inside.get(anchor.before) ?? []
1091
+ }, pair);
1092
+ beforeCursor = anchor.before + 1;
1093
+ afterCursor = anchor.after + 1;
1094
+ continue;
1095
+ }
1096
+ const beforeUnits = step.before ? units.before.slice(step.before.start, step.before.end + 1) : [];
1097
+ const afterUnits = step.after ? units.after.slice(step.after.start, step.after.end + 1) : [];
1098
+ const [onlyBefore] = beforeUnits;
1099
+ const [onlyAfter] = afterUnits;
1100
+ const found = [...step.footprints.before, ...step.footprints.after];
1101
+ if (beforeUnits.length === 1 && afterUnits.length === 1 && onlyBefore?.element && onlyAfter?.element) elementPair(state, root, level, onlyBefore.element, onlyAfter.element, step.footprints);
1102
+ else contentWindow(state, {
1103
+ after: afterUnits,
1104
+ afterAt: position("after", afterCursor),
1105
+ before: beforeUnits,
1106
+ beforeAt: position("before", beforeCursor),
1107
+ effects: found.map(({ effect }) => effect),
1108
+ level,
1109
+ owners: found.map(({ owner }) => owner),
1110
+ root
1111
+ });
1112
+ if (step.before) beforeCursor = step.before.end + 1;
1113
+ if (step.after) afterCursor = step.after.end + 1;
1114
+ }
1115
+ return true;
1116
+ };
1117
+ const rootChildren = (document, root) => root === null ? document.children : document.roots?.[root] ?? [];
1118
+ const walkPlan = (input) => {
1119
+ const { after, afterIndex, before, beforeIndex, groups } = input;
1120
+ const state = {
1121
+ described: describedPairsOf(groups),
1122
+ failures: [],
1123
+ groupOrder: new Map(groups.map(({ id }, index) => [id, index])),
1124
+ index: {
1125
+ after: afterIndex,
1126
+ before: beforeIndex
1127
+ },
1128
+ levels: 0,
1129
+ partitioned: true,
1130
+ requirements: [],
1131
+ windows: []
1132
+ };
1133
+ const footprints = {
1134
+ after: /* @__PURE__ */ new Map(),
1135
+ before: /* @__PURE__ */ new Map()
1136
+ };
1137
+ for (const group of groups) for (const effect of group.effects) for (const side of ["before", "after"]) for (const span of effect[side]) {
1138
+ const list = footprints[side].get(span.root) ?? [];
1139
+ list.push({
1140
+ effect,
1141
+ from: span.from,
1142
+ owner: group.id,
1143
+ to: span.to
1144
+ });
1145
+ footprints[side].set(span.root, list);
1146
+ }
1147
+ const beforeRoots = Object.keys(before.roots ?? {});
1148
+ const afterRoots = Object.keys(after.roots ?? {});
1149
+ const roots = [null, ...[.../* @__PURE__ */ new Set([...beforeRoots, ...afterRoots])].toSorted()];
1150
+ const lifecycle = [];
1151
+ for (const root of roots) {
1152
+ const inBefore = root === null || Object.hasOwn(before.roots ?? {}, root);
1153
+ const inAfter = root === null || Object.hasOwn(after.roots ?? {}, root);
1154
+ const found = {
1155
+ after: footprints.after.get(root) ?? [],
1156
+ before: footprints.before.get(root) ?? []
1157
+ };
1158
+ const everyOwner = [...found.before, ...found.after].map(({ owner }) => owner);
1159
+ const wholeRoot = () => {
1160
+ const beforeLength = beforeIndex.roots.get(root)?.length ?? 0;
1161
+ const afterLength = afterIndex.roots.get(root)?.length ?? 0;
1162
+ const afterChildren = inAfter ? rootChildren(after, root) : [];
1163
+ pushWindow(state, {
1164
+ addsOrRemoves: true,
1165
+ after: {
1166
+ from: 0,
1167
+ to: inAfter ? afterLength : 0
1168
+ },
1169
+ before: {
1170
+ from: 0,
1171
+ to: inBefore ? beforeLength : 0
1172
+ },
1173
+ blocks: replaceAll(inBefore ? beforeLength : 0, afterChildren),
1174
+ level: -1,
1175
+ marks: true,
1176
+ owners: everyOwner,
1177
+ root,
1178
+ sections: sectionsBetween(inBefore ? rootChildren(before, root) : [], afterChildren),
1179
+ structural: true,
1180
+ text: true
1181
+ });
1182
+ };
1183
+ if (root !== null && inBefore !== inAfter) {
1184
+ wholeRoot();
1185
+ lifecycle.push({
1186
+ kind: inAfter ? "create" : "delete",
1187
+ owners: ownersOf(state, everyOwner),
1188
+ root
1189
+ });
1190
+ continue;
1191
+ }
1192
+ const mark = markOf(state);
1193
+ const level = state.levels;
1194
+ state.levels += 1;
1195
+ if (!walkLevel(state, root, level, {
1196
+ after: unitsOf(afterIndex, afterIndex.roots.get(root)?.topLevelIndexes ?? []),
1197
+ before: unitsOf(beforeIndex, beforeIndex.roots.get(root)?.topLevelIndexes ?? [])
1198
+ }, found, {
1199
+ after: 0,
1200
+ before: 0
1201
+ }, null)) {
1202
+ truncate(state, mark);
1203
+ wholeRoot();
1204
+ state.failures.push(`the top level of ${root ?? "primary"} does not tile`);
1205
+ }
1206
+ }
1207
+ const required = new Map(groups.map(({ id, requiredChangeIds }) => [id, new Set(requiredChangeIds)]));
1208
+ const owning = /* @__PURE__ */ new Set();
1209
+ const requiring = /* @__PURE__ */ new Set();
1210
+ for (const { owners } of [...state.windows, ...lifecycle]) {
1211
+ const [hub, ...others] = owners;
1212
+ for (const owner of owners) owning.add(owner);
1213
+ for (const other of others) {
1214
+ required.get(hub)?.add(other);
1215
+ required.get(other)?.add(hub);
1216
+ }
1217
+ }
1218
+ for (const [owner, ids] of state.requirements) {
1219
+ if (ids.length > 0) requiring.add(owner);
1220
+ for (const id of ids) required.get(owner)?.add(id);
1221
+ }
1222
+ for (const { id } of groups) if (!owning.has(id) && !requiring.has(id)) state.failures.push(`group ${id} owns no window and requires none`);
1223
+ if (lawCheckEnabled() && state.failures.length > 0) throw new Error(`Comparison plan invariant failed: ${state.failures.join("; ")}.`);
1224
+ const windows = Object.freeze(state.windows);
1225
+ const select = (ids, form = "sections") => {
1226
+ const keep = (owners) => ids === "all" || owners.length > 0 && owners.every((id) => ids.has(id));
1227
+ const rootJson = (root) => {
1228
+ const kept = windows.filter((window) => window.root === root && keep(window.owners));
1229
+ if (kept.length === 0) return void 0;
1230
+ const length = beforeIndex.roots.get(root)?.length ?? 0;
1231
+ const sections = [];
1232
+ let cursor = 0;
1233
+ for (const window of kept) {
1234
+ if (window.before.from < cursor) throw new Error("Comparison plan windows overlap.");
1235
+ if (window.before.from > cursor) sections.push({ length: window.before.from - cursor });
1236
+ sections.push(...window[form]);
1237
+ cursor = window.before.to;
1238
+ }
1239
+ if (length > cursor) sections.push({ length: length - cursor });
1240
+ return sections;
1241
+ };
1242
+ const primary = rootJson(null);
1243
+ const named = roots.flatMap((root) => {
1244
+ const json = root === null ? void 0 : rootJson(root);
1245
+ return root !== null && json ? [[root, json]] : [];
1246
+ });
1247
+ const flags = (kind) => lifecycle.filter((flag) => flag.kind === kind && keep(flag.owners)).map(({ root }) => root);
1248
+ const createRoots = flags("create");
1249
+ const deleteRoots = flags("delete");
1250
+ const json = {
1251
+ ...createRoots.length > 0 ? { createRoots } : {},
1252
+ ...deleteRoots.length > 0 ? { deleteRoots } : {},
1253
+ ...primary ? { primary } : {},
1254
+ ...named.length > 0 ? { roots: Object.fromEntries(named) } : {},
1255
+ version: 3
1256
+ };
1257
+ return DocumentChange.fromJSON(json);
1258
+ };
1259
+ const change = select("all");
1260
+ return Object.freeze({
1261
+ change,
1262
+ changes: cloneFrozen(groups.map((group) => ({
1263
+ ...group,
1264
+ requiredChangeIds: ownersOf(state, [...required.get(group.id) ?? []].filter((id) => id !== group.id))
1265
+ }))),
1266
+ lifecycle: Object.freeze(lifecycle),
1267
+ partitioned: state.partitioned,
1268
+ select,
1269
+ windows
1270
+ });
1271
+ };
1272
+ const mergeTied = (groups, ties) => {
1273
+ const indexOf = new Map(groups.map(({ id }, index) => [id, index]));
1274
+ const { find, join } = disjointSets(groups.length);
1275
+ for (const owners of ties) {
1276
+ const [first, ...rest] = owners.flatMap((id) => {
1277
+ const at = indexOf.get(id);
1278
+ return at === void 0 ? [] : [at];
1279
+ });
1280
+ for (const member of rest) join(first, member);
1281
+ }
1282
+ const sets = /* @__PURE__ */ new Map();
1283
+ groups.forEach((_group, index) => {
1284
+ const root = find(index);
1285
+ const set = sets.get(root);
1286
+ if (set) set.push(index);
1287
+ else sets.set(root, [index]);
1288
+ });
1289
+ return mergeGroups(groups, [...sets.values()].filter((members) => members.length > 1).map((members) => ({
1290
+ members,
1291
+ owner: members[0]
1292
+ })));
1293
+ };
1294
+ const planComparison = (input) => {
1295
+ let { groups } = input;
1296
+ for (;;) {
1297
+ const plan = walkPlan({
1298
+ ...input,
1299
+ groups
1300
+ });
1301
+ const ties = movedWordTies(plan.windows, plan.changes, input.beforeIndex, input.afterIndex);
1302
+ if (ties.length === 0) {
1303
+ PLANS.set(plan.change, plan);
1304
+ return plan;
1305
+ }
1306
+ groups = mergeTied(groups, ties);
1307
+ }
1308
+ };
1309
+ const sameChanges = (plan, changes) => plan.changes === changes || jsonEqual(plan.changes, changes);
1310
+ const comparisonPlanOf = (comparison, schema) => {
1311
+ const cached = PLANS.get(comparison.change);
1312
+ if (cached && sameChanges(cached, comparison.changes)) return cached;
1313
+ try {
1314
+ const afterIndex = createComparisonIndex(comparison.after.document, schema);
1315
+ const beforeIndex = createComparisonIndex(comparison.before.document, schema);
1316
+ const plan = planComparison({
1317
+ after: comparison.after.document,
1318
+ afterIndex,
1319
+ before: comparison.before.document,
1320
+ beforeIndex,
1321
+ groups: comparison.changes
1322
+ });
1323
+ if (!jsonEqual(plan.change.toJSON(), comparison.change.toJSON()) || !sameChanges(plan, comparison.changes)) return null;
1324
+ PLANS.set(comparison.change, plan);
1325
+ return plan;
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ };
1330
+ /** `ids` and every group they require, transitively. */
1331
+ const closeOverRequired = (groups, ids) => {
1332
+ const byId = new Map(groups.map((group) => [group.id, group]));
1333
+ const closed = new Set(ids);
1334
+ for (const id of closed) for (const required of byId.get(id)?.requiredChangeIds ?? []) closed.add(required);
1335
+ return closed;
1336
+ };
1337
+ //#endregion
1338
+ export { fingerprintEditorJson as S, mergeGroups as _, comparisonTextRuns as a, uniqueSpans as b, COMPARISON_POLICY as c, comparisonDocumentsEqual as d, comparisonHash as f, disjointSets as g, detachComparisonEnvelope as h, comparisonTextPoint as i, COMPARISON_WORD as l, detachComparisonDocument as m, comparisonPlanOf as n, comparisonTextSpans as o, createComparisonSnapshot as p, planComparison as r, createComparisonIndex as s, closeOverRequired as t, assertComparisonActive as u, spanKey$1 as v, yieldComparisonWork as x, stableStringify as y };